From 55e3d2f687f4ed9653982dbda92c6a055b0a8350 Mon Sep 17 00:00:00 2001 From: Apple Date: Tue, 25 Aug 2009 00:11:40 +0000 Subject: [PATCH] ld64-95.2.12.tar.gz --- APPLE_LICENSE | 0 ChangeLog | 4666 +++++++++++++++-- doc/man/man1/dyldinfo.1 | 47 + doc/man/man1/ld.1 | 56 +- doc/man/man1/ld64.1 | 0 doc/man/man1/rebase.1 | 0 doc/man/man1/unwinddump.1 | 22 + ld64.xcodeproj/project.pbxproj | 494 +- src/{ => abstraction}/FileAbstraction.hpp | 0 .../MachOFileAbstraction.hpp | 299 +- src/abstraction/MachOTrie.hpp | 320 ++ src/{ => ld}/Architectures.hpp | 18 +- src/{ => ld}/ArchiveReader.hpp | 45 +- src/{ => ld}/ExecutableFile.h | 8 +- src/{ => ld}/LTOReader.hpp | 115 +- src/{ => ld}/MachOReaderDylib.hpp | 156 +- src/{ => ld}/MachOReaderRelocatable.hpp | 1694 +++++- src/{ => ld}/MachOWriterExecutable.hpp | 4064 ++++++++++++-- src/{ => ld}/ObjectFile.h | 58 +- src/{ => ld}/OpaqueSection.hpp | 0 src/{ => ld}/Options.cpp | 620 ++- src/{ => ld}/Options.h | 57 +- src/{ => ld}/SectCreate.h | 0 src/{ => ld}/debugline.c | 3 +- src/{ => ld}/debugline.h | 0 src/{ => ld}/dwarf2.h | 5 + src/{ => ld}/ld.cpp | 990 ++-- src/{ => other}/ObjectDump.cpp | 23 +- src/other/PruneTrie.cpp | 100 + src/other/dyldinfo.cpp | 1460 ++++++ src/{ => other}/machochecker.cpp | 22 +- src/other/prune_trie.h | 54 + src/{ => other}/rebase.cpp | 196 +- src/other/unwinddump.cpp | 926 ++++ unit-tests/README | 0 unit-tests/include/common.makefile | 73 +- unit-tests/include/test.h | 0 unit-tests/run-all-unit-tests | 7 +- unit-tests/src/Makefile | 0 unit-tests/src/results-to-xml.cpp | 0 unit-tests/src/xmlparser/xmlparser.1 | 0 unit-tests/src/xmlparser/xmlparser.m | 0 .../xmlparser.xcodeproj/project.pbxproj | 0 unit-tests/src/xmlparser/xmlparser_Prefix.pch | 0 .../test-cases/16-byte-alignment/Makefile | 0 .../test-cases/16-byte-alignment/comment.txt | 0 .../test-cases/16-byte-alignment/tl_test2.c | 0 .../test-cases/absolute-symbol/Makefile | 0 unit-tests/test-cases/absolute-symbol/abs.s | 0 unit-tests/test-cases/absolute-symbol/main.c | 0 .../test-cases/alias-command-line/Makefile | 0 .../test-cases/alias-command-line/aliases.s | 0 .../test-cases/alias-command-line/aliases.txt | 0 unit-tests/test-cases/alias-objects/Makefile | 0 unit-tests/test-cases/alias-objects/aliases.s | 0 unit-tests/test-cases/align-modulus/Makefile | 0 unit-tests/test-cases/align-modulus/align.s | 0 .../test-cases/align-modulus/comment.txt | 0 unit-tests/test-cases/align-modulus/foo.c | 0 unit-tests/test-cases/align-modulus/foo.exp | 0 .../test-cases/allow-stack-execute/Makefile | 0 .../allow-stack-execute/comment.txt | 0 .../test-cases/allow-stack-execute/foo.c | 0 .../test-cases/allowable-client/Makefile | 0 unit-tests/test-cases/allowable-client/bar.c | 0 unit-tests/test-cases/allowable-client/baz.c | 0 .../test-cases/allowable-client/comment.txt | 0 unit-tests/test-cases/allowable-client/foo.c | 0 unit-tests/test-cases/allowable-client/main.c | 0 unit-tests/test-cases/archive-ObjC/Makefile | 0 unit-tests/test-cases/archive-ObjC/bar.c | 0 unit-tests/test-cases/archive-ObjC/baz.m | 0 unit-tests/test-cases/archive-ObjC/foo.m | 0 unit-tests/test-cases/archive-ObjC/main.c | 0 unit-tests/test-cases/archive-basic/Makefile | 0 unit-tests/test-cases/archive-basic/bar.c | 0 .../test-cases/archive-basic/comment.txt | 0 unit-tests/test-cases/archive-basic/foo.c | 0 unit-tests/test-cases/archive-basic/main.c | 0 .../test-cases/archive-duplicate/Makefile | 0 unit-tests/test-cases/archive-duplicate/bar.c | 0 unit-tests/test-cases/archive-duplicate/foo.c | 0 .../test-cases/archive-duplicate/main.c | 0 .../test-cases/archive-force-load/Makefile | 48 + .../test-cases/archive-force-load/bar.c | 1 + .../test-cases/archive-force-load/bat.c | 1 + .../test-cases/archive-force-load/baz.c | 2 + .../test-cases/archive-force-load/foo.c | 1 + .../test-cases/archive-force-load/main.c | 5 + unit-tests/test-cases/archive-weak/Makefile | 0 unit-tests/test-cases/archive-weak/bar.c | 0 unit-tests/test-cases/archive-weak/baz.c | 0 .../test-cases/archive-weak/comment.txt | 0 unit-tests/test-cases/archive-weak/foo.c | 0 unit-tests/test-cases/archive-weak/main.c | 0 unit-tests/test-cases/auto-arch/Makefile | 0 unit-tests/test-cases/auto-arch/hello.c | 0 unit-tests/test-cases/blank-stubs/Makefile | 0 unit-tests/test-cases/blank-stubs/comment.txt | 0 unit-tests/test-cases/blank-stubs/foo.c | 0 unit-tests/test-cases/blank-stubs/main.c | 0 .../test-cases/branch-distance/Makefile | 44 + unit-tests/test-cases/branch-distance/bar.s | 21 + unit-tests/test-cases/branch-distance/foo.s | 33 + unit-tests/test-cases/branch-islands/Makefile | 0 unit-tests/test-cases/branch-islands/extra.c | 0 unit-tests/test-cases/branch-islands/hello.c | 0 unit-tests/test-cases/branch-islands/space.s | 0 unit-tests/test-cases/bundle_loader/Makefile | 0 unit-tests/test-cases/bundle_loader/bar.c | 0 unit-tests/test-cases/bundle_loader/bundle.c | 0 unit-tests/test-cases/bundle_loader/main.c | 0 .../test-cases/cfstring-coalesce/Makefile | 10 +- unit-tests/test-cases/cfstring-coalesce/bar.c | 1 + unit-tests/test-cases/cfstring-coalesce/foo.c | 3 + unit-tests/test-cases/cfstring-utf16/Makefile | 0 unit-tests/test-cases/cfstring-utf16/bar.m | 0 unit-tests/test-cases/cfstring-utf16/foo.m | 0 .../coalesce_weak_def_in_dylib/Makefile | 55 + .../coalesce_weak_def_in_dylib/foo.c | 4 + .../coalesce_weak_def_in_dylib/main.c | 17 + .../code-signed-object-file/Makefile | 26 + .../test-cases/code-signed-object-file/foo.c | 1 + .../test-cases/commons-alignment/Makefile | 0 unit-tests/test-cases/commons-alignment/foo.s | 0 .../commons-coalesced-dead_strip/Makefile | 0 .../commons-coalesced-dead_strip/a.c | 0 .../commons-coalesced-dead_strip/b.c | 0 .../commons-coalesced-dead_strip/c.c | 0 .../commons-coalesced-dead_strip/c.h | 0 unit-tests/test-cases/commons-mixed/Makefile | 0 unit-tests/test-cases/commons-mixed/bar.c | 0 unit-tests/test-cases/commons-mixed/foo.c | 0 unit-tests/test-cases/commons-order/Makefile | 0 unit-tests/test-cases/commons-order/bar.c | 0 unit-tests/test-cases/commons-order/baz.c | 0 .../test-cases/commons-order/expected.order | 0 unit-tests/test-cases/commons-order/foo.c | 0 unit-tests/test-cases/commons-order/main.c | 0 .../cpu-sub-types-preference/Makefile | 0 .../test-cases/cpu-sub-types-preference/foo.c | 0 unit-tests/test-cases/cpu-sub-types/Makefile | 0 .../test-cases/cpu-sub-types/comment.txt | 0 unit-tests/test-cases/cpu-sub-types/foo.c | 0 unit-tests/test-cases/cpu-sub-types/main.c | 0 .../test-cases/cstring-alt-segment/Makefile | 39 + .../test-cases/cstring-alt-segment/custom.s | 8 + .../test-cases/cstring-alt-segment/main.c | 7 + .../cstring-custom-section/Makefile | 47 + .../test-cases/cstring-custom-section/bar.s | 31 + .../test-cases/cstring-custom-section/foo.s | 31 + unit-tests/test-cases/cstring-labels/Makefile | 56 + unit-tests/test-cases/cstring-labels/bar.c | 2 + unit-tests/test-cases/cstring-labels/foo.c | 6 + .../Makefile | 31 +- .../test-cases/dead_strip-archive-eh/bar.cxx | 14 + .../test-cases/dead_strip-archive-eh/foo.cxx | 13 + .../test-cases/dead_strip-archive-eh/main.cxx | 12 + .../dead_strip-archive-global/Makefile | 0 .../dead_strip-archive-global/foo.c | 0 .../dead_strip-archive-global/main.c | 0 .../dead_strip-archive-weak/Makefile | 44 + .../test-cases/dead_strip-archive-weak/foo.c | 13 + .../test-cases/dead_strip-archive-weak/main.c | 27 + .../test-cases/dead_strip-archive/Makefile | 0 .../test-cases/dead_strip-archive/comment.txt | 0 .../test-cases/dead_strip-archive/foo.c | 0 .../test-cases/dead_strip-archive/main.c | 0 .../dead_strip-init-archive/Makefile | 0 .../test-cases/dead_strip-init-archive/bar.c | 0 .../test-cases/dead_strip-init-archive/foo.c | 0 .../dead_strip-r_symbol_desc/Makefile | 43 + .../main.c} | 24 +- .../dead_strip-weak-coalesce/Makefile | 41 + .../test-cases/dead_strip-weak-coalesce/baz.c | 7 + .../test-cases/dead_strip-weak-coalesce/foo.c | 25 + .../dead_strip-weak-coalesce/main.c | 13 + unit-tests/test-cases/dead_strip/Makefile | 0 unit-tests/test-cases/dead_strip/comment.txt | 0 unit-tests/test-cases/dead_strip/deadwood.c | 0 unit-tests/test-cases/dead_strip/main.c | 0 unit-tests/test-cases/dead_strip/main.exp | 0 .../test-cases/dead_strip_dylibs/Makefile | 0 unit-tests/test-cases/dead_strip_dylibs/bar.c | 0 unit-tests/test-cases/dead_strip_dylibs/baz.c | 0 unit-tests/test-cases/dead_strip_dylibs/foo.c | 0 .../test-cases/dead_strip_dylibs/main.c | 0 .../dead_strip_section_attribute/Makefile | 0 .../dead_strip_section_attribute/comment.txt | 0 .../dead_strip_section_attribute/main.c | 0 .../test-cases/dead_strippable_dylib/Makefile | 50 + .../test-cases/dead_strippable_dylib/bar.c | 5 + .../test-cases/dead_strippable_dylib/baz.c | 5 + .../test-cases/dead_strippable_dylib/foo.c | 4 + .../test-cases/dead_strippable_dylib/main.c | 8 + .../dtrace-static-probes-coalescing/Makefile | 0 .../dtrace-static-probes-coalescing/Number.d | 0 .../dtrace-static-probes-coalescing/a.cxx | 0 .../dtrace-static-probes-coalescing/header.h | 0 .../dtrace-static-probes-coalescing/x.cxx | 0 .../test-cases/dtrace-static-probes/Makefile | 0 .../test-cases/dtrace-static-probes/bar.d | 0 .../dtrace-static-probes/comment.txt | 0 .../test-cases/dtrace-static-probes/foo.d | 0 .../test-cases/dtrace-static-probes/main.c | 9 +- .../dwarf-archive-all_load/Makefile | 4 +- .../test-cases/dwarf-archive-all_load/bar.c | 0 .../test-cases/dwarf-archive-all_load/baz.c | 0 .../dwarf-archive-all_load/comment.txt | 0 .../dwarf-archive-all_load/expected-stabs | 0 .../test-cases/dwarf-archive-all_load/foo.c | 0 .../test-cases/dwarf-debug-notes-r/Makefile | 0 .../test-cases/dwarf-debug-notes-r/bar.cxx | 0 .../dwarf-debug-notes-r/comment.txt | 0 .../dwarf-debug-notes-r/expected-stabs | 0 .../test-cases/dwarf-debug-notes-r/foo.cxx | 0 .../test-cases/dwarf-debug-notes-r/main.cxx | 0 .../test-cases/dwarf-debug-notes/Makefile | 0 .../test-cases/dwarf-debug-notes/comment.txt | 0 .../dwarf-debug-notes/expected-stabs | 6 +- .../test-cases/dwarf-debug-notes/header.h | 0 .../test-cases/dwarf-debug-notes/hello.cxx | 0 .../test-cases/dwarf-debug-notes/other.cxx | 0 unit-tests/test-cases/dwarf-ignore/Makefile | 0 .../test-cases/dwarf-ignore/comment.txt | 0 unit-tests/test-cases/dwarf-ignore/hello.c | 0 unit-tests/test-cases/dwarf-strip/Makefile | 0 unit-tests/test-cases/dwarf-strip/comment.txt | 0 unit-tests/test-cases/dwarf-strip/hello.c | 0 unit-tests/test-cases/dylib-aliases/Makefile | 0 unit-tests/test-cases/dylib-aliases/bar.c | 0 unit-tests/test-cases/dylib-aliases/foo.c | 0 unit-tests/test-cases/dylib-aliases/main.c | 0 .../test-cases/dylib-re-export-cycle/Makefile | 0 .../test-cases/dylib-re-export-cycle/bar.c | 0 .../test-cases/dylib-re-export-cycle/foo.c | 0 .../test-cases/dylib-re-export-cycle/main.c | 0 .../test-cases/dylib_file-missing/Makefile | 0 .../test-cases/dylib_file-missing/bar.c | 0 .../test-cases/dylib_file-missing/foo.c | 0 .../test-cases/dylib_file-missing/main.c | 0 unit-tests/test-cases/dylib_file/Makefile | 0 unit-tests/test-cases/dylib_file/bar.c | 0 unit-tests/test-cases/dylib_file/comment.txt | 0 unit-tests/test-cases/dylib_file/foo.c | 0 unit-tests/test-cases/dylib_file/main.c | 0 unit-tests/test-cases/dylib_init/Makefile | 0 unit-tests/test-cases/dylib_init/foo.c | 0 .../eh-coalescing-no-labels/Makefile | 51 + .../test-cases/eh-coalescing-no-labels/bar.c | 18 + .../test-cases/eh-coalescing-no-labels/baz.c | 18 + .../test-cases/eh-coalescing-no-labels/foo.c | 18 + .../test-cases/eh-coalescing-r/Makefile | 0 unit-tests/test-cases/eh-coalescing-r/bar.cxx | 0 unit-tests/test-cases/eh-coalescing-r/baz.cxx | 32 + unit-tests/test-cases/eh-coalescing-r/foo.cxx | 0 unit-tests/test-cases/eh-coalescing-r/func.h | 0 unit-tests/test-cases/eh-coalescing/Makefile | 0 unit-tests/test-cases/eh-coalescing/bar.cxx | 0 unit-tests/test-cases/eh-coalescing/foo.cxx | 0 unit-tests/test-cases/eh-coalescing/foo2.cxx | 0 unit-tests/test-cases/eh-coalescing/func.h | 0 unit-tests/test-cases/eh-strip-test/Makefile | 0 .../test-cases/eh-strip-test/comment.txt | 0 unit-tests/test-cases/eh-strip-test/main.cxx | 0 .../test-cases/eh-stripped-symbols/Makefile | 23 + .../test-cases/eh-stripped-symbols/keep.exp | 3 + .../test-cases/eh-stripped-symbols/main.cxx | 52 + unit-tests/test-cases/eh_frame/Makefile | 1 + unit-tests/test-cases/eh_frame/bar.cxx | 0 unit-tests/test-cases/eh_frame/foo.cxx | 0 unit-tests/test-cases/empty-object/Makefile | 0 unit-tests/test-cases/empty-object/main.c | 0 unit-tests/test-cases/end-label/Makefile | 0 unit-tests/test-cases/end-label/bar.s | 0 unit-tests/test-cases/end-label/foo.s | 2 + .../Makefile | 0 .../foo.c | 0 .../exported-symbols-wildcards/Makefile | 24 +- .../exported-symbols-wildcards/expect1 | 0 .../exported-symbols-wildcards/expect2 | 0 .../exported-symbols-wildcards/expect3 | 0 .../exported-symbols-wildcards/expect4 | 0 .../exported-symbols-wildcards/expect5 | 0 .../exported-symbols-wildcards/expect6 | 0 .../exported-symbols-wildcards/expect7 | 0 .../exported-symbols-wildcards/expect8 | 0 .../exported-symbols-wildcards/foo.c | 0 .../exported-symbols-wildcards/list5 | 0 .../exported_symbols_list-eol/Makefile | 4 +- .../exported_symbols_list-eol/expected.nm | 0 .../exported_symbols_list-eol/test.c | 0 .../exported_symbols_list-eol/test.exp | 0 .../exported_symbols_list-hidden/Makefile | 0 .../exported_symbols_list-hidden/test.c | 0 .../exported_symbols_list-hidden/test.exp | 0 .../exported_symbols_list-r/Makefile | 0 .../exported_symbols_list-r/test-bad.exp | 0 .../test-cases/exported_symbols_list-r/test.c | 0 .../exported_symbols_list-r/test.exp | 0 .../external-reloc-sorting/Makefile | 0 .../test-cases/external-reloc-sorting/foo.c | 0 .../test-cases/external-reloc-sorting/main.c | 0 unit-tests/test-cases/filelist/Makefile | 24 +- unit-tests/test-cases/filelist/comment.txt | 0 unit-tests/test-cases/filelist/hello.c | 0 unit-tests/test-cases/flat-dylib/Makefile | 0 unit-tests/test-cases/flat-dylib/main.c | 0 .../flat-indirect-undefines/Makefile | 0 .../test-cases/flat-indirect-undefines/bar.c | 0 .../test-cases/flat-indirect-undefines/foo.c | 0 .../test-cases/flat-indirect-undefines/main.c | 0 unit-tests/test-cases/flat-main/Makefile | 0 unit-tests/test-cases/flat-main/main.c | 0 .../test-cases/got-elimination/Makefile | 4 +- unit-tests/test-cases/got-elimination/bar.c | 0 unit-tests/test-cases/got-elimination/foo.c | 0 unit-tests/test-cases/header-pad/Makefile | 0 unit-tests/test-cases/header-pad/comment.txt | 0 unit-tests/test-cases/header-pad/hello.c | 0 unit-tests/test-cases/hello-world/Makefile | 0 unit-tests/test-cases/hello-world/comment.txt | 0 unit-tests/test-cases/hello-world/hello.c | 0 .../implicit-common2/Makefile.newtest | 0 unit-tests/test-cases/implicit-common2/a.c | 0 .../test-cases/implicit-common2/comment.txt | 0 unit-tests/test-cases/implicit-common2/test.c | 0 unit-tests/test-cases/implicit-common3/a.c | 8 - .../test-cases/implicit-common3/comment.txt | 1 - .../implicit-common4/Makefile.newtest | 0 unit-tests/test-cases/implicit-common4/a.c | 0 .../test-cases/implicit-common4/comment.txt | 0 unit-tests/test-cases/implicit-common4/test.c | 0 .../implicit-common5/Makefile.newtest | 0 unit-tests/test-cases/implicit-common5/a.c | 0 .../test-cases/implicit-common5/comment.txt | 0 unit-tests/test-cases/implicit-common5/test.c | 0 unit-tests/test-cases/implicit_dylib/Makefile | 0 unit-tests/test-cases/implicit_dylib/bar.c | 0 unit-tests/test-cases/implicit_dylib/foo.c | 0 unit-tests/test-cases/implicit_dylib/main.c | 0 unit-tests/test-cases/indirect-dylib/Makefile | 2 +- unit-tests/test-cases/indirect-dylib/bar.c | 0 .../test-cases/indirect-dylib/comment.txt | 0 unit-tests/test-cases/indirect-dylib/foo.c | 0 unit-tests/test-cases/indirect-dylib/main.c | 0 .../test-cases/indirect-path-search/Makefile | 0 .../test-cases/indirect-path-search/bar.c | 0 .../test-cases/indirect-path-search/baz.c | 0 .../test-cases/indirect-path-search/foo.c | 0 .../test-cases/indirect-path-search/main.c | 0 unit-tests/test-cases/init-order/Makefile | 42 + unit-tests/test-cases/init-order/bar.cxx | 16 + .../test-cases/init-order/expected-order.txt | 20 + unit-tests/test-cases/init-order/foo.cxx | 14 + unit-tests/test-cases/init-order/main.cxx | 18 + .../test-cases/interposable_list/Makefile | 0 .../test-cases/interposable_list/test.c | 0 .../test-cases/interposable_list/test.exp | 0 unit-tests/test-cases/kext-basic/Makefile | 29 + unit-tests/test-cases/kext-basic/mykext.c | 18 + unit-tests/test-cases/kext-basic/mykextinfo.c | 12 + unit-tests/test-cases/large-data/Makefile | 0 unit-tests/test-cases/large-data/test1.c | 0 unit-tests/test-cases/large-data/test2.c | 0 unit-tests/test-cases/large-data/test3.c | 0 unit-tests/test-cases/large-data/test4.c | 0 .../test-cases/late-link-error/Makefile | 0 .../test-cases/late-link-error/comment.txt | 0 .../test-cases/late-link-error/link_error.s | 0 .../test-cases/lazy-dylib-objc/Makefile | 0 unit-tests/test-cases/lazy-dylib-objc/foo.h | 0 unit-tests/test-cases/lazy-dylib-objc/foo.m | 0 unit-tests/test-cases/lazy-dylib-objc/main.m | 0 unit-tests/test-cases/lazy-dylib/Makefile | 0 unit-tests/test-cases/lazy-dylib/bad.c | 0 unit-tests/test-cases/lazy-dylib/bad2.c | 0 unit-tests/test-cases/lazy-dylib/foo.c | 0 unit-tests/test-cases/lazy-dylib/main.c | 0 .../literals-coalesce-alignment/Makefile | 0 .../cstring-align-0.s | 0 .../cstring-align-3.s | 0 .../literals-coalesce-alignment2/Makefile | 0 .../literals-coalesce-alignment2/comment.txt | 0 .../cstring-align-0.s | 0 .../cstring-align-3.s | 0 .../literals-coalesce-alignment3/Makefile | 0 .../literals-coalesce-alignment3/comment.txt | 0 .../cstring-align-0.s | 0 .../cstring-align-3.s | 0 .../test-cases/literals-coalesce/Makefile | 0 .../test-cases/literals-coalesce/literals.s | 0 .../literals-coalesce2/Makefile.newtest | 0 .../test-cases/literals-coalesce2/comment.txt | 0 .../test-cases/literals-coalesce2/literals.s | 0 .../test-cases/llvm-integration/Makefile | 22 +- unit-tests/test-cases/llvm-integration/a.c | 0 unit-tests/test-cases/llvm-integration/a1.c | 0 unit-tests/test-cases/llvm-integration/a10.c | 0 unit-tests/test-cases/llvm-integration/a11.c | 0 unit-tests/test-cases/llvm-integration/a12.c | 0 unit-tests/test-cases/llvm-integration/a12.h | 0 unit-tests/test-cases/llvm-integration/a13.cc | 0 unit-tests/test-cases/llvm-integration/a13.h | 0 unit-tests/test-cases/llvm-integration/a14.c | 0 unit-tests/test-cases/llvm-integration/a15.c | 0 unit-tests/test-cases/llvm-integration/a17.c | 0 unit-tests/test-cases/llvm-integration/a18.c | 0 unit-tests/test-cases/llvm-integration/a2.c | 0 unit-tests/test-cases/llvm-integration/a20.c | 0 unit-tests/test-cases/llvm-integration/a3.c | 0 unit-tests/test-cases/llvm-integration/a4.c | 0 unit-tests/test-cases/llvm-integration/a5.c | 0 unit-tests/test-cases/llvm-integration/a6.c | 0 unit-tests/test-cases/llvm-integration/a7.c | 0 unit-tests/test-cases/llvm-integration/a8.c | 0 unit-tests/test-cases/llvm-integration/a9.c | 0 .../test-cases/llvm-integration/a9.list | 0 unit-tests/test-cases/llvm-integration/b.c | 0 unit-tests/test-cases/llvm-integration/b1.c | 0 unit-tests/test-cases/llvm-integration/b10.c | 0 unit-tests/test-cases/llvm-integration/b10.h | 0 unit-tests/test-cases/llvm-integration/b14.c | 0 unit-tests/test-cases/llvm-integration/b15.c | 0 unit-tests/test-cases/llvm-integration/b17.c | 0 unit-tests/test-cases/llvm-integration/b2.c | 0 unit-tests/test-cases/llvm-integration/b20.c | 0 unit-tests/test-cases/llvm-integration/b3.c | 0 unit-tests/test-cases/llvm-integration/b4.c | 0 unit-tests/test-cases/llvm-integration/b5.c | 0 unit-tests/test-cases/llvm-integration/b7.c | 0 unit-tests/test-cases/llvm-integration/c15.c | 0 unit-tests/test-cases/llvm-integration/main.c | 0 .../test-cases/llvm-integration/main1.c | 0 .../test-cases/llvm-integration/main10.c | 0 .../test-cases/llvm-integration/main11.c | 0 .../test-cases/llvm-integration/main12.c | 0 .../test-cases/llvm-integration/main13.cc | 0 .../test-cases/llvm-integration/main16.c | 0 .../test-cases/llvm-integration/main19.c | 0 .../test-cases/llvm-integration/main2.c | 0 .../test-cases/llvm-integration/main20.c | 0 .../test-cases/llvm-integration/main3.c | 0 .../test-cases/llvm-integration/main4.c | 0 .../test-cases/llvm-integration/main5.c | 0 .../test-cases/llvm-integration/main6.c | 0 .../test-cases/llvm-integration/main7.c | 0 .../test-cases/llvm-integration/main8.c | 0 .../test-cases/llvm-integration/main9.c | 0 unit-tests/test-cases/loader_path/Makefile | 0 unit-tests/test-cases/loader_path/bar.c | 0 unit-tests/test-cases/loader_path/foo.c | 0 unit-tests/test-cases/loader_path/main.c | 0 .../local-symbol-partial-stripping/Makefile | 0 .../local-symbol-partial-stripping/a.expect | 0 .../local-symbol-partial-stripping/a.list | 0 .../local-symbol-partial-stripping/b.expect | 0 .../local-symbol-partial-stripping/b.list | 0 .../local-symbol-partial-stripping/c.list | 0 .../local-symbol-partial-stripping/foo.c | 0 .../local-symbol-partial-stripping/main.c | 0 .../test-cases/lto-archive-dylib/Makefile | 46 + unit-tests/test-cases/lto-archive-dylib/foo.c | 5 + .../test-cases/lto-archive-dylib/main.c | 8 + .../test-cases/lto-llvm-options/Makefile | 45 + unit-tests/test-cases/lto-llvm-options/main.c | 15 + .../test-cases/lto-preload-pie/Makefile | 47 + unit-tests/test-cases/lto-preload-pie/a.c | 4 + unit-tests/test-cases/lto-preload-pie/b.c | 1 + unit-tests/test-cases/lto-preload-pie/main.c | 11 + .../lto-weak-native-override/Makefile | 45 + .../test-cases/lto-weak-native-override/foo.c | 6 + .../lto-weak-native-override/main.c | 17 + unit-tests/test-cases/main-stripped/Makefile | 0 unit-tests/test-cases/main-stripped/main.c | 0 unit-tests/test-cases/main-stripped/main.exp | 0 .../test-cases/missing-option-args/Makefile | 0 .../missing-option-args/comment.txt | 0 .../test-cases/multiple-entry-points/Makefile | 0 .../multiple-entry-points/comment.txt | 0 .../test-cases/multiple-entry-points/test.s | 0 unit-tests/test-cases/no-data-bundle/Makefile | 38 + unit-tests/test-cases/no-data-bundle/foo.c | 6 + .../no-dynamic-common/Makefile.newtest | 0 unit-tests/test-cases/no-dynamic-common/a.c | 0 .../test-cases/no-dynamic-common/comment.txt | 0 .../test-cases/no-dynamic-common/test.c | 0 .../test-cases/no-object-symbols/Makefile | 46 + .../test-cases/no-object-symbols/empty.s | 2 + unit-tests/test-cases/no-uuid/Makefile | 0 unit-tests/test-cases/no-uuid/bar.c | 0 unit-tests/test-cases/no-uuid/comment.txt | 0 unit-tests/test-cases/no-uuid/foo.c | 0 unit-tests/test-cases/non-lazy-r/Makefile | 6 +- unit-tests/test-cases/non-lazy-r/foo.c | 5 + unit-tests/test-cases/non-lazy-r/other.c | 1 + .../objc-category-debug-notes/Makefile | 0 .../objc-category-debug-notes/test.m | 0 .../objc-exported_symbols_list/Makefile | 0 .../objc-exported_symbols_list/foo.exp | 0 .../objc-exported_symbols_list/foo.m | 0 unit-tests/test-cases/objc-gc-checks/Makefile | 0 unit-tests/test-cases/objc-gc-checks/bar.m | 0 .../test-cases/objc-gc-checks/comment.txt | 0 unit-tests/test-cases/objc-gc-checks/foo.m | 0 .../test-cases/objc-gc-checks/runtime.c | 0 .../objc-literal-pointers-strip/Makefile | 57 + .../objc-literal-pointers-strip/test.m | 46 + .../test-cases/objc-literal-pointers/Makefile | 6 +- .../test-cases/objc-literal-pointers/test.m | 0 .../test-cases/objc-references/Makefile | 0 .../test-cases/objc-references/comment.txt | 0 unit-tests/test-cases/objc-references/test.m | 0 .../objc-selector-coalescing/Makefile | 0 .../objc-selector-coalescing/main.m | 0 .../objc-selector-coalescing/other.m | 0 unit-tests/test-cases/operator-new/Makefile | 5 +- unit-tests/test-cases/operator-new/main.cxx | 2 +- unit-tests/test-cases/order_file-ans/Makefile | 6 +- unit-tests/test-cases/order_file-ans/main.cxx | 5 +- .../test-cases/order_file-ans/main.expected | 8 +- .../test-cases/order_file-ans/main.order | 8 +- unit-tests/test-cases/order_file/Makefile | 0 unit-tests/test-cases/order_file/extra.s | 0 unit-tests/test-cases/order_file/main.c | 0 .../test-cases/order_file/main1.expected | 0 unit-tests/test-cases/order_file/main1.order | 0 .../test-cases/order_file/main2.expected | 0 unit-tests/test-cases/order_file/main2.order | 0 .../test-cases/order_file/main3.expected | 0 unit-tests/test-cases/order_file/main3.order | 0 unit-tests/test-cases/prebound-main/Makefile | 26 +- unit-tests/test-cases/prebound-main/main.c | 0 .../test-cases/prebound-split-seg/Makefile | 0 .../prebound-split-seg/address_table | 0 .../test-cases/prebound-split-seg/bar.c | 0 .../test-cases/private-non-lazy/Makefile | 0 unit-tests/test-cases/private-non-lazy/bar.c | 0 .../test-cases/private-non-lazy/comment.txt | 0 unit-tests/test-cases/private-non-lazy/foo.c | 0 .../test-cases/private-non-lazy/hello.c | 0 .../test-cases/re-export-cases/Makefile | 0 unit-tests/test-cases/re-export-cases/bar.c | 0 unit-tests/test-cases/re-export-cases/baz.c | 0 unit-tests/test-cases/re-export-cases/foo.c | 0 unit-tests/test-cases/re-export-flag/Makefile | 0 unit-tests/test-cases/re-export-flag/bar.c | 0 unit-tests/test-cases/re-export-flag/foo.c | 0 .../re-export-optimizations-indirect/Makefile | 64 + .../re-export-optimizations-indirect/bar.c | 5 + .../re-export-optimizations-indirect/foo.c | 4 + .../re-export-optimizations-indirect/main.c | 8 + .../re-export-optimizations-indirect/middle.c | 3 + .../re-export-optimizations-indirect/other.c | 1 + .../re-export-optimizations/Makefile | 0 .../test-cases/re-export-optimizations/bar.c | 0 .../test-cases/re-export-optimizations/foo.c | 0 .../test-cases/re-export-optimizations/main.c | 0 .../re-export-relative-paths/Makefile | 0 .../test-cases/re-export-relative-paths/bar.c | 0 .../test-cases/re-export-relative-paths/foo.c | 0 .../re-export-relative-paths/main.c | 0 .../re-export-relative-paths/wrap.c | 0 .../test-cases/read-only-relocs/Makefile | 0 unit-tests/test-cases/read-only-relocs/foo.c | 0 unit-tests/test-cases/read-only-relocs/test.c | 0 unit-tests/test-cases/rebase-basic/Makefile | 12 +- unit-tests/test-cases/rebase-basic/bar.m | 0 .../test-cases/rebase-basic/comment.txt | 0 unit-tests/test-cases/rebase-basic/foo.c | 0 unit-tests/test-cases/relocs-asm/Makefile | 0 unit-tests/test-cases/relocs-asm/comment.txt | 0 unit-tests/test-cases/relocs-asm/relocs-asm.s | 26 + unit-tests/test-cases/relocs-c/Makefile | 0 unit-tests/test-cases/relocs-c/test.c | 0 unit-tests/test-cases/relocs-c2/Makefile | 0 unit-tests/test-cases/relocs-c2/comment.txt | 0 unit-tests/test-cases/relocs-c2/test.c | 0 .../test-cases/relocs-literals/Makefile | 0 unit-tests/test-cases/relocs-literals/test.c | 0 .../test-cases/relocs-literals2/Makefile | 0 unit-tests/test-cases/relocs-literals2/test.c | 0 .../test-cases/relocs-literals3/Makefile | 0 .../test-cases/relocs-literals3/comment.txt | 0 unit-tests/test-cases/relocs-literals3/test.c | 0 .../test-cases/relocs-neg-from-local/Makefile | 51 + .../test-cases/relocs-neg-from-local/test.s | 43 + unit-tests/test-cases/relocs-objc/Makefile | 0 unit-tests/test-cases/relocs-objc/comment.txt | 0 unit-tests/test-cases/relocs-objc/test.m | 0 .../test-cases/section-names-long/Makefile | 42 + unit-tests/test-cases/section-names-long/a.s | 9 + unit-tests/test-cases/section-names-long/b.s | 9 + unit-tests/test-cases/section-names-long/c.s | 11 + .../test-cases/section-names-long/main.c | 4 + unit-tests/test-cases/segment-order/Makefile | 0 .../test-cases/segment-order/expected.order | 0 unit-tests/test-cases/segment-order/main.c | 0 unit-tests/test-cases/segment-order/segJJJ.s | 0 unit-tests/test-cases/segment-order/segKKK.s | 0 unit-tests/test-cases/segment-order/segLLL.s | 0 .../test-cases/shared-cache-dylib/Makefile | 46 + .../test-cases/shared-cache-dylib/foo.c | 3 + unit-tests/test-cases/slow-x86-stubs/Makefile | 6 +- unit-tests/test-cases/slow-x86-stubs/hello.c | 0 unit-tests/test-cases/special-labels/Makefile | 0 unit-tests/test-cases/special-labels/extra.s | 0 unit-tests/test-cases/special-labels/main.c | 0 unit-tests/test-cases/stabs-coalesce/Makefile | 0 .../test-cases/stabs-coalesce/comment.txt | 0 unit-tests/test-cases/stabs-coalesce/header.h | 0 .../test-cases/stabs-coalesce/hello.cxx | 0 .../test-cases/stabs-coalesce/other.cxx | 0 .../test-cases/stabs-directory-slash/Makefile | 0 .../test-cases/stabs-directory-slash/main.c | 0 .../stack_addr_no_size/Makefile.newtest | 0 .../test-cases/stack_addr_no_size/comment.txt | 0 .../test-cases/stack_addr_no_size/main.c | 0 .../test-cases/stack_addr_size/Makefile | 0 .../test-cases/stack_addr_size/comment.txt | 0 unit-tests/test-cases/stack_addr_size/main.c | 0 .../test-cases/stack_size_no_addr/Makefile | 0 .../test-cases/stack_size_no_addr/comment.txt | 0 .../test-cases/stack_size_no_addr/main.c | 0 .../test-cases/static-executable/Makefile | 0 .../test-cases/static-executable/test.c | 0 .../test-cases/static-strip/Makefile.newtest | 0 .../test-cases/static-strip/comment.txt | 0 unit-tests/test-cases/static-strip/test.c | 0 unit-tests/test-cases/strip-test2/Makefile | 0 unit-tests/test-cases/strip-test2/comment.txt | 0 unit-tests/test-cases/strip-test2/main.cxx | 0 .../test-cases/strip-test3/Makefile.newtest | 0 unit-tests/test-cases/strip-test3/comment.txt | 0 unit-tests/test-cases/strip-test3/main.cxx | 0 unit-tests/test-cases/strip_local/Makefile | 0 unit-tests/test-cases/strip_local/foo.c | 0 unit-tests/test-cases/strip_local/hello.c | 0 .../stripped-indirect-symbol-table/Makefile | 14 +- .../stripped-indirect-symbol-table/a.c | 0 .../stripped-indirect-symbol-table/b.c | 0 .../stripped-indirect-symbol-table/c.c | 0 .../stripped-indirect-symbol-table/func.c | 0 .../stripped-indirect-symbol-table/strip.list | 0 .../test-cases/stub-generation-weak/Makefile | 0 .../test-cases/stub-generation-weak/foo.c | 0 .../test-cases/stub-generation-weak/main.c | 0 .../test-cases/stub-generation/Makefile | 0 unit-tests/test-cases/stub-generation/test.c | 0 .../test-cases/switch-jump-table/Makefile | 17 +- .../switch-jump-table/interpose.exp | 0 .../test-cases/switch-jump-table/main.c | 0 .../test-cases/switch-jump-table/switch.s | 0 unit-tests/test-cases/symbol-moving/Makefile | 2 +- unit-tests/test-cases/symbol-moving/aaa.c | 0 unit-tests/test-cases/symbol-moving/anotb.c | 0 unit-tests/test-cases/symbol-moving/bar.c | 0 unit-tests/test-cases/symbol-moving/bbb.c | 0 unit-tests/test-cases/symbol-moving/bnota.c | 0 unit-tests/test-cases/symbol-moving/foo.c | 0 unit-tests/test-cases/symbol-moving/main.c | 0 .../test-cases/tentative-and-archive/Makefile | 19 +- .../test-cases/tentative-and-archive/bar.c | 1 + .../test-cases/tentative-and-archive/foo.c | 0 .../test-cases/tentative-and-archive/main.c | 1 + .../test-cases/tentative-and-dylib/Makefile | 0 .../test-cases/tentative-and-dylib/bar.c | 0 .../test-cases/tentative-and-dylib/foo.c | 0 .../test-cases/tentative-and-dylib/main.c | 0 .../tentative-to-real-hidden/Makefile | 0 .../tentative-to-real-hidden/test.c | 0 .../test-cases/tentative-to-real/Makefile | 0 .../test-cases/tentative-to-real/comment.txt | 0 .../test-cases/tentative-to-real/test.c | 0 unit-tests/test-cases/thumb-blx/Makefile | 0 unit-tests/test-cases/thumb-blx/test.c | 0 unit-tests/test-cases/thumb-pointer/Makefile | 49 + unit-tests/test-cases/thumb-pointer/bar.c | 5 + unit-tests/test-cases/thumb-pointer/foo.c | 14 + .../undefined-dynamic-lookup/Makefile | 0 .../undefined-dynamic-lookup/main.c | 0 .../unexported_symbols_list-r/Makefile | 40 + .../unexported_symbols_list-r/foo.c | 9 + .../unexported_symbols_list-r/foo.exp | 3 + .../Makefile | 0 .../visibility-warning-dylib-v-archive/bar.c | 0 .../visibility-warning-dylib-v-archive/foo.c | 0 .../visibility-warning-dylib-v-archive/main.c | 0 .../test-cases/visibility-warning/Makefile | 0 .../test-cases/visibility-warning/foo.c | 0 .../visibility-warning/foo_hidden.c | 0 .../test-cases/visibility-warning/foo_weak.c | 0 .../visibility-warning/foo_weak_hidden.c | 0 unit-tests/test-cases/weak-def-flag/Makefile | 46 + unit-tests/test-cases/weak-def-flag/main.c | 13 + .../test-cases/weak-def-ordinal/Makefile | 0 unit-tests/test-cases/weak-def-ordinal/bar.c | 0 unit-tests/test-cases/weak-def-ordinal/foo.c | 0 unit-tests/test-cases/weak-def-ordinal/main.c | 0 unit-tests/test-cases/weak_dylib/Makefile | 0 unit-tests/test-cases/weak_dylib/bar.c | 0 unit-tests/test-cases/weak_dylib/bar.h | 0 unit-tests/test-cases/weak_dylib/foo.c | 0 unit-tests/test-cases/weak_dylib/foo.h | 0 unit-tests/test-cases/weak_dylib/main.c | 0 .../test-cases/weak_import-force/Makefile | 44 + unit-tests/test-cases/weak_import-force/bar.c | 9 + unit-tests/test-cases/weak_import-force/foo.c | 9 + .../test-cases/weak_import-force/main.c | 31 + unit-tests/test-cases/weak_import/Makefile | 10 +- unit-tests/test-cases/weak_import/foo.c | 0 unit-tests/test-cases/weak_import/foo.h | 0 unit-tests/test-cases/weak_import/main.c | 0 .../test-cases/weak_import2/Makefile.newtest | 0 .../test-cases/weak_import2/comment.txt | 0 unit-tests/test-cases/weak_import2/foo.c | 0 unit-tests/test-cases/weak_import2/foo.h | 0 unit-tests/test-cases/weak_import2/foo1.c | 0 unit-tests/test-cases/weak_import2/main.c | 0 unit-tests/test-cases/weak_import3/Makefile | 0 .../test-cases/weak_import3/comment.txt | 0 unit-tests/test-cases/weak_import3/foo.c | 0 unit-tests/test-cases/weak_import3/foo.h | 0 unit-tests/test-cases/weak_import3/foo1.c | 0 unit-tests/test-cases/weak_import3/main.c | 0 unit-tests/test-cases/why_live/Makefile | 0 unit-tests/test-cases/why_live/bar.c | 0 unit-tests/test-cases/why_live/foo.c | 0 unit-tests/test-cases/why_live/main.c | 0 unit-tests/test-cases/zero-fill/Makefile | 0 unit-tests/test-cases/zero-fill/test.c | 0 unit-tests/test-cases/zero-fill2/Makefile | 0 unit-tests/test-cases/zero-fill2/comment.txt | 0 unit-tests/test-cases/zero-fill2/test.c | 0 unit-tests/test-cases/zero-fill3/Makefile | 0 unit-tests/test-cases/zero-fill3/comment.txt | 0 unit-tests/test-cases/zero-fill3/test.c | 0 737 files changed, 17258 insertions(+), 1920 deletions(-) mode change 100755 => 100644 APPLE_LICENSE mode change 100755 => 100644 ChangeLog create mode 100644 doc/man/man1/dyldinfo.1 mode change 100755 => 100644 doc/man/man1/ld.1 mode change 100755 => 100644 doc/man/man1/ld64.1 mode change 100755 => 100644 doc/man/man1/rebase.1 create mode 100644 doc/man/man1/unwinddump.1 mode change 100755 => 100644 ld64.xcodeproj/project.pbxproj rename src/{ => abstraction}/FileAbstraction.hpp (100%) mode change 100755 => 100644 rename src/{ => abstraction}/MachOFileAbstraction.hpp (76%) mode change 100755 => 100644 create mode 100644 src/abstraction/MachOTrie.hpp rename src/{ => ld}/Architectures.hpp (80%) mode change 100755 => 100644 rename src/{ => ld}/ArchiveReader.hpp (88%) mode change 100755 => 100644 rename src/{ => ld}/ExecutableFile.h (88%) mode change 100755 => 100644 rename src/{ => ld}/LTOReader.hpp (84%) mode change 100755 => 100644 rename src/{ => ld}/MachOReaderDylib.hpp (86%) mode change 100755 => 100644 rename src/{ => ld}/MachOReaderRelocatable.hpp (74%) mode change 100755 => 100644 rename src/{ => ld}/MachOWriterExecutable.hpp (67%) mode change 100755 => 100644 rename src/{ => ld}/ObjectFile.h (85%) mode change 100755 => 100644 rename src/{ => ld}/OpaqueSection.hpp (100%) mode change 100755 => 100644 rename src/{ => ld}/Options.cpp (83%) mode change 100755 => 100644 rename src/{ => ld}/Options.h (85%) mode change 100755 => 100644 rename src/{ => ld}/SectCreate.h (100%) mode change 100755 => 100644 rename src/{ => ld}/debugline.c (99%) mode change 100755 => 100644 rename src/{ => ld}/debugline.h (100%) mode change 100755 => 100644 rename src/{ => ld}/dwarf2.h (97%) mode change 100755 => 100644 rename src/{ => ld}/ld.cpp (80%) mode change 100755 => 100644 rename src/{ => other}/ObjectDump.cpp (94%) mode change 100755 => 100644 create mode 100644 src/other/PruneTrie.cpp create mode 100644 src/other/dyldinfo.cpp rename src/{ => other}/machochecker.cpp (97%) mode change 100755 => 100644 create mode 100644 src/other/prune_trie.h rename src/{ => other}/rebase.cpp (83%) mode change 100755 => 100644 create mode 100644 src/other/unwinddump.cpp mode change 100755 => 100644 unit-tests/README mode change 100755 => 100644 unit-tests/include/common.makefile mode change 100755 => 100644 unit-tests/include/test.h mode change 100755 => 100644 unit-tests/src/Makefile mode change 100755 => 100644 unit-tests/src/results-to-xml.cpp mode change 100755 => 100644 unit-tests/src/xmlparser/xmlparser.1 mode change 100755 => 100644 unit-tests/src/xmlparser/xmlparser.m mode change 100755 => 100644 unit-tests/src/xmlparser/xmlparser.xcodeproj/project.pbxproj mode change 100755 => 100644 unit-tests/src/xmlparser/xmlparser_Prefix.pch mode change 100755 => 100644 unit-tests/test-cases/16-byte-alignment/Makefile mode change 100755 => 100644 unit-tests/test-cases/16-byte-alignment/comment.txt mode change 100755 => 100644 unit-tests/test-cases/16-byte-alignment/tl_test2.c mode change 100755 => 100644 unit-tests/test-cases/absolute-symbol/Makefile mode change 100755 => 100644 unit-tests/test-cases/absolute-symbol/abs.s mode change 100755 => 100644 unit-tests/test-cases/absolute-symbol/main.c mode change 100755 => 100644 unit-tests/test-cases/alias-command-line/Makefile mode change 100755 => 100644 unit-tests/test-cases/alias-command-line/aliases.s mode change 100755 => 100644 unit-tests/test-cases/alias-command-line/aliases.txt mode change 100755 => 100644 unit-tests/test-cases/alias-objects/Makefile mode change 100755 => 100644 unit-tests/test-cases/alias-objects/aliases.s mode change 100755 => 100644 unit-tests/test-cases/align-modulus/Makefile mode change 100755 => 100644 unit-tests/test-cases/align-modulus/align.s mode change 100755 => 100644 unit-tests/test-cases/align-modulus/comment.txt mode change 100755 => 100644 unit-tests/test-cases/align-modulus/foo.c mode change 100755 => 100644 unit-tests/test-cases/align-modulus/foo.exp mode change 100755 => 100644 unit-tests/test-cases/allow-stack-execute/Makefile mode change 100755 => 100644 unit-tests/test-cases/allow-stack-execute/comment.txt mode change 100755 => 100644 unit-tests/test-cases/allow-stack-execute/foo.c mode change 100755 => 100644 unit-tests/test-cases/allowable-client/Makefile mode change 100755 => 100644 unit-tests/test-cases/allowable-client/bar.c mode change 100755 => 100644 unit-tests/test-cases/allowable-client/baz.c mode change 100755 => 100644 unit-tests/test-cases/allowable-client/comment.txt mode change 100755 => 100644 unit-tests/test-cases/allowable-client/foo.c mode change 100755 => 100644 unit-tests/test-cases/allowable-client/main.c mode change 100755 => 100644 unit-tests/test-cases/archive-ObjC/Makefile mode change 100755 => 100644 unit-tests/test-cases/archive-ObjC/bar.c mode change 100755 => 100644 unit-tests/test-cases/archive-ObjC/baz.m mode change 100755 => 100644 unit-tests/test-cases/archive-ObjC/foo.m mode change 100755 => 100644 unit-tests/test-cases/archive-ObjC/main.c mode change 100755 => 100644 unit-tests/test-cases/archive-basic/Makefile mode change 100755 => 100644 unit-tests/test-cases/archive-basic/bar.c mode change 100755 => 100644 unit-tests/test-cases/archive-basic/comment.txt mode change 100755 => 100644 unit-tests/test-cases/archive-basic/foo.c mode change 100755 => 100644 unit-tests/test-cases/archive-basic/main.c mode change 100755 => 100644 unit-tests/test-cases/archive-duplicate/Makefile mode change 100755 => 100644 unit-tests/test-cases/archive-duplicate/bar.c mode change 100755 => 100644 unit-tests/test-cases/archive-duplicate/foo.c mode change 100755 => 100644 unit-tests/test-cases/archive-duplicate/main.c create mode 100644 unit-tests/test-cases/archive-force-load/Makefile create mode 100644 unit-tests/test-cases/archive-force-load/bar.c create mode 100644 unit-tests/test-cases/archive-force-load/bat.c create mode 100644 unit-tests/test-cases/archive-force-load/baz.c create mode 100644 unit-tests/test-cases/archive-force-load/foo.c create mode 100644 unit-tests/test-cases/archive-force-load/main.c mode change 100755 => 100644 unit-tests/test-cases/archive-weak/Makefile mode change 100755 => 100644 unit-tests/test-cases/archive-weak/bar.c mode change 100755 => 100644 unit-tests/test-cases/archive-weak/baz.c mode change 100755 => 100644 unit-tests/test-cases/archive-weak/comment.txt mode change 100755 => 100644 unit-tests/test-cases/archive-weak/foo.c mode change 100755 => 100644 unit-tests/test-cases/archive-weak/main.c mode change 100755 => 100644 unit-tests/test-cases/auto-arch/Makefile mode change 100755 => 100644 unit-tests/test-cases/auto-arch/hello.c mode change 100755 => 100644 unit-tests/test-cases/blank-stubs/Makefile mode change 100755 => 100644 unit-tests/test-cases/blank-stubs/comment.txt mode change 100755 => 100644 unit-tests/test-cases/blank-stubs/foo.c mode change 100755 => 100644 unit-tests/test-cases/blank-stubs/main.c create mode 100644 unit-tests/test-cases/branch-distance/Makefile create mode 100644 unit-tests/test-cases/branch-distance/bar.s create mode 100644 unit-tests/test-cases/branch-distance/foo.s mode change 100755 => 100644 unit-tests/test-cases/branch-islands/Makefile mode change 100755 => 100644 unit-tests/test-cases/branch-islands/extra.c mode change 100755 => 100644 unit-tests/test-cases/branch-islands/hello.c mode change 100755 => 100644 unit-tests/test-cases/branch-islands/space.s mode change 100755 => 100644 unit-tests/test-cases/bundle_loader/Makefile mode change 100755 => 100644 unit-tests/test-cases/bundle_loader/bar.c mode change 100755 => 100644 unit-tests/test-cases/bundle_loader/bundle.c mode change 100755 => 100644 unit-tests/test-cases/bundle_loader/main.c mode change 100755 => 100644 unit-tests/test-cases/cfstring-coalesce/Makefile mode change 100755 => 100644 unit-tests/test-cases/cfstring-coalesce/bar.c mode change 100755 => 100644 unit-tests/test-cases/cfstring-coalesce/foo.c mode change 100755 => 100644 unit-tests/test-cases/cfstring-utf16/Makefile mode change 100755 => 100644 unit-tests/test-cases/cfstring-utf16/bar.m mode change 100755 => 100644 unit-tests/test-cases/cfstring-utf16/foo.m create mode 100644 unit-tests/test-cases/coalesce_weak_def_in_dylib/Makefile create mode 100644 unit-tests/test-cases/coalesce_weak_def_in_dylib/foo.c create mode 100644 unit-tests/test-cases/coalesce_weak_def_in_dylib/main.c create mode 100644 unit-tests/test-cases/code-signed-object-file/Makefile create mode 100644 unit-tests/test-cases/code-signed-object-file/foo.c mode change 100755 => 100644 unit-tests/test-cases/commons-alignment/Makefile mode change 100755 => 100644 unit-tests/test-cases/commons-alignment/foo.s mode change 100755 => 100644 unit-tests/test-cases/commons-coalesced-dead_strip/Makefile mode change 100755 => 100644 unit-tests/test-cases/commons-coalesced-dead_strip/a.c mode change 100755 => 100644 unit-tests/test-cases/commons-coalesced-dead_strip/b.c mode change 100755 => 100644 unit-tests/test-cases/commons-coalesced-dead_strip/c.c mode change 100755 => 100644 unit-tests/test-cases/commons-coalesced-dead_strip/c.h mode change 100755 => 100644 unit-tests/test-cases/commons-mixed/Makefile mode change 100755 => 100644 unit-tests/test-cases/commons-mixed/bar.c mode change 100755 => 100644 unit-tests/test-cases/commons-mixed/foo.c mode change 100755 => 100644 unit-tests/test-cases/commons-order/Makefile mode change 100755 => 100644 unit-tests/test-cases/commons-order/bar.c mode change 100755 => 100644 unit-tests/test-cases/commons-order/baz.c mode change 100755 => 100644 unit-tests/test-cases/commons-order/expected.order mode change 100755 => 100644 unit-tests/test-cases/commons-order/foo.c mode change 100755 => 100644 unit-tests/test-cases/commons-order/main.c mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types-preference/Makefile mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types-preference/foo.c mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types/Makefile mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types/comment.txt mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types/foo.c mode change 100755 => 100644 unit-tests/test-cases/cpu-sub-types/main.c create mode 100644 unit-tests/test-cases/cstring-alt-segment/Makefile create mode 100644 unit-tests/test-cases/cstring-alt-segment/custom.s create mode 100644 unit-tests/test-cases/cstring-alt-segment/main.c create mode 100644 unit-tests/test-cases/cstring-custom-section/Makefile create mode 100644 unit-tests/test-cases/cstring-custom-section/bar.s create mode 100644 unit-tests/test-cases/cstring-custom-section/foo.s create mode 100644 unit-tests/test-cases/cstring-labels/Makefile create mode 100644 unit-tests/test-cases/cstring-labels/bar.c create mode 100644 unit-tests/test-cases/cstring-labels/foo.c rename unit-tests/test-cases/{implicit-common3 => dead_strip-archive-eh}/Makefile (63%) mode change 100755 => 100644 create mode 100644 unit-tests/test-cases/dead_strip-archive-eh/bar.cxx create mode 100644 unit-tests/test-cases/dead_strip-archive-eh/foo.cxx create mode 100644 unit-tests/test-cases/dead_strip-archive-eh/main.cxx mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive-global/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive-global/foo.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive-global/main.c create mode 100644 unit-tests/test-cases/dead_strip-archive-weak/Makefile create mode 100644 unit-tests/test-cases/dead_strip-archive-weak/foo.c create mode 100644 unit-tests/test-cases/dead_strip-archive-weak/main.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive/foo.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip-archive/main.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip-init-archive/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip-init-archive/bar.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip-init-archive/foo.c create mode 100644 unit-tests/test-cases/dead_strip-r_symbol_desc/Makefile rename unit-tests/test-cases/{implicit-common3/test.c => dead_strip-r_symbol_desc/main.c} (83%) mode change 100755 => 100644 create mode 100644 unit-tests/test-cases/dead_strip-weak-coalesce/Makefile create mode 100644 unit-tests/test-cases/dead_strip-weak-coalesce/baz.c create mode 100644 unit-tests/test-cases/dead_strip-weak-coalesce/foo.c create mode 100644 unit-tests/test-cases/dead_strip-weak-coalesce/main.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dead_strip/deadwood.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip/main.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip/main.exp mode change 100755 => 100644 unit-tests/test-cases/dead_strip_dylibs/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip_dylibs/bar.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip_dylibs/baz.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip_dylibs/foo.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip_dylibs/main.c mode change 100755 => 100644 unit-tests/test-cases/dead_strip_section_attribute/Makefile mode change 100755 => 100644 unit-tests/test-cases/dead_strip_section_attribute/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dead_strip_section_attribute/main.c create mode 100644 unit-tests/test-cases/dead_strippable_dylib/Makefile create mode 100644 unit-tests/test-cases/dead_strippable_dylib/bar.c create mode 100644 unit-tests/test-cases/dead_strippable_dylib/baz.c create mode 100644 unit-tests/test-cases/dead_strippable_dylib/foo.c create mode 100644 unit-tests/test-cases/dead_strippable_dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes-coalescing/Makefile mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes-coalescing/Number.d mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes-coalescing/a.cxx mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes-coalescing/header.h mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes-coalescing/x.cxx mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes/Makefile mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes/bar.d mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes/foo.d mode change 100755 => 100644 unit-tests/test-cases/dtrace-static-probes/main.c mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/Makefile mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/bar.c mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/baz.c mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/expected-stabs mode change 100755 => 100644 unit-tests/test-cases/dwarf-archive-all_load/foo.c mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/Makefile mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/bar.cxx mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/expected-stabs mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/foo.cxx mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes-r/main.cxx mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/Makefile mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/expected-stabs mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/header.h mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/hello.cxx mode change 100755 => 100644 unit-tests/test-cases/dwarf-debug-notes/other.cxx mode change 100755 => 100644 unit-tests/test-cases/dwarf-ignore/Makefile mode change 100755 => 100644 unit-tests/test-cases/dwarf-ignore/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dwarf-ignore/hello.c mode change 100755 => 100644 unit-tests/test-cases/dwarf-strip/Makefile mode change 100755 => 100644 unit-tests/test-cases/dwarf-strip/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dwarf-strip/hello.c mode change 100755 => 100644 unit-tests/test-cases/dylib-aliases/Makefile mode change 100755 => 100644 unit-tests/test-cases/dylib-aliases/bar.c mode change 100755 => 100644 unit-tests/test-cases/dylib-aliases/foo.c mode change 100755 => 100644 unit-tests/test-cases/dylib-aliases/main.c mode change 100755 => 100644 unit-tests/test-cases/dylib-re-export-cycle/Makefile mode change 100755 => 100644 unit-tests/test-cases/dylib-re-export-cycle/bar.c mode change 100755 => 100644 unit-tests/test-cases/dylib-re-export-cycle/foo.c mode change 100755 => 100644 unit-tests/test-cases/dylib-re-export-cycle/main.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file-missing/Makefile mode change 100755 => 100644 unit-tests/test-cases/dylib_file-missing/bar.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file-missing/foo.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file-missing/main.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file/Makefile mode change 100755 => 100644 unit-tests/test-cases/dylib_file/bar.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file/comment.txt mode change 100755 => 100644 unit-tests/test-cases/dylib_file/foo.c mode change 100755 => 100644 unit-tests/test-cases/dylib_file/main.c mode change 100755 => 100644 unit-tests/test-cases/dylib_init/Makefile mode change 100755 => 100644 unit-tests/test-cases/dylib_init/foo.c create mode 100644 unit-tests/test-cases/eh-coalescing-no-labels/Makefile create mode 100644 unit-tests/test-cases/eh-coalescing-no-labels/bar.c create mode 100644 unit-tests/test-cases/eh-coalescing-no-labels/baz.c create mode 100644 unit-tests/test-cases/eh-coalescing-no-labels/foo.c mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing-r/Makefile mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing-r/bar.cxx create mode 100644 unit-tests/test-cases/eh-coalescing-r/baz.cxx mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing-r/foo.cxx mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing-r/func.h mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing/Makefile mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing/bar.cxx mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing/foo.cxx mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing/foo2.cxx mode change 100755 => 100644 unit-tests/test-cases/eh-coalescing/func.h mode change 100755 => 100644 unit-tests/test-cases/eh-strip-test/Makefile mode change 100755 => 100644 unit-tests/test-cases/eh-strip-test/comment.txt mode change 100755 => 100644 unit-tests/test-cases/eh-strip-test/main.cxx create mode 100644 unit-tests/test-cases/eh-stripped-symbols/Makefile create mode 100644 unit-tests/test-cases/eh-stripped-symbols/keep.exp create mode 100644 unit-tests/test-cases/eh-stripped-symbols/main.cxx mode change 100755 => 100644 unit-tests/test-cases/eh_frame/Makefile mode change 100755 => 100644 unit-tests/test-cases/eh_frame/bar.cxx mode change 100755 => 100644 unit-tests/test-cases/eh_frame/foo.cxx mode change 100755 => 100644 unit-tests/test-cases/empty-object/Makefile mode change 100755 => 100644 unit-tests/test-cases/empty-object/main.c mode change 100755 => 100644 unit-tests/test-cases/end-label/Makefile mode change 100755 => 100644 unit-tests/test-cases/end-label/bar.s mode change 100755 => 100644 unit-tests/test-cases/end-label/foo.s mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards-dead_strip/Makefile mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards-dead_strip/foo.c mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/Makefile mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect1 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect2 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect3 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect4 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect5 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect6 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect7 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/expect8 mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/foo.c mode change 100755 => 100644 unit-tests/test-cases/exported-symbols-wildcards/list5 mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-eol/Makefile mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-eol/expected.nm mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-eol/test.c mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-eol/test.exp mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-hidden/Makefile mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-hidden/test.c mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-hidden/test.exp mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-r/Makefile mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-r/test-bad.exp mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-r/test.c mode change 100755 => 100644 unit-tests/test-cases/exported_symbols_list-r/test.exp mode change 100755 => 100644 unit-tests/test-cases/external-reloc-sorting/Makefile mode change 100755 => 100644 unit-tests/test-cases/external-reloc-sorting/foo.c mode change 100755 => 100644 unit-tests/test-cases/external-reloc-sorting/main.c mode change 100755 => 100644 unit-tests/test-cases/filelist/Makefile mode change 100755 => 100644 unit-tests/test-cases/filelist/comment.txt mode change 100755 => 100644 unit-tests/test-cases/filelist/hello.c mode change 100755 => 100644 unit-tests/test-cases/flat-dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/flat-dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/flat-indirect-undefines/Makefile mode change 100755 => 100644 unit-tests/test-cases/flat-indirect-undefines/bar.c mode change 100755 => 100644 unit-tests/test-cases/flat-indirect-undefines/foo.c mode change 100755 => 100644 unit-tests/test-cases/flat-indirect-undefines/main.c mode change 100755 => 100644 unit-tests/test-cases/flat-main/Makefile mode change 100755 => 100644 unit-tests/test-cases/flat-main/main.c mode change 100755 => 100644 unit-tests/test-cases/got-elimination/Makefile mode change 100755 => 100644 unit-tests/test-cases/got-elimination/bar.c mode change 100755 => 100644 unit-tests/test-cases/got-elimination/foo.c mode change 100755 => 100644 unit-tests/test-cases/header-pad/Makefile mode change 100755 => 100644 unit-tests/test-cases/header-pad/comment.txt mode change 100755 => 100644 unit-tests/test-cases/header-pad/hello.c mode change 100755 => 100644 unit-tests/test-cases/hello-world/Makefile mode change 100755 => 100644 unit-tests/test-cases/hello-world/comment.txt mode change 100755 => 100644 unit-tests/test-cases/hello-world/hello.c mode change 100755 => 100644 unit-tests/test-cases/implicit-common2/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/implicit-common2/a.c mode change 100755 => 100644 unit-tests/test-cases/implicit-common2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/implicit-common2/test.c delete mode 100755 unit-tests/test-cases/implicit-common3/a.c delete mode 100755 unit-tests/test-cases/implicit-common3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/implicit-common4/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/implicit-common4/a.c mode change 100755 => 100644 unit-tests/test-cases/implicit-common4/comment.txt mode change 100755 => 100644 unit-tests/test-cases/implicit-common4/test.c mode change 100755 => 100644 unit-tests/test-cases/implicit-common5/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/implicit-common5/a.c mode change 100755 => 100644 unit-tests/test-cases/implicit-common5/comment.txt mode change 100755 => 100644 unit-tests/test-cases/implicit-common5/test.c mode change 100755 => 100644 unit-tests/test-cases/implicit_dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/implicit_dylib/bar.c mode change 100755 => 100644 unit-tests/test-cases/implicit_dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/implicit_dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/indirect-dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/indirect-dylib/bar.c mode change 100755 => 100644 unit-tests/test-cases/indirect-dylib/comment.txt mode change 100755 => 100644 unit-tests/test-cases/indirect-dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/indirect-dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/indirect-path-search/Makefile mode change 100755 => 100644 unit-tests/test-cases/indirect-path-search/bar.c mode change 100755 => 100644 unit-tests/test-cases/indirect-path-search/baz.c mode change 100755 => 100644 unit-tests/test-cases/indirect-path-search/foo.c mode change 100755 => 100644 unit-tests/test-cases/indirect-path-search/main.c create mode 100644 unit-tests/test-cases/init-order/Makefile create mode 100644 unit-tests/test-cases/init-order/bar.cxx create mode 100644 unit-tests/test-cases/init-order/expected-order.txt create mode 100644 unit-tests/test-cases/init-order/foo.cxx create mode 100644 unit-tests/test-cases/init-order/main.cxx mode change 100755 => 100644 unit-tests/test-cases/interposable_list/Makefile mode change 100755 => 100644 unit-tests/test-cases/interposable_list/test.c mode change 100755 => 100644 unit-tests/test-cases/interposable_list/test.exp create mode 100644 unit-tests/test-cases/kext-basic/Makefile create mode 100644 unit-tests/test-cases/kext-basic/mykext.c create mode 100644 unit-tests/test-cases/kext-basic/mykextinfo.c mode change 100755 => 100644 unit-tests/test-cases/large-data/Makefile mode change 100755 => 100644 unit-tests/test-cases/large-data/test1.c mode change 100755 => 100644 unit-tests/test-cases/large-data/test2.c mode change 100755 => 100644 unit-tests/test-cases/large-data/test3.c mode change 100755 => 100644 unit-tests/test-cases/large-data/test4.c mode change 100755 => 100644 unit-tests/test-cases/late-link-error/Makefile mode change 100755 => 100644 unit-tests/test-cases/late-link-error/comment.txt mode change 100755 => 100644 unit-tests/test-cases/late-link-error/link_error.s mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib-objc/Makefile mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib-objc/foo.h mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib-objc/foo.m mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib-objc/main.m mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib/bad.c mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib/bad2.c mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/lazy-dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment/Makefile mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment/cstring-align-0.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment/cstring-align-3.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment2/Makefile mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-0.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-3.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment3/Makefile mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-0.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-3.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce/Makefile mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce/literals.s mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce2/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/literals-coalesce2/literals.s mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/Makefile mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a1.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a10.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a11.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a12.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a12.h mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a13.cc mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a13.h mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a14.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a15.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a17.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a18.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a2.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a20.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a3.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a4.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a5.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a6.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a7.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a8.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a9.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/a9.list mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b1.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b10.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b10.h mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b14.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b15.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b17.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b2.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b20.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b3.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b4.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b5.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/b7.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/c15.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main1.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main10.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main11.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main12.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main13.cc mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main16.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main19.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main2.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main20.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main3.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main4.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main5.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main6.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main7.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main8.c mode change 100755 => 100644 unit-tests/test-cases/llvm-integration/main9.c mode change 100755 => 100644 unit-tests/test-cases/loader_path/Makefile mode change 100755 => 100644 unit-tests/test-cases/loader_path/bar.c mode change 100755 => 100644 unit-tests/test-cases/loader_path/foo.c mode change 100755 => 100644 unit-tests/test-cases/loader_path/main.c mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/Makefile mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/a.expect mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/a.list mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/b.expect mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/b.list mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/c.list mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/foo.c mode change 100755 => 100644 unit-tests/test-cases/local-symbol-partial-stripping/main.c create mode 100644 unit-tests/test-cases/lto-archive-dylib/Makefile create mode 100644 unit-tests/test-cases/lto-archive-dylib/foo.c create mode 100644 unit-tests/test-cases/lto-archive-dylib/main.c create mode 100644 unit-tests/test-cases/lto-llvm-options/Makefile create mode 100644 unit-tests/test-cases/lto-llvm-options/main.c create mode 100644 unit-tests/test-cases/lto-preload-pie/Makefile create mode 100644 unit-tests/test-cases/lto-preload-pie/a.c create mode 100644 unit-tests/test-cases/lto-preload-pie/b.c create mode 100644 unit-tests/test-cases/lto-preload-pie/main.c create mode 100644 unit-tests/test-cases/lto-weak-native-override/Makefile create mode 100644 unit-tests/test-cases/lto-weak-native-override/foo.c create mode 100644 unit-tests/test-cases/lto-weak-native-override/main.c mode change 100755 => 100644 unit-tests/test-cases/main-stripped/Makefile mode change 100755 => 100644 unit-tests/test-cases/main-stripped/main.c mode change 100755 => 100644 unit-tests/test-cases/main-stripped/main.exp mode change 100755 => 100644 unit-tests/test-cases/missing-option-args/Makefile mode change 100755 => 100644 unit-tests/test-cases/missing-option-args/comment.txt mode change 100755 => 100644 unit-tests/test-cases/multiple-entry-points/Makefile mode change 100755 => 100644 unit-tests/test-cases/multiple-entry-points/comment.txt mode change 100755 => 100644 unit-tests/test-cases/multiple-entry-points/test.s create mode 100644 unit-tests/test-cases/no-data-bundle/Makefile create mode 100644 unit-tests/test-cases/no-data-bundle/foo.c mode change 100755 => 100644 unit-tests/test-cases/no-dynamic-common/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/no-dynamic-common/a.c mode change 100755 => 100644 unit-tests/test-cases/no-dynamic-common/comment.txt mode change 100755 => 100644 unit-tests/test-cases/no-dynamic-common/test.c create mode 100644 unit-tests/test-cases/no-object-symbols/Makefile create mode 100644 unit-tests/test-cases/no-object-symbols/empty.s mode change 100755 => 100644 unit-tests/test-cases/no-uuid/Makefile mode change 100755 => 100644 unit-tests/test-cases/no-uuid/bar.c mode change 100755 => 100644 unit-tests/test-cases/no-uuid/comment.txt mode change 100755 => 100644 unit-tests/test-cases/no-uuid/foo.c mode change 100755 => 100644 unit-tests/test-cases/non-lazy-r/Makefile mode change 100755 => 100644 unit-tests/test-cases/non-lazy-r/foo.c mode change 100755 => 100644 unit-tests/test-cases/non-lazy-r/other.c mode change 100755 => 100644 unit-tests/test-cases/objc-category-debug-notes/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-category-debug-notes/test.m mode change 100755 => 100644 unit-tests/test-cases/objc-exported_symbols_list/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-exported_symbols_list/foo.exp mode change 100755 => 100644 unit-tests/test-cases/objc-exported_symbols_list/foo.m mode change 100755 => 100644 unit-tests/test-cases/objc-gc-checks/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-gc-checks/bar.m mode change 100755 => 100644 unit-tests/test-cases/objc-gc-checks/comment.txt mode change 100755 => 100644 unit-tests/test-cases/objc-gc-checks/foo.m mode change 100755 => 100644 unit-tests/test-cases/objc-gc-checks/runtime.c create mode 100644 unit-tests/test-cases/objc-literal-pointers-strip/Makefile create mode 100644 unit-tests/test-cases/objc-literal-pointers-strip/test.m mode change 100755 => 100644 unit-tests/test-cases/objc-literal-pointers/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-literal-pointers/test.m mode change 100755 => 100644 unit-tests/test-cases/objc-references/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-references/comment.txt mode change 100755 => 100644 unit-tests/test-cases/objc-references/test.m mode change 100755 => 100644 unit-tests/test-cases/objc-selector-coalescing/Makefile mode change 100755 => 100644 unit-tests/test-cases/objc-selector-coalescing/main.m mode change 100755 => 100644 unit-tests/test-cases/objc-selector-coalescing/other.m mode change 100755 => 100644 unit-tests/test-cases/operator-new/Makefile mode change 100755 => 100644 unit-tests/test-cases/operator-new/main.cxx mode change 100755 => 100644 unit-tests/test-cases/order_file-ans/Makefile mode change 100755 => 100644 unit-tests/test-cases/order_file-ans/main.cxx mode change 100755 => 100644 unit-tests/test-cases/order_file-ans/main.expected mode change 100755 => 100644 unit-tests/test-cases/order_file-ans/main.order mode change 100755 => 100644 unit-tests/test-cases/order_file/Makefile mode change 100755 => 100644 unit-tests/test-cases/order_file/extra.s mode change 100755 => 100644 unit-tests/test-cases/order_file/main.c mode change 100755 => 100644 unit-tests/test-cases/order_file/main1.expected mode change 100755 => 100644 unit-tests/test-cases/order_file/main1.order mode change 100755 => 100644 unit-tests/test-cases/order_file/main2.expected mode change 100755 => 100644 unit-tests/test-cases/order_file/main2.order mode change 100755 => 100644 unit-tests/test-cases/order_file/main3.expected mode change 100755 => 100644 unit-tests/test-cases/order_file/main3.order mode change 100755 => 100644 unit-tests/test-cases/prebound-main/Makefile mode change 100755 => 100644 unit-tests/test-cases/prebound-main/main.c mode change 100755 => 100644 unit-tests/test-cases/prebound-split-seg/Makefile mode change 100755 => 100644 unit-tests/test-cases/prebound-split-seg/address_table mode change 100755 => 100644 unit-tests/test-cases/prebound-split-seg/bar.c mode change 100755 => 100644 unit-tests/test-cases/private-non-lazy/Makefile mode change 100755 => 100644 unit-tests/test-cases/private-non-lazy/bar.c mode change 100755 => 100644 unit-tests/test-cases/private-non-lazy/comment.txt mode change 100755 => 100644 unit-tests/test-cases/private-non-lazy/foo.c mode change 100755 => 100644 unit-tests/test-cases/private-non-lazy/hello.c mode change 100755 => 100644 unit-tests/test-cases/re-export-cases/Makefile mode change 100755 => 100644 unit-tests/test-cases/re-export-cases/bar.c mode change 100755 => 100644 unit-tests/test-cases/re-export-cases/baz.c mode change 100755 => 100644 unit-tests/test-cases/re-export-cases/foo.c mode change 100755 => 100644 unit-tests/test-cases/re-export-flag/Makefile mode change 100755 => 100644 unit-tests/test-cases/re-export-flag/bar.c mode change 100755 => 100644 unit-tests/test-cases/re-export-flag/foo.c create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/Makefile create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/bar.c create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/foo.c create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/main.c create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/middle.c create mode 100644 unit-tests/test-cases/re-export-optimizations-indirect/other.c mode change 100755 => 100644 unit-tests/test-cases/re-export-optimizations/Makefile mode change 100755 => 100644 unit-tests/test-cases/re-export-optimizations/bar.c mode change 100755 => 100644 unit-tests/test-cases/re-export-optimizations/foo.c mode change 100755 => 100644 unit-tests/test-cases/re-export-optimizations/main.c mode change 100755 => 100644 unit-tests/test-cases/re-export-relative-paths/Makefile mode change 100755 => 100644 unit-tests/test-cases/re-export-relative-paths/bar.c mode change 100755 => 100644 unit-tests/test-cases/re-export-relative-paths/foo.c mode change 100755 => 100644 unit-tests/test-cases/re-export-relative-paths/main.c mode change 100755 => 100644 unit-tests/test-cases/re-export-relative-paths/wrap.c mode change 100755 => 100644 unit-tests/test-cases/read-only-relocs/Makefile mode change 100755 => 100644 unit-tests/test-cases/read-only-relocs/foo.c mode change 100755 => 100644 unit-tests/test-cases/read-only-relocs/test.c mode change 100755 => 100644 unit-tests/test-cases/rebase-basic/Makefile mode change 100755 => 100644 unit-tests/test-cases/rebase-basic/bar.m mode change 100755 => 100644 unit-tests/test-cases/rebase-basic/comment.txt mode change 100755 => 100644 unit-tests/test-cases/rebase-basic/foo.c mode change 100755 => 100644 unit-tests/test-cases/relocs-asm/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-asm/comment.txt mode change 100755 => 100644 unit-tests/test-cases/relocs-asm/relocs-asm.s mode change 100755 => 100644 unit-tests/test-cases/relocs-c/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-c/test.c mode change 100755 => 100644 unit-tests/test-cases/relocs-c2/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-c2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/relocs-c2/test.c mode change 100755 => 100644 unit-tests/test-cases/relocs-literals/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-literals/test.c mode change 100755 => 100644 unit-tests/test-cases/relocs-literals2/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-literals2/test.c mode change 100755 => 100644 unit-tests/test-cases/relocs-literals3/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-literals3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/relocs-literals3/test.c create mode 100644 unit-tests/test-cases/relocs-neg-from-local/Makefile create mode 100644 unit-tests/test-cases/relocs-neg-from-local/test.s mode change 100755 => 100644 unit-tests/test-cases/relocs-objc/Makefile mode change 100755 => 100644 unit-tests/test-cases/relocs-objc/comment.txt mode change 100755 => 100644 unit-tests/test-cases/relocs-objc/test.m create mode 100644 unit-tests/test-cases/section-names-long/Makefile create mode 100644 unit-tests/test-cases/section-names-long/a.s create mode 100644 unit-tests/test-cases/section-names-long/b.s create mode 100644 unit-tests/test-cases/section-names-long/c.s create mode 100644 unit-tests/test-cases/section-names-long/main.c mode change 100755 => 100644 unit-tests/test-cases/segment-order/Makefile mode change 100755 => 100644 unit-tests/test-cases/segment-order/expected.order mode change 100755 => 100644 unit-tests/test-cases/segment-order/main.c mode change 100755 => 100644 unit-tests/test-cases/segment-order/segJJJ.s mode change 100755 => 100644 unit-tests/test-cases/segment-order/segKKK.s mode change 100755 => 100644 unit-tests/test-cases/segment-order/segLLL.s create mode 100644 unit-tests/test-cases/shared-cache-dylib/Makefile create mode 100644 unit-tests/test-cases/shared-cache-dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/slow-x86-stubs/Makefile mode change 100755 => 100644 unit-tests/test-cases/slow-x86-stubs/hello.c mode change 100755 => 100644 unit-tests/test-cases/special-labels/Makefile mode change 100755 => 100644 unit-tests/test-cases/special-labels/extra.s mode change 100755 => 100644 unit-tests/test-cases/special-labels/main.c mode change 100755 => 100644 unit-tests/test-cases/stabs-coalesce/Makefile mode change 100755 => 100644 unit-tests/test-cases/stabs-coalesce/comment.txt mode change 100755 => 100644 unit-tests/test-cases/stabs-coalesce/header.h mode change 100755 => 100644 unit-tests/test-cases/stabs-coalesce/hello.cxx mode change 100755 => 100644 unit-tests/test-cases/stabs-coalesce/other.cxx mode change 100755 => 100644 unit-tests/test-cases/stabs-directory-slash/Makefile mode change 100755 => 100644 unit-tests/test-cases/stabs-directory-slash/main.c mode change 100755 => 100644 unit-tests/test-cases/stack_addr_no_size/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/stack_addr_no_size/comment.txt mode change 100755 => 100644 unit-tests/test-cases/stack_addr_no_size/main.c mode change 100755 => 100644 unit-tests/test-cases/stack_addr_size/Makefile mode change 100755 => 100644 unit-tests/test-cases/stack_addr_size/comment.txt mode change 100755 => 100644 unit-tests/test-cases/stack_addr_size/main.c mode change 100755 => 100644 unit-tests/test-cases/stack_size_no_addr/Makefile mode change 100755 => 100644 unit-tests/test-cases/stack_size_no_addr/comment.txt mode change 100755 => 100644 unit-tests/test-cases/stack_size_no_addr/main.c mode change 100755 => 100644 unit-tests/test-cases/static-executable/Makefile mode change 100755 => 100644 unit-tests/test-cases/static-executable/test.c mode change 100755 => 100644 unit-tests/test-cases/static-strip/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/static-strip/comment.txt mode change 100755 => 100644 unit-tests/test-cases/static-strip/test.c mode change 100755 => 100644 unit-tests/test-cases/strip-test2/Makefile mode change 100755 => 100644 unit-tests/test-cases/strip-test2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/strip-test2/main.cxx mode change 100755 => 100644 unit-tests/test-cases/strip-test3/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/strip-test3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/strip-test3/main.cxx mode change 100755 => 100644 unit-tests/test-cases/strip_local/Makefile mode change 100755 => 100644 unit-tests/test-cases/strip_local/foo.c mode change 100755 => 100644 unit-tests/test-cases/strip_local/hello.c mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/Makefile mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/a.c mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/b.c mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/c.c mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/func.c mode change 100755 => 100644 unit-tests/test-cases/stripped-indirect-symbol-table/strip.list mode change 100755 => 100644 unit-tests/test-cases/stub-generation-weak/Makefile mode change 100755 => 100644 unit-tests/test-cases/stub-generation-weak/foo.c mode change 100755 => 100644 unit-tests/test-cases/stub-generation-weak/main.c mode change 100755 => 100644 unit-tests/test-cases/stub-generation/Makefile mode change 100755 => 100644 unit-tests/test-cases/stub-generation/test.c mode change 100755 => 100644 unit-tests/test-cases/switch-jump-table/Makefile mode change 100755 => 100644 unit-tests/test-cases/switch-jump-table/interpose.exp mode change 100755 => 100644 unit-tests/test-cases/switch-jump-table/main.c mode change 100755 => 100644 unit-tests/test-cases/switch-jump-table/switch.s mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/Makefile mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/aaa.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/anotb.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/bar.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/bbb.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/bnota.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/foo.c mode change 100755 => 100644 unit-tests/test-cases/symbol-moving/main.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-archive/Makefile create mode 100644 unit-tests/test-cases/tentative-and-archive/bar.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-archive/foo.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-archive/main.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/tentative-and-dylib/bar.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/tentative-and-dylib/main.c mode change 100755 => 100644 unit-tests/test-cases/tentative-to-real-hidden/Makefile mode change 100755 => 100644 unit-tests/test-cases/tentative-to-real-hidden/test.c mode change 100755 => 100644 unit-tests/test-cases/tentative-to-real/Makefile mode change 100755 => 100644 unit-tests/test-cases/tentative-to-real/comment.txt mode change 100755 => 100644 unit-tests/test-cases/tentative-to-real/test.c mode change 100755 => 100644 unit-tests/test-cases/thumb-blx/Makefile mode change 100755 => 100644 unit-tests/test-cases/thumb-blx/test.c create mode 100644 unit-tests/test-cases/thumb-pointer/Makefile create mode 100644 unit-tests/test-cases/thumb-pointer/bar.c create mode 100644 unit-tests/test-cases/thumb-pointer/foo.c mode change 100755 => 100644 unit-tests/test-cases/undefined-dynamic-lookup/Makefile mode change 100755 => 100644 unit-tests/test-cases/undefined-dynamic-lookup/main.c create mode 100644 unit-tests/test-cases/unexported_symbols_list-r/Makefile create mode 100644 unit-tests/test-cases/unexported_symbols_list-r/foo.c create mode 100644 unit-tests/test-cases/unexported_symbols_list-r/foo.exp mode change 100755 => 100644 unit-tests/test-cases/visibility-warning-dylib-v-archive/Makefile mode change 100755 => 100644 unit-tests/test-cases/visibility-warning-dylib-v-archive/bar.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning-dylib-v-archive/foo.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning-dylib-v-archive/main.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning/Makefile mode change 100755 => 100644 unit-tests/test-cases/visibility-warning/foo.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning/foo_hidden.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning/foo_weak.c mode change 100755 => 100644 unit-tests/test-cases/visibility-warning/foo_weak_hidden.c create mode 100644 unit-tests/test-cases/weak-def-flag/Makefile create mode 100644 unit-tests/test-cases/weak-def-flag/main.c mode change 100755 => 100644 unit-tests/test-cases/weak-def-ordinal/Makefile mode change 100755 => 100644 unit-tests/test-cases/weak-def-ordinal/bar.c mode change 100755 => 100644 unit-tests/test-cases/weak-def-ordinal/foo.c mode change 100755 => 100644 unit-tests/test-cases/weak-def-ordinal/main.c mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/Makefile mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/bar.c mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/bar.h mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/foo.c mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/foo.h mode change 100755 => 100644 unit-tests/test-cases/weak_dylib/main.c create mode 100644 unit-tests/test-cases/weak_import-force/Makefile create mode 100644 unit-tests/test-cases/weak_import-force/bar.c create mode 100644 unit-tests/test-cases/weak_import-force/foo.c create mode 100644 unit-tests/test-cases/weak_import-force/main.c mode change 100755 => 100644 unit-tests/test-cases/weak_import/Makefile mode change 100755 => 100644 unit-tests/test-cases/weak_import/foo.c mode change 100755 => 100644 unit-tests/test-cases/weak_import/foo.h mode change 100755 => 100644 unit-tests/test-cases/weak_import/main.c mode change 100755 => 100644 unit-tests/test-cases/weak_import2/Makefile.newtest mode change 100755 => 100644 unit-tests/test-cases/weak_import2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/weak_import2/foo.c mode change 100755 => 100644 unit-tests/test-cases/weak_import2/foo.h mode change 100755 => 100644 unit-tests/test-cases/weak_import2/foo1.c mode change 100755 => 100644 unit-tests/test-cases/weak_import2/main.c mode change 100755 => 100644 unit-tests/test-cases/weak_import3/Makefile mode change 100755 => 100644 unit-tests/test-cases/weak_import3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/weak_import3/foo.c mode change 100755 => 100644 unit-tests/test-cases/weak_import3/foo.h mode change 100755 => 100644 unit-tests/test-cases/weak_import3/foo1.c mode change 100755 => 100644 unit-tests/test-cases/weak_import3/main.c mode change 100755 => 100644 unit-tests/test-cases/why_live/Makefile mode change 100755 => 100644 unit-tests/test-cases/why_live/bar.c mode change 100755 => 100644 unit-tests/test-cases/why_live/foo.c mode change 100755 => 100644 unit-tests/test-cases/why_live/main.c mode change 100755 => 100644 unit-tests/test-cases/zero-fill/Makefile mode change 100755 => 100644 unit-tests/test-cases/zero-fill/test.c mode change 100755 => 100644 unit-tests/test-cases/zero-fill2/Makefile mode change 100755 => 100644 unit-tests/test-cases/zero-fill2/comment.txt mode change 100755 => 100644 unit-tests/test-cases/zero-fill2/test.c mode change 100755 => 100644 unit-tests/test-cases/zero-fill3/Makefile mode change 100755 => 100644 unit-tests/test-cases/zero-fill3/comment.txt mode change 100755 => 100644 unit-tests/test-cases/zero-fill3/test.c diff --git a/APPLE_LICENSE b/APPLE_LICENSE old mode 100755 new mode 100644 diff --git a/ChangeLog b/ChangeLog old mode 100755 new mode 100644 index 62ac23d..79dcc59 --- a/ChangeLog +++ b/ChangeLog @@ -1,504 +1,4534 @@ -2008-05-06 Nick Kledzik +----- Tagged ld64-95.2.12 - ARM ld should take W bit off of maxprot for __TEXT segment - * src/MachOWriterExecutable.hpp: for iPhone always set maxprot to be initprot in all segments +2009-07-02 Nick Kledzik + creation of __unwind_info section can fail if hundreds of functions cannot be compact encoded -2008-05-06 Nick Kledzik - encryptable images may not be signable - * src/MachOWriterExecutable.hpp: use minimum header padding when aligning __text section - +----- Tagged ld64-95.2.11 ------ Tagged ld64-85 +2009-06-19 Nick Kledzik -2008-04-29 Nick Kledzik + Link Time Optimization errors out when targeting < 10.6 - * ld64.xcodeproj/project.pbxproj: is moving from /usr/local/include to /Developer/usr/local/include +----- Tagged ld64-95.2.10 -2008-04-29 Nick Kledzik +2009-04-02 Nick Kledzik - ld doesn't honor "rightmost" -syslibroot argument - * src/Options.cpp: if last -syslibroot is /, then ignore all syslibroots + corrupt metaclass entry in dynamic library + * src/ld/ld.cpp: change Section constructor to copy segment and section names -2008-04-29 Nick Kledzik - - GLRendererFloat has bad __eh_frame section caused by mixing llvm-gcc and gcc object files - * src/MachOReaderRelocatable.hpp: make all atoms in __eh_frame section have 1-byte alignment - * src/MachOWriterExecutable.hpp: make __eh_frame section have pointer sized alignment +----- Tagged ld64-95.2.9 +2009-04-02 Nick Kledzik -2008-04-17 Nick Kledzik + Update ld64 for new triples introduced in 6654669 to support ARM LLVM + * src/ld/LTOReader.hpp: change "arm-" to "arm" so matching works for new triples - * src/MachOReaderRelocatable.hpp: better cpu subtype support +----- Tagged ld64-95.2.8 -2008-04-14 Nick Kledzik - - ld64 has bad ARM branch island check - * src/MachOWriterExecutable.hpp: in addBranchIslands() don't force large arm programs to fail - +2009-03-24 Nick Kledzik -2008-04-10 Nick Kledzik + anonymous functions have the compact unwind info computed wrong + * ld/MachOReaderRelocatable.hpp: use new compact unwind function in AnonymousAtom - * src/MachOWriterExecutable.hpp: fix stubs used with lazy dylibs - ------ Tagged ld64-84.4 +----- Tagged ld64-95.2.7 -2008-04-10 Nick Kledzik +2009-03-11 Nick Kledzik - SPEC2000/eon built with -mdynamic-no-pic won't run - * src/Architectures.hpp: added arm::kReadOnlyPointer - * src/MachOReaderRelocatable.hpp: generate arm::kReadOnlyPointer - * src/MachOWriterExecutable.hpp: use arm::kReadOnlyPointer - * src/machochecker.cpp: allow MH_PIE bit - * unit-tests/test-cases/switch-jump-table: added test cases + AddressBook incorrectly gets _objc_msgSend from WebKit + * src/ld/MachOReaderDylib.hpp: fix processIndirectLibraries() to not force a private re-export of a dylib + that is already explictly or implicitly linked. + * unit-tests/test-cases/re-export-optimizations-indirect: add test case ------ Tagged ld64-84.3 +2009-03-10 Nick Kledzik -2008-04-09 Nick Kledzik - - -undefined dynamic_lookup busted - * src/ld.cpp: don't create proxy atom when scanning for dylib duplicates - * unit-tests/test-cases/tentative-and-archive: use -undefined dynamic_lookup + dyld weak linking optimization leaves some symbols unbound + * src/ld/MachOWriterExecutable.hpp: be sure to create bind entry for a reference + to a symbol in a dylib that is a weak definition + * unit-tests/test-cases/coalesce_weak_def_in_dylib: add test case ------ Tagged ld64-84.2 +2009-03-10 Nick Kledzik -2008-04-04 Nick Kledzik + many OS i386 OS dylibs still have __IMPORT segment + * ld/MachOReaderRelocatable.hpp: moved where __IMPORT/__pointer is changed to __DATA/__nl_symbol_ptr + * unit-tests/test-cases/stripped-indirect-symbol-table: updated to test for this problem - * src/ld.cpp: don't add .eh symbols to symbol table in -r mode - * unit-tests/test-cases/eh-coalescing-r: update to test out of order coalescing + +----- Tagged ld64-95.2.6 + +2009-02-27 Nick Kledzik + + ld might set MH_WEAK_DEFINES when it should not + * src/ld/MachOWriterExecutable.hpp: only consider atoms in fRegularDefAtomsThatOverrideADylibsWeakDef + that will be exported when computing MH_WEAK_DEFINES + * unit-tests/test-cases/operator-new: updated to reproduce issue ------ Tagged ld64-84.1 +----- Tagged ld64-95.2.5 -2008-03-28 Nick Kledzik +2009-02-24 Nick Kledzik - ld should prefer architecture-specific variant over generic in fat object file - * src/Options.cpp: fully process -arch arguments into fArchitecture and fSubArchitecture - * src/ld.cpp: when -arch with a subtype is used, try to find the exact subtype from fat files - * unit-tests/test-cases/cpu-sub-types-preference: added test cases for arm and ppc + x86_64 obj-c runtime confused when static lib is stripped + * src/ld/MachOWriterExecutable.hpp: in setLocalNlist() don't use 'l' labels for x86_64 strings + * unit-tests/test-cases/objc-literal-pointers-strip: added test case ------ Tagged ld64-84 +----- Tagged ld64-95.2.4 -2008-03-28 Nick Kledzik +2009-02-23 Nick Kledzik - * src/LTOReader.hpp: don't print lto version, if lto is unavailable + * src/ld/MachOReaderRelocatable.hpp: ignore ARM_THUMB_32BIT_BRANCH relocs + + +2009-02-18 Nick Kledzik + + Writer::symbolIndex() uses a linear search and does not scale + * src/ld/MachOWriterExecutable.hpp: build a std::map so symbolIndex() scales better -2008-03-26 Nick Kledzik +2009-02-18 Nick Kledzik - Add LD_WARN_COMMONS to BigBear builds - * src/Options.cpp: Add support for LD_WARN_FILE which copies all warnings to a side file + Use new compact encodings that handle all register permutations + * src/ld/Architectures.hpp: add kSectionOffset24 + * src/ld/ObjectFile.h: add getFDE() + * src/ld/MachOReaderRelocatable.hpp: use new libunwind functions to get new compact encoding + * src/ld/MachOWriterExecutable.hpp: use new compact encoding which includes offset in dwarf if needed + * src/other/unwinddump.cpp: update unwinddump output to display register save set -2008-03-26 Nick Kledzik +2009-02-16 Nick Kledzik - Need encryption tag in mach-o file - linker should adjust arm final linked images so __text is never on the same page as the load commands - * src/MachOFileAbstraction.hpp: add support for encryption_info_command - * src/Options.cpp: add support for LD_NO_ENCRYPT and -no_encryption - * src/MachOWriterExecutable.hpp: add EncryptionLoadCommandsAtom - * src/machochecker.cpp: validate LC_ENCRYPTION_INFO + runtime error with bundle for 10.5 that has weak external symols + * src/ld/ld.cpp: fix hybrid (10.5) compressed linkedit info for data pointing to weak definitions -2008-03-25 Nick Kledzik +2009-02-15 Nick Kledzik - ld64 does not recognize LLVM bitcode archive files - * src/MachOReaderArchive.hpp: renamed to src/ArchiveReader.hpp - * src/ArchiveReader.hpp: sniff each member and instantiate correct reader - * src/ld.cpp: rename mach_o::archive::Reader to archive::Reader - * ld64.xcodeproj/project.pbxproj: rename MachOReaderArchive.hpp to ArchiveReader.hpp - * unit-tests/test-cases/llvm-integration: added test case + i386 relocation error with negative offsets from local labels + * src/ld/MachOReaderRelocatable.hpp: handle when base addr of scattered relocation does not point to a label + * unit-tests/test-cases/relocs-neg-from-local: add test case + +2009-02-12 Nick Kledzik -2008-03-25 Nick Kledzik + -dead_strip inhibits weak coalescing in no_dead_strip section + * src/ld/ld.cpp: remove atoms coalesced away from fLiveRootAtoms + * unit-tests/test-cases/dead_strip-weak-coalesce: added test case - ld64 should switch to new libLTO.dylib interface - Produce llvm bc file in 'ld -r' mode if all .o files are llvm bc - * src/LTOReader.hpp: rewrite from LLVMReader.hpp to use new lto_* C interface - * unit-tests/test-cases/llvm-integration: update and comment - * ld64.xcodeproj/project.pbxproj: update to lazy load libLTO.dylib - * src/ld.cpp: rework and simplify Linker::optimize() - * src/ObjectDump.cpp: Add -nm option + +2009-02-12 Nick Kledzik + + x86_64 weak_import broken for initialized data + * src/ld/MachOReaderRelocatable.hpp: use isWeakImportSymbol() in Reader::addRelocReference() + * src/other/dyldinfo.cpp: update to display weak_import attribute + * unit-tests/test-cases/weak_import: updated test case -2008-03-25 Nick Kledzik +2009-02-06 Nick Kledzik - * src/MachOReaderRelocatable.cpp: Fix some .objc_class_name_ off by one problem - * src/MachOWriterExecutable.cpp: Fix some .objc_class_name_ off by one problem + ld parsing of __eh_frame unwind information is slow + * src/ld/MachOReaderRelocatable.hpp: build a std::map of all __eh_frame relocations for x86_64 -2008-03-24 Nick Kledzik +----- Tagged ld64-95.2.3 - Xcode 3.1 breaks linkage of libgcj.9.dylib from gcc 4.3.0 - * src/MachOWriterExecutable.cpp: Make sure all ivars in Writer are initialized. +2009-02-04 Nick Kledzik + ld: warning: can't add line info to anonymous symbol + * src/ld/MachOReaderRelocatable.hpp: don't warn about line info in dyld stubs -2008-03-21 Nick Kledzik - * src/Options.cpp: warn if -seg1addr value is not page aligned - +----- Tagged ld64-95.2.2 -2008-03-21 Nick Kledzik +2009-02-02 Nick Kledzik - Move ARM support outside of __OPEN_SOURCE__ - * src/ld.cpp: remove __OPEN_SOURCE__ around arm support - * src/LLVMReader.hpp: remove __OPEN_SOURCE__ around arm support - * src/MachOReaderDylib.hpp: remove __OPEN_SOURCE__ around arm support - * src/ObjectFile.h: remove __OPEN_SOURCE__ around arm support - * src/MachOReaderRelocatable.hpp: remove __OPEN_SOURCE__ around arm support - * src/OpaqueSection.hpp: Cover arm support inside __OPEN_SOURCE__ macro check - * src/MachOWriterExecutable.hpp: remove __OPEN_SOURCE__ around arm support - * src/ObjectDump.cpp: remove __OPEN_SOURCE__ around arm support - * ld64.xcodeproj/project.pbxproj: remove ARM_SUPPORT from config.h - + ld -r does not preserve the N_NO_DEAD_STRIP bit + * src/ld/MachOWriterExecutable.hpp: set N_NO_DEAD_STRIP based on dontDeadStrip() + * unit-tests/test-cases/dead_strip-r_symbol_desc: added test case ------ Tagged ld64-83.2 + +----- Tagged ld64-95.2.1 + +2009-01-29 Nick Kledzik + + ld coalesces C strings in different segments + * src/ld/MachOReaderRelocatable.hpp: only do standard coalescing on __cstring section if is in __TEXT segment + * unit-tests/test-cases/cstring-alt-segment: add test case -2008-03-15 Nick Kledzik + +2009-01-29 Nick Kledzik + + gcc DejaGnu failure: building longcall/dylib library + * src/ld/MachOWriterExecutable.hpp: if no __DATA sections insert non-lazy pointers at end of __TEXT segment + * unit-tests/test-cases/no-data-bundle: added test case + + +----- Tagged ld64-95.2 + +2009-01-06 Nick Kledzik + + strip -S fails with "new trie is larger than original" + * src/other/PruneTrie.cpp: don't align trie more than original trie was aligned - ld64-83 removes OBJC_CLASS_$ symbols from projects, causes catastrophic results - * src/Options.cpp: restore "case CPU_TYPE_ARM" in switch statement for .objc_class symbols in .exp files - * unit-tests/test-cases/objc-exported_symbols_list: added test case + +----- Tagged ld64-95.1 + +2008-12-21 Nick Kledzik + + * src/ld/MachOWriterExecutable.hpp: in new linkedit format, make sure only exported symbols + make it into weak binding info ------ Tagged ld64-83.1 +----- Tagged ld64-95 -2008-03-14 Nick Kledzik +2008-12-18 Nick Kledzik - -iphone_version_min ==> -iphoneos_version_min - * src/Options.cpp: support -iphoneos_version_min as well + * src/ld/Options.cpp: move check for fSharedRegionEligible until fPrebind has stabilized ------ Tagged ld64-83 - -2008-03-10 Nick Kledzik +2008-12-18 Nick Kledzik - ld needs to strip iphone_version_min option if invoking ld_classic - * src/Options.cpp: suppress -iphone_version_min from being passed to ld_classic + Generate new compressed LINKEDIT when targeting 10.6 + * src/ld/Options.cpp: turn on compressed LINKEDIT by default -2008-03-04 Nick Kledzik +----- Tagged ld64-94.1 - ADOBE XCODE: Linker option to lazy load frameworks (cause dyld is too slow) - * src/MachOWriterExecutable.hpp: create lazy stubs and LC_LAZY_LOAD_DYLIB for lazy load dylibs - * src/Options.cpp: support -lazy-l, -lazy_library, and -lazy_framework - * src/MachOFileAbstraction.hpp: add LC_LAZY_LOAD_DYLIB and S_LAZY_DYLIB_SYMBOL_POINTERS until in cctools - * src/MachOReaderDylib.hpp: add isLazyLoadedDylib() - * src/ld.cpp: pass lazy helper atom to writer - * doc/man/man1/ld.1: document new options - * unit-tests/test-cases/lazy-dylib-objc: add test case - * unit-tests/test-cases/lazy-dylib: add test case - +2008-12-16 Nick Kledzik ------ Tagged ld64-82.7 + * src/ld/Options.cpp: Fix -F handling in buildSearchPaths() -2008-03-07 Nick Kledzik - duplicate symbol literal-pointer@__OBJC@__message_refs@... - * src/MachOReaderRelocatable.hpp: AnonymousAtom from S_LITERAL_POINTERS section should be weak - * unit-tests/test-cases/objc-selector-coalescing: added test case +----- Tagged ld64-94 + +2008-12-15 Nick Kledzik + * doc/man/man1/ld.1: document new options ------ Tagged ld64-82.6 -2008-03-04 Nick Kledzik +2008-12-15 Nick Kledzik - ld crashes building XsanFS for Snow Leopard Builds - * src/ld.cpp: add bool dylibsOnly parameter to addJustInTimeAtoms() - * unit-tests/test-cases/tentative-and-archive: added test case + linker should enforce all .o files have same sub-type, and ignore sub-type of dylibs + * doc/man/man1/ld.1: update man page about -allow_sub_type_mismatches + * src/ld/ld.cpp: call validFile() with new arguments + * src/ld/MachOReaderRelocatable.hpp: add new arguments to validFile() + * src/ld/Options.cpp: Support LD_ALLOW_CPU_SUBTYPE_MISMATCHES and -allow_sub_type_mismatches -2008-03-04 Nick Kledzik - ld64 should not force building with gcc 4.0 - * ld64.xcodeproj/project.pbxproj: change rules to use "system" compiler instead of 4.0 - +2008-12-15 Nick Kledzik -2008-02-29 Nick Kledzik + -syslibroot should skip standard search paths not in the SDK + * src/ld/Options.cpp: in buildSearchPaths() if an SDK is specified don't add + standard search paths not in the SDK. - Simulator frameworks are being build split-seg and not prebound - * src/Options.cpp: only splitseg if prebound +2008-12-15 Nick Kledzik -2008-02-29 Nick Kledzik + ld: remove "can't make compact unwind encoding" warning + * src/ld/ObjectFile.h: add fWarnCompactUnwind + * src/ld/Options.cpp: -warn_compact_unwind --> fWarnCompactUnwind + * src/ld/MachOReaderRelocatable.hpp: test fWarnCompactUnwind before warning - Linker should not make GSYM debug note for .objc_category_* symbols - * src/ld.cpp: suppress GSYM debug notes for absolute symbols - * unit-tests/test-cases/objc-category-debug-notes: added test case +2008-12-15 Nick Kledzik -2008-02-29 Nick Kledzik + Add dtrace usdt support for arm to ld64 + * src/ld/MachOWriterExecutable.hpp: handle arm::kDtraceIsEnabledSite + * unit-tests/test-cases/dtrace-static-probes: use is-enabled in test case - non-ASCII CFString support is broken - * src/MachOReaderRelocatable.hpp: only name and coalesce cfstring constants if they use a __cstring - * unit-tests/test-cases/cfstring-utf16: add test case +----- Tagged ld64-93 -2008-02-25 Nick Kledzik +2008-12-11 Nick Kledzik - ld -r -x - * doc/man/man1/ld.1: update man page to explain -r -x produces auto-stripped labels + * src/ld/ObjectFile.h: add fIPhoneVersionMin to track min iPhoneOS version + * src/ld/Options.cpp: use fIPhoneVersionMin + +2008-12-11 Nick Kledzik ------ Tagged ld64-82.5 + non-lazy pointer to non-global tentative definition encoded wrong + * src/ld/MachOWriterExecutable.hpp: don't use INDIRECT_SYMBOL_LOCAL for tentative definitions + * unit-tests/test-cases/non-lazy-r: updated test case -2008-02-12 Nick Kledzik - x86_64: -stack_size failure when large __bss is used - * src/ld.cpp: only move section already in __DATA segment to new __huge section - * unit-tests/test-cases/stack_size_no_addr: updated test case to add large bss section +2008-12-11 Nick Kledzik + + kernel fails to boot when ld64 used for intermediate ld -r step + * src/ld/MachOWriterExecutable.hpp: in -r mode when generating a scattered sect-diff reloc for + i386/arm, special case when from target is not the atom + the relocation is in. + * unit-tests/test-cases/relocs-asm: update test case ------ Tagged ld64-82.4 +2008-12-11 Nick Kledzik -2008-02-06 Nick Kledzik - - comdat warnings with ld -r of C++ .o files - * unit-tests/test-cases/eh-coalescing-r: added test case - * src/ld.cpp: in ld -r mode don't warn about if .eh symbols are not static - + * src/ld/ld.cpp: handle new __program_vars section + * src/ld/MachOWriterExecutable.hpp: handle inserting synthesized sections when there is no __dyld section -2008-02-06 Devang Patel - LTO of Bom framework with -dead_strip causes ld(1) crash - * src/LLVMReader.hpp: Check fAtom while determining LLVMReference target binding. - * unit-tests/test-cases/llvm-integration/Makefile: Add new test case. - * unit-tests/test-cases/llvm-integration/a15.c: New. - * unit-tests/test-cases/llvm-integration/b15.c: New. - * unit-tests/test-cases/llvm-integration/c15.c: New. - -2008-02-05 Nick Kledzik +2008-12-11 Nick Kledzik - * src/ld.cpp: fix for -arch ppc -mdynamic-no-pic -pie so PPC_RELOC_HA16 reloc is used + * src/ld/MachOReaderRelocatable.hpp: Fix getDescription() to work when direct reference is to anonymous atom + + +2008-12-10 Nick Kledzik + + * src/ld/Options.cpp: enable LD_FORCE_NO_PREBIND to be used with arm + + +2008-12-10 Nick Kledzik ------ Tagged ld64-82.3 + Developer tool to print the new compressed LINKEDIT information + * src/other/dyldinfo.cpp: fix typo in usage() -2008-02-04 Nick Kledzik - ld doesn't seem to understand $ld$add$os... and $ld$hide$os... for 10.6 moves - * src/ObjectFile.h: add 10.6 - * src/Options.cpp: add 10.6 support - * src/MachOReaderDylib.hpp: recognize $os10.6$ - +2008-12-05 Nick Kledzik ------ Tagged ld64-82.2 + SnowLeopard kernel should compile warning free + * src/ld/MachOReaderRelocatable.hpp: correct parse two global labels at end of section and make one an alias + * unit-tests/test-cases/end-label: update test case -2008-01-30 Devang Patel - Can't build 64-bit Intel binaries with LTO - ld64 fails to build with llvm-gcc-4.2 - * src/LLVMReader.hpp: Fix character count typo in strncmp call. - Use const char * to initialize temp. string. - * ld64.xcodeproj/project.pbxproj: use $(DEVELOPER_DIR) in header search construction - instead of hard coding /Developer. - ------ Tagged ld64-82.1 +2008-12-04 Nick Kledzik -2008-01-23 Nick Kledzik + Better warning than "PPC_RELOC_JBSR should not be using an external relocation" + * src/ld/MachOReaderRelocatable.hpp: issue warning with .o path if it was compiled with -mlong-branch - * src/MachOReaderRelocatable.hpp: don't bus error if S_LITERAL_POINTERS is missing relocs + +2008-12-04 Nick Kledzik + linker should not map __pointers -> __nl_symbol_ptr unless actually making new LINKEDIT + * src/ld/ObjectFile.h: add fMakeCompressedDyldInfo for readers to see + * src/ld/Options.cpp: set fMakeCompressedDyldInfo for readers to see + * src/ld/MachOReaderRelocatable.hpp: check fMakeCompressedDyldInfo -2008-01-22 Nick Kledzik - ld uses 32-bits in some places to hold addresses when parsing 64-bit mach-o files - * src/MachOReaderRelocatable.hpp: use AddrToAtomMap type that switch address to 64-bits for 64-bit archs - * src/MachOWriterExecutable.hpp: verify BR14 does not overflow for external relocs - * unit-tests/test-cases/relocs-c: update test case to slide addresses to verify x86_64 .o files +2008-12-02 Nick Kledzik + * src/ld/debugline.c: fix error handling in line_open() ------ Tagged ld64-82 - -2008-01-18 Nick Kledzik - Bad grammar used in ld warning: cannot exported hidden symbol - * src/ld.cpp: fix typo in warning string - +2008-11-26 Nick Kledzik -2008-01-16 Nick Kledzik + vtable with thumb entries broke after ld -r + * src/ld/MachOReaderRelocatable.hpp: if target of reloc is thumb, mask thumb bit off addend + * unit-tests/test-cases/thumb-pointer: added test case - Bundle Loader does not work anymore when loader is a bundle - ld warns of incorrect architecture when linking a bundle to a bundle - * src/MachOReaderDylib.hpp: support linking against bundles via -bundle_loader. Clean up error messages - * unit-tests/test-cases/bundle_loader: update test case - - -2008-01-16 Nick Kledzik - - ld -r -x creates debug notes (stabs) when it should not with -x (keep only global symbols) - * src/Options.cpp: in reconfigureDefaults() if -r and -x then -S - -2008-01-16 Nick Kledzik +2008-11-26 Nick Kledzik - if ld crashes while writing output file, it should delete the half written file - * src/MachOWriterExecutable.hpp: wrap open/write/close in try block and add signal handlers all to delete - output file on failure. + * src/ld/Option.cpp: Fix how crashreporterBuffer is created to not miss some arguments -2008-01-16 Devang Patel +2008-11-24 Nick Kledzik - * src/LLVMReader.hpp: Use __gnu_cxx::hash_map instead of hash supported by LLVM. + Security.framework has some duplicate FDEs for some functions + * src/ld/ld.cpp: remove fDeadAtoms from fLiveAtoms when there are weak atoms overriden by late loads + * unit-tests/test-cases/dead_strip-archive-eh: added test case -2008-01-16 Nick Kledzik +----- Tagged ld64-92 - GC-supported library can't be linked into GC-required executable - * src/ld.cpp: loosen constraint that all objc code must be compiled with same GC settings and - allow gc-compatible code to be linked into anything. - * unit-tests/test-cases/objc-gc-checks: update test case +2008-11-21 Nick Kledzik + * src/ld/MachOReaderDylib.hpp: if export_size is zero, no need to parse trie + * src/abstraction/MachOTrie.hpp: gracefully handle empty trie + -2008-01-15 Nick Kledzik +2008-11-21 Nick Kledzik - no debug notes for custom named data - * src/ld.cpp: in synthesizeDebugNotes() check getSymbolTableInclusion() instead of for leading underscore - * unit-tests/test-cases/dwarf-debug-notes: update test case + strip(1) support for new compressed LINKEDIT information + * ld64.xcodeproj/project.pbxproj: build and install new libprunetrie.a + * src/other/prune_trie.h: added + * src/other/PruneTrie.cpp: implements prune_trie() ------ Tagged ld64-81.5 -2008-01-14 Devang Patel +2008-11-21 Nick Kledzik - llvm-gcc-4.2 fails to build Sqlite 3.5.4 with -O4 - * src/LLVMReader.hpp: Resolve proxy references. Collect new unbounded references - after optimization. - * src/ld.cpp: Resolve additional unbounded references after optimization. + * src/ld/ld.cpp: if an export file is used and all weak symbols are masked, don't set WEAK_DEFINES + * unit-tests/test-cases/weak-def-flag: added test case + + +2008-11-20 Nick Kledzik + + Generate new compressed LINKEDIT when targeting 10.6 + * src/ld/MachOWriterExecutable.hpp: support generating new compressed format + * src/ld/MachOReaderRelocatable.hpp: new compress format implies non-lazy pointers in __DATA for i386 + * src/ld/MachOReaderDylib.hpp: support linking aginst new format + * src/ld/Options.cpp: suppport -exported_symbols_order and -no_compact_linkedit + * src/ld/ld.cpp: track which atoms have weak counter parts in dylibs + * src/other/dyldinfo.cpp: added tool to display new LINKEDIT format + * ld64.xcodeproj/project.pbxproj: add dyldinfo tool + * unit-tests/*: lots of fixes to work with new format + + +2008-11-20 Nick Kledzik + + ld64 should preserve N_WEAK_REF when linking MH_KEXT_BUNDLEs + * src/ld/MachOWriterExecutable.hpp: set up fWeakImportMap in synthesizeKextGOT() + + +2008-11-19 Nick Kledzik + + VideoToolbox.framework has bad __TEXT.__eh_frame info + * src/ld/Options.cpp: add -no_eh_labels option for use with -r + * src/ld/MachOWriterExecutable.hpp: generate correct x86_64 labeless relocs in -r mode + * src/ld/MachOReaderRelocatable.hpp: now ignore all labels and relocations in + __TEXT/__eh_frame section and rely on getCFIs() from libunwind + * unit-tests/test-cases/eh-coalescing-no-labels: add test case + + +2008-11-19 Nick Kledzik + + LTO doesn't like dtrace symbols + * src/ld/LTOReader.hpp: ignore __dtrace_probe undefines in bitcode files -2008-01-14 Nick Kledzik +2008-11-14 Nick Kledzik - PPC Leopard (Xcode 3.0) linker ld gets "Bus error" sometimes - * src/MachOReaderRelocatable.hpp: use same code as x86 to parse ppc and arm sect-diff relocs - * src/MachOWriterExecutable.hpp: use same code as x86 to write ppc and arm sect-diff relocs + * src/abstraction/MachOFileAbstraction.hpp: fix to work with 10.5 headers + +----- Tagged ld64-91 -2008-01-11 Nick Kledzik +2008-11-07 Nick Kledzik - PPC Leopard (Xcode 3.0) linker ld reports "unknown scattered relocation type 4" - * src/MachOReaderRelocatable.hpp: add PPC_RELOC_HI16 to scattered reloc parsing - * unit-tests/test-cases/relocs-asm/relocs-asm.s: added tests for scattered hi/lo instructions + Remove COMPACT_UNWIND_SUPPORT conditionalizing -2008-01-11 Nick Kledzik +2008-11-06 Nick Kledzik - * doc/man/man1/ld.1: add doc for -no_implicit_dylibs, -read_only_stubs, -slow_stubs, -interposable_list + Reorganize source layout. ld sources are now in "ld", + and other tools are in "other". + + +2008-11-05 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: start installing unwinddump tool + * src/UnwindDump.cpp: support -arch option + * doc/man/man1/unwinddump.1: create man page + + +2008-11-05 Nick Kledzik + + linker should put cpusubtype in n_sect field of nlist entry for N_OSO debug note entries + * src/ld.cpp: in synthesizeDebugNotes() set other field of OSO to be subtype + + +2008-11-05 Nick Kledzik + + Need a linker option to load all objects from one library + * src/Options.cpp: support -force_load option + * src/ArchiveReader.hpp: Add fForceLoad ivar + * doc/man/man1/ld.1: update man page with -force_load option + * unit-tests/test-cases/archive-force-load: add test case + + +2008-11-05 Nick Kledzik + + Dtrace Probe Warnings: SnowLeopard kernel should compile warning free + * src/ld.cpp: don't generate GSYM stabs for old style __dtrace_probe + * src/MachOReaderRelocatable.hpp: fix test for deciding if a symbol is an alias + +2008-11-04 Nick Kledzik + + ADOBE: XCODE: ld: duplicate typeinfo in executable + * src/ld.cpp: in dead-strip mode, record overriden symbols and later rebind all uses + * unit-tests/test-cases/dead_strip-archive-weak: add test case -2008-01-11 Nick Kledzik - ld64(1) man page uses ambiguous term "suffix" - * doc/man/man1/ld.1: make meaning of "suffix" more explicit +2008-11-03 Nick Kledzik + + support increased branch range in Thumb-2 + * src/MachOReaderRelocatable.hpp: handle full branch range in addRelocReference() + * unit-tests/test-cases/branch-distance: added test case +2008-10-31 Devang Patel -2008-01-11 Nick Kledzik + Sqlite 3.5.4 built with lvm-gcc-4.2 -O4 fails regression test + * src/LTOReader.hpp: Use real atom scope when real atom is available. + Preserve globals while optimizing an executable. - Obj-C Symbols in Leopard Can't Be Weak Linked - * src/MachOWriterExecutable.hpp: set weak and lazy attributes on dummy .objc_class_name undefines - to dylibs to support Mac OS X 10.3.x dyld - +2008-10-30 Nick Kledzik -2008-01-11 Nick Kledzik + * src/MachOReaderRelocatable.hpp: support all encodings in getEncodedP() - Unknown error with linker (dyld: unknown external relocation type) - * src/ld.cpp: fix crash when SO stabs are not balanced + +----- Tagged ld64-90 + +2008-10-30 Nick Kledzik + + icc has dwarf unwind info that is different than gcc + * src/MachOReaderRelocatable.hpp: support more encodings in getEncodedP() + + +2008-10-23 Nick Kledzik + + build ld64 for x86_64 + * ld64.xcodeproj/project.pbxproj: add X86_64 to valid archs -2008-01-11 Devang Patel +2008-10-23 Nick Kledzik - LTO does not work if expected output is a dynamic library - * src/LLVMReader.hpp: Supply arguments describing output kind to optimizer. Communicate - visibility info. + * ld64.xcodeproj/project.pbxproj: use generated @$(DERIVED_FILE_DIR)/linker_opts for extra + linker options. This allows linker to be built if LTO headers and libs are missing. -2000-01-10 Nick Kledzik - __cls_refs section is losing S_LITERAL_POINTERS section type - * src/MachOWriterExecutable.hpp: special case __cls_refs section - * unit-tests/test-cases/objc-literal-pointers: add test case +2008-10-23 Nick Kledzik + Linker warning not shown in the Xcode build log + * src/Options.cpp: add colon to format string in warning() -2008-01-03 Nick Kledzik - wrong EH information might be used - Created new kGroupSubordinate reference kind to model group comdat. The "signature" atom - has kGroupSubordinate references to the other atoms in the group. If the signature atom - is coalesced away, the linker follows kGroupSubordinate references and throws away the - other members of the group. - * unit-tests/test-cases/eh-coalescing: added test case - * src/ld.cpp: added markDead() and use propagate to subordinates - * src/Architectures.hpp: added kGroupSubordinate - * src/MachOReaderRelocatable.hpp: add kGroupSubordinate reference from a function to its .eh atom - and if used, from .eh atom to its LSDA atom. - * src/MachOWriterExecutable.hpp: handle kGroupSubordinate like kNoFixUp +----- Tagged ld64-89.3 ------ Tagged ld64-81.4.1 +2008-10-24 Nick Kledzik + + ld64-89 broke TOT OpenGL libProgrammability x86_64 build + * src/MachOReaderRelocatable.hpp: add cast in getEncodedP() + -2007-12-19 Devang Patel +----- Tagged ld64-89.2 - * src/LLVMReader.hpp: Add LLVM_LTO_VERSION #ifdef check. +2008-10-23 Nick Kledzik + + SnowLeopard: Libsystem built with ld64-89.1 causes crashes + * src/MachOReaderRelocatable.hpp: when FDE information causes __text atom to be split, make the + atoms follow-on pairs. + + +----- Tagged ld64-89.1 + +2008-10-22 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: for x86_64 __eh_frame force direct references -2007-12-19 Devang Patel - * src/LLVMReader.hpp: Add fOptimizer NULL check before calling printVersion(). +2008-10-21 Nick Kledzik + + * src/ObjectDump.cpp: Use getContentType() to see if content type is a cstring -2007-12-19 Devang Patel - print LLVM LTO version number in verbose mode - * src/LLVMReader.hpp: Add printLLVMVersion() to print llvm version string in verbose mode. - * src/Options.cpp: Use printLLVMVersion() in verbose mode. +----- Tagged ld64-89 -2007-12-19 Devang Patel +2008-10-21 Nick Kledzik - print LLVM LTO version number in verbose mode - * src/Options.h: Add verbose() method to check fVerbose flag. - * src/LLVMReader.hpp: Print LLVM version string in verbose mode. + 10A180 with QT-1119 roots: iTunes and QuickTime cannot play back purchased videos + linker should not need .eh labels + * src/MachOWriterExecutable.hpp: use kCFIType to set section attributes + * src/MachOReaderRelocatable.hpp: use libunwind's CFITuple to parse __eh_frame content + * src/ld.cpp: Add adjustScope() phase instead of demoting scope within symboltable.add() + * unit-tests/test-cases/eh-stripped-symbols: added test case + + +----- Tagged ld64-88.1 + +2008-10-16 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: Fix uses of COMPACT_UNWIND_SUPPORT + * src/MachOWriterExecutable.hpp: Fix uses of COMPACT_UNWIND_SUPPORT + + +2008-09-30 Nick Kledzik + + OBJC2: Reorder __DATA,__objc_* sections by writedness + * src/ld.cpp: change sorting order of Sections + + +2008-09-29 Nick Kledzik + + Executable produced by XCode 3.2 on 10.6 crashes on 10.3.9 + * src/MachOWriterExecutable.hpp: set objc_module_info_addr field of module table ------ Tagged ld64-81.4 -2007-12-18 Devang Patel +----- Tagged ld64-88 - * src/LLVMReader.hpp: Invalidate input architecture when optimizer is not available. +2008-09-25 Nick Kledzik ------ Tagged ld64-81.3 + kexts need to be built as MH_BUNDLE mach-o files + * src/ld.cpp: use getUndefinedProxyAtom() with kKextBundle + * src/MachOFileAbstraction.hpp: add MH_KEXT_BUNDLE + * src/Options.cpp: support -kext for all architectures + * src/MachOWriterExecutable.hpp: support kKextBundle to make a bundle like kext + * unit-tests/test-cases/kext-basic: added test case + -2007-12-17 Nick Kledzik +2008-09-25 Nick Kledzik - * ld64.xcodeproj/project.pbxproj: remove extraneous header search paths + ld invoking wrong ld_classic + * src/Options.cpp: first look for ld_classic relative to ld itself -2007-12-17 Devang Patel +2008-09-25 Nick Kledzik - * src/LLVMReader.hpp: Do not throw exception if LLVMReader is not able to - dlopen LTO library. Instead just flag input file as an invalid LLVM bitcode file. + ld fails to link references from 32 bit code into 64 bit code + Desired 32-bit absolute relocation + * src/Architectures.hpp: add x86_64::kPointer32 + * src/MachOReaderRelocatable.hpp: support X86_64_RELOC_UNSIGNED with length=2 + * src/MachOWriterExecutable.hpp: support x86_64::kPointer32 + * unit-tests/test-cases/relocs-asm/relocs-asm.s: added 32-bit pointer tests + +2008-09-25 Nick Kledzik + + Should be able to mark dylibs as auto-dead-dylib-strip + * src/Options.h: add fMarkDeadStrippableDylib + * src/MachOReaderDylib.hpp: check MH_DEAD_STRIPPABLE_DYLIB + * src/ObjectFile.h: add deadStrippable() + * src/MachOFileAbstraction.hpp: add MH_DEAD_STRIPPABLE_DYLIB + * src/Options.cpp: support -mark_dead_strippable_dylib + * src/MachOWriterExecutable.hpp: test reader->deadStrippable(), set MH_DEAD_STRIPPABLE_DYLIB + * doc/man/man1/ld.1: update man page + * unit-tests/test-cases/dead_strippable_dylib: added test case + -2007-12-14 Nick Kledzik +2008-09-25 Nick Kledzik - gcc DejaGnu failure: gcc.dg/20020312-2.c (test for excess errors) (-fstack-protector-all) - * src/MachOWriterExecutable.hpp: fix Writer::generatesExternalTextReloc() to allow text relocs - * unit-tests/test-cases/read-only-relocs: updated test case to link a dynamic main executable compiled with -static + ER: Add -seg_page_size option + * src/Options.cpp: add -seg_page_size option + * src/MachOWriterExecutable.hpp: use new page size info when laying out segments + * doc/man/man1/ld.1: update man page + +2008-09-24 Nick Kledzik -2007-12-14 Devang Patel + -arch_errors_fatal not working + * src/ld.cpp: check fOptions.errorOnOtherArchFiles() + * src/Options.cpp: turn -arch_errors_fatal into fOptions.errorOnOtherArchFiles() - Enable Link Time Optimization in Opal - * src/LLVMReader.hpp: Locate LLVMlto.dylib relative to ld location in Developer folder. - * ld64.xcodeproj/project.pbxproj: Add {DEVELOPER_DIR}/usr/include in header search path. - * unit-tests/run-all-unit-tests: Set DYLD_FALLBACK_LIBRARY_PATH to find LLVMlto.dylib during unit testing. - * unit-tests/testcases/llvm-integration/Makefile: Point LLVMGCC and LLVMGXX to llvm-gcc-4.2 in Developer folder during unit testing. - - -2007-12-13 Nick Kledzik - SWB: failures due to ld: pointer in read-only segment not allowed in slidable image, used in ... - * src/MachOReaderRelocatable.hpp: in Reader::addRelocReference() handle weak pc-rel 32-bit vanilla relocs properly +2008-09-24 Nick Kledzik + + CrashTracer: [USER] 1 crash in ld at ld: 0x5ce02 + * src/ld.cpp: abort if resolve() finds an unresolved reference, rather than allow a future crash ------ Tagged ld64-81.2 +2008-09-24 Nick Kledzik + + linker crashes linking X86-64 with -fwritable-strings + * src/MachOReaderRelocatable.hpp: handle unbound cfstring references + * unit-tests/test-cases/cfstring-coalesce: update test case + + +2008-09-24 Nick Kledzik + + ld64: bl out of range (-17147704 max is +/-16M) on ppc + * src/MachOWriterExecutable.hpp: tweak branch island regions to be every 14MB instead of 15MB + + +2008-09-24 Nick Kledzik + + -filelist fails with comma in path + * src/Options.cpp: in loadFileList() first try without special comma meaning + * unit-tests/test-cases/filelist/Makefile: update test case + + +2008-09-23 Nick Kledzik + + nop not used when aligning functions in -r mode + * src/MachOWriterExecutable.hpp: change check for when to pad with nops to not test segment's name + + +2008-09-23 Nick Kledzik + + "-pie can only be used when linking a main executable" should be a warning, not an error + * src/Options.cpp: make -pie on a dylib or bundle be a warning instead of an error + + +2008-09-23 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: add warning if dwarf cannot be encoded as compact unwind + + +2008-09-18 Nick Kledzik + + * src/LTOReader.hpp: re-enable use of lto_codegen_debug_options() + + +2008-09-16 Nick Kledzik + + ld does not always set S_CSTRING_LITERALS on __TEXT,__cstring + * src/MachOReaderRelocatable.hpp: add getContentType() to SymbolAtom + * src/MachOWriterExecutable.hpp: for x86_64 don't override named cstrings with LC* name + + +2008-09-10 Nick Kledzik + + * Options.cpp: add __crashreporter_info__ to communicate command line to crash reporter + * ld64.xcodeproj/project.pbxproj: leave local symbols in ld to provide better crash reports + + +2008-09-08 Nick Kledzik + + 161569 GCC 4.2 - breakpoints no longer work for a large number of functions + * src/MachOReaderRelocatable.hpp: support DW_FORM_strp out-of-line strings when parsing line table + + +2008-09-02 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix compact unwind personality for dyld and -slow_stubs + + +2008-08-29 Nick Kledzik + + -weak_library no longer forces uses to be weak_import + * src/MachOWriterExecutable.hpp: use fWeakImport on dylib to force proxy atoms into fWeakImportMap + * unit-tests/test-cases/weak_import-force: added test case + + +2008-08-29 Nick Kledzik + + linker should order __DATA segment to reduce dyld dirtied pages + * src/Options.cpp: add fOrderData and support -no_data_order + * src/ld.cpp: modify tweakLayout() to sort atoms with relocations to start of __data section + + +2008-08-27 Nick Kledzik + + * src/Options.cpp: back out + + +----- Tagged ld64-87.5 + +2008-08-26 Nick Kledzik + + some projects show _Unwind_Resume coming from libSystem.B.dylib + * src/Options.cpp: swap any early symlinks to libSystem with libgcc_s + + +----- Tagged ld64-87.4 + +2008-08-25 Nick Kledzik + + some projects show _Unwind_Resume coming from libSystem.B.dylib + * src/Options.cpp: swap any early libSystem with libgcc_s + + +2008-08-15 Nick Kledzik + + Unable to build ppc debug builds (linker out of range error) + * src/MachOWriterExecutable.hpp: in addPPCBranchIslands() look ahead so large atoms don't push out branch islands + + +----- Tagged ld64-87.3.1 + +2008-09-08 Nick Kledzik + + i386 dylibs have incorrect personality pointers when put in dyld shared cache + * src/MachOWriterExecutable.hpp: in addCrossSegmentRef() handle kImageOffset32 to __IMPORT segment + + +----- Tagged ld64-87.3 + +2008-08-09 Nick Kledzik + + work around compiler gcc_except_table alignment + * src/ObjectFile.h: change getLSDA() to return a reference instead of an atom + * src/MachOReaderRelocatable.hpp: special case __eh_frame 64-bit pointer diff relocations + * src/MachOWriterExecutable.hpp: track lsda offset when creating __unwind_info section + * src/UnwindDump.cpp: log when LDSA content does not start with 0xFF + +----- Tagged ld64-87.2 + +2008-08-07 Nick Kledzik + + 10A141: libuwind falls back to dwarf and makes whole system super slow + * src/MachOWriterExecutable.hpp: Fix sign extension bug with x86_64::kPointerDiff24 + * src/UnwindDump.cpp: warn about mangled LSDA entries when dumping unwind section + + +----- Tagged ld64-87.1 + +2008-08-03 Nick Kledzik + + * src/LTOReader.hpp: Don't use lto_codegen_debug_options until newer libLTO.dylib is available + + +----- Tagged ld64-87 + +2008-07-21 Nick Kledzik + + * src/Options.cpp: Always set fAutoOrderInitializers=false for dyld + + +2008-07-21 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix when regular vs compressed __unwind_info pages are generated + * src/UnwindDump.cpp: fix function name decoding in regular pages + + +2008-07-21 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: don't allow ld to build for x86_64 until libdtrace.dylib is available + + +2008-07-18 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: don't crash if debug_line section has no line table + + +2008-07-18 Nick Kledzik + + Duplicate probe firings in Security.framework + * src/LTOReader.hpp: optimize() now returns atoms optimized away + * src/ObjectFile.h: optimize() should return if it did anything + * src/ArchiveReader.hpp: pass through optimize() result + * src/ld.cpp: rework dtrace probe processing as a new pass to prevent double counting + + +2008-07-15 Nick Kledzik + + automatically order initializers to start of __TEXT + * src/Options.cpp: add -no_order_inits option + * src/MachOReaderRelocatable.hpp: merge __StaticInit into __text + * src/ObjectFile.h: add fAutoOrderInitializers + * src/ld.cpp: sort initializer to start of __text and terminators to end + * doc/man/man1/ld.1: add doc about -no_order_inits + * unit-tests/test-cases/init-order: add test case + +2008-07-15 Nick Kledzik + + Only add LC_SEGMENT_SPLIT_INFO to dylibs that might be in the shared cache + * src/MachOWriterExecutable.hpp: re-layout load commands after split-seg data computed + * src/Options.cpp: non-public install name will disable split-seg load command + + +2008-07-14 Nick Kledzik + + ld -r for x86_64 is changing visibility of cstring constants + * src/MachOWriterExecutable.hpp: force x86_64 cstring labels to be local in -r mode + * unit-tests/test-cases/cstring-label: added test case + + +2008-07-11 Nick Kledzik + + ld not adding updating LC_SEGMENT_SPLIT_INFO with __unwind_info section + * src/MachOWriterExecutable.hpp: run createSplitSegContent() after __unwind_info section is created + +2008-07-10 Nick Kledzik + + * src/LTOReader.hpp: improve missing symbol error message + + +2008-07-09 Nick Kledzik + + linker should order __DATA segment to reduce dyld dirtied pages + * src/ld.cpp: first phase, order sections + + +2008-07-08 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: remove "coal" sections when creating a final linked image + + +2008-07-08 Nick Kledzik + + ld: add support for mllvm LTO options + * src/Options.cpp: support -mllvm option + * src/LTOReader.hpp: call lto_codegen_debug_options() with -mllvm options + * src/ld.cpp: pass llvmOptions to optimize() + * src/Options.h: add fLLVMOptions + * src/ArchiveReader.hpp: add llvmOptions parameter to optimize() + * src/ObjectFile.h: add llvmOptions parameter to optimize() + * unit-tests/test-cases/lto-llvm-options: add test case + + +2008-07-07 Nick Kledzik + + Linker fails with: 24-bit pointer diff out of range in unwind info in unwind info from... + * src/MachOWriterExecutable.hpp: fix when to fallback to uncompressed unwind info + + +2008-07-03 Nick Kledzik + + ld crash with gcc-4.0 code that uses a zero sized array + * src/MachOReaderRelocatable.hpp: handle zero size atom in a zero sized section + + +2008-07-03 Nick Kledzik + + ld crashes when bad ppc relocs are found + * src/MachOReaderRelocatable.hpp: change all missing PAIR warnings to errors + + +2008-07-02 Nick Kledzik + + when linking a kext the static linker should leave a pad in the headers to allow code signing + * src/MachOWriterExecutable.hpp: add padding for load commands in object files + * unit-tests/test-cases/code-signed-object-file: added test case + + +2008-07-02 Nick Kledzik + + LC_SEGMENT_64 filesize incorrect for MH_OBJECT filetype + * src/MachOWriterExecutable.hpp: correctly set segment size info in object files + * unit-tests/test-cases/no-object-symbols: add test case + + +2008-06-26 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: enable ld and rebase targets to build for x86_64 + * src/rebase.cpp: remove unused fRelocBase field that was not 64-bit clean + * src/MachOReaderRelocatable.hpp: fix getEncodedP() to be 64-bit clean + + +----- Tagged ld64-86.3 + +2008-06-17 Nick Kledzik + + * src/ld.cpp: fix loadUndefines() to double check undefine symbol was not already loaded + + +----- Tagged ld64-86.2 + +2008-06-14 Nick Kledzik + + * srd/ld.cpp: Add NULL check in getTentativesNames() + + +----- Tagged ld64-86.1 + +2008-06-06 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix header padding calculation for dyld + + +----- Tagged ld64-86 + +2008-06-04 Nick Kledzik + + * src/LTOReader.hpp: if lto_codegen_add_module() fails, add explanation to error message + + +2008-06-04 Nick Kledzik + + * src/ObjectFile.h: add deadAtoms parameter to optimize() + * src/ld.cpp: ditto + * src/ArchiveReader.hpp: ditto + * src/MachOReaderRelocatable.hpp: handle llvm use of 0x1B pointer encodings in CIEs + * src/LTOReader.hpp: make sure libLTO.dylib knows about any llvm symbol coalesced away + * unit-tests/test-cases/lto-weak-native-override: add test case + + +2008-06-04 Nick Kledzik + + LTO : 176.gcc and 177.mesa build failure at -O4 + * src/LTOReader.hpp: make sure internal is returned by getAtoms() + * unit-tests/test-cases/lto-archive-dylib: update test case + + +2008-06-03 Nick Kledzik + + fix for 5613343 need to search for definitions for common symbols is broken + * src/ld.cpp: modify loadUndefines() to check for undefines in all files and tentative definitions but only in archives + * src/machochecker.cpp: check for undefine symbols and external symbols with same name + * unit-tests/test-cases/tentative-and-archive: update test case + + +2008-06-03 Nick Kledzik + + linker produces wrong result for 16-bit call relocations + * src/MachOReaderRelocatable.hpp: properly parse i386 scattered relocs for word sized pc-rel vanilla + * src/MachOWriterExecutable.hpp: propery compute displacement for x86::kPCRel16 + * unit-tests/test-cases/relocs-asm: update test case with callw instructions + + +2008-06-03 Nick Kledzik + + Building kext x86_64 with unexported symbols file causes linking problems + * src/MachOWriterExecutable.hpp: better check when creating undefined proxy atoms + * unit-tests/test-cases/unexported_symbols_list-r: added test case + + +2008-06-02 Nick Kledzik + + S_CSTRING_LITERALS section type not preserved in executable + * src/ObjectFile.h: added ContentType + * src/MachOReaderRelocatable.hpp: set ContentType for anonymous string literals + * src/MachOWriterExecutable.hpp: set S_CSTRING_LITERALS if ContentType is kCStringType + * unit-tests/test-cases/cstring-custom-section: added test case + + +2008-06-02 Nick Kledzik + + linker should produce __unwind_info section in final linked images + * src/ld.cpp: sort __unwind_info then __eh_frame section to end of __TEXT + * src/Architectures.hpp: add kImageOffset32 and kPointerDiff24 + * src/ObjectFile.h: add compact unwind info support + * src/MachOReaderRelocatable.hpp: add compact unwind info support + * src/MachOFileAbstraction.hpp: add C++ wrappers for unwind section layout + * src/UnwindDump.cpp: new tool for dumping __unwind_info section + * src/MachOWriterExecutable.hpp: create __unwind_info section when needed + * src/ObjectDump.cpp: print unwind info + + +2008-06-02 Nick Kledzik + + * unit-tests/test-cases/llvm-integration: split out some test cases + * unit-tests/test-cases/lto-preload-pie: added + * unit-tests/test-cases/lto-archive-dylib: added + + +2008-05-30 Nick Kledzik + + * unit-tests: fixes to build all tests with with gcc-4.2 on SnowLeopard + + +2008-05-30 Nick Kledzik + + support -preload option to generate MH_PRELOAD binaries compatible with mtoc(1) and EFI + * src/ld.cpp: add entryPoint parameter to optimize() + * src/ArchiveReader.hpp: ditto + * src/ObjectFile.h: ditto + * src/LTOReader.hpp: use entryPoint parameter to optimize() + * src/Options.h: add kPreload and segment alignment + * src/Options.cpp: support -preload and -segalign + * src/MachOWriterExecutable.hpp: support kPreload and non-page aligned segments + + +2008-05-30 Nick Kledzik + + ld should warn if passed -r and also dylibs + * src/ld.cpp: check for spurious dylibs in Linker::addDylib() + + +----- Tagged ld64-85.6 + +2008-11-01 Nick Kledzik + + support increased branch range in Thumb-2 + * src/MachOWriterExecutable.hpp: in fixUpReferenceFinal() support new longer branch range + + +2008-11-01 Nick Kledzik + + ld warning: unknown option to -iphoneos_version_min, not 1.x or 2.x + * src/Options.cpp: In setIPhoneVersionMin() support 3.x + + +----- Tagged ld64-85.5 + +2008-09-17 Nick Kledzik + + vtable pointers can be missing thumb bit + * src/MachOWriterExecutable.hpp: Writer::fixUpReferenceFinal() OR in the 1 bit if the target + of a arm::kReadOnlyPointer is thumb. + + +----- Tagged ld64-85.4 + +2008-08-11 Nick Kledzik + + ld should ignore LD_PREBIND when processing a static archive + * src/MachOWriterExecutable.hpp: in setImportNlist() never use N_PBUD for object files + +----- Tagged ld64-85.3 + +2008-07-14 Nick Kledzik + + Prebinding busted in DTSB + * src/Options.cpp: check for libstdc++.6.0.[49] in seg_addr_table + + +----- Tagged ld64-85.2 + +2008-05-06 Nick Kledzik + + ARM ld should take W bit off of maxprot for __TEXT segment + * src/MachOWriterExecutable.hpp: for iPhone always set maxprot to be initprot in all segments + + +2008-05-06 Nick Kledzik + + encryptable images may not be signable + * src/MachOWriterExecutable.hpp: use minimum header padding when aligning __text section + + +----- Tagged ld64-85 (Xcode 3.1) + +2008-04-29 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: is moving from /usr/local/include to /Developer/usr/local/include + + +2008-04-29 Nick Kledzik + + ld doesn't honor "rightmost" -syslibroot argument + * src/Options.cpp: if last -syslibroot is /, then ignore all syslibroots + + +2008-04-29 Nick Kledzik + + GLRendererFloat has bad __eh_frame section caused by mixing llvm-gcc and gcc object files + * src/MachOReaderRelocatable.hpp: make all atoms in __eh_frame section have 1-byte alignment + * src/MachOWriterExecutable.hpp: make __eh_frame section have pointer sized alignment + + +2008-04-17 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: better cpu subtype support + + +2008-04-14 Nick Kledzik + + ld64 has bad ARM branch island check + * src/MachOWriterExecutable.hpp: in addBranchIslands() don't force large arm programs to fail + + +2008-04-10 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix stubs used with lazy dylibs + + +----- Tagged ld64-84.4 + +2008-04-10 Nick Kledzik + + SPEC2000/eon built with -mdynamic-no-pic won't run + * src/Architectures.hpp: added arm::kReadOnlyPointer + * src/MachOReaderRelocatable.hpp: generate arm::kReadOnlyPointer + * src/MachOWriterExecutable.hpp: use arm::kReadOnlyPointer + * src/machochecker.cpp: allow MH_PIE bit + * unit-tests/test-cases/switch-jump-table: added test cases + + +----- Tagged ld64-84.3 + +2008-04-09 Nick Kledzik + + -undefined dynamic_lookup busted + * src/ld.cpp: don't create proxy atom when scanning for dylib duplicates + * unit-tests/test-cases/tentative-and-archive: use -undefined dynamic_lookup + + +----- Tagged ld64-84.2 + +2008-04-04 Nick Kledzik + + * src/ld.cpp: don't add .eh symbols to symbol table in -r mode + * unit-tests/test-cases/eh-coalescing-r: update to test out of order coalescing + + +----- Tagged ld64-84.1 + +2008-03-28 Nick Kledzik + + ld should prefer architecture-specific variant over generic in fat object file + * src/Options.cpp: fully process -arch arguments into fArchitecture and fSubArchitecture + * src/ld.cpp: when -arch with a subtype is used, try to find the exact subtype from fat files + * unit-tests/test-cases/cpu-sub-types-preference: added test cases for arm and ppc + + +----- Tagged ld64-84 + +2008-03-28 Nick Kledzik + + * src/LTOReader.hpp: don't print lto version, if lto is unavailable + + +2008-03-26 Nick Kledzik + + Add LD_WARN_COMMONS to BigBear builds + * src/Options.cpp: Add support for LD_WARN_FILE which copies all warnings to a side file + + +2008-03-26 Nick Kledzik + + Need encryption tag in mach-o file + linker should adjust arm final linked images so __text is never on the same page as the load commands + * src/MachOFileAbstraction.hpp: add support for encryption_info_command + * src/Options.cpp: add support for LD_NO_ENCRYPT and -no_encryption + * src/MachOWriterExecutable.hpp: add EncryptionLoadCommandsAtom + * src/machochecker.cpp: validate LC_ENCRYPTION_INFO + + +2008-03-25 Nick Kledzik + + ld64 does not recognize LLVM bitcode archive files + * src/MachOReaderArchive.hpp: renamed to src/ArchiveReader.hpp + * src/ArchiveReader.hpp: sniff each member and instantiate correct reader + * src/ld.cpp: rename mach_o::archive::Reader to archive::Reader + * ld64.xcodeproj/project.pbxproj: rename MachOReaderArchive.hpp to ArchiveReader.hpp + * unit-tests/test-cases/llvm-integration: added test case + + +2008-03-25 Nick Kledzik + + ld64 should switch to new libLTO.dylib interface + Produce llvm bc file in 'ld -r' mode if all .o files are llvm bc + * src/LTOReader.hpp: rewrite from LLVMReader.hpp to use new lto_* C interface + * unit-tests/test-cases/llvm-integration: update and comment + * ld64.xcodeproj/project.pbxproj: update to lazy load libLTO.dylib + * src/ld.cpp: rework and simplify Linker::optimize() + * src/ObjectDump.cpp: Add -nm option + + +2008-03-25 Nick Kledzik + + * src/MachOReaderRelocatable.cpp: Fix some .objc_class_name_ off by one problem + * src/MachOWriterExecutable.cpp: Fix some .objc_class_name_ off by one problem + + +2008-03-24 Nick Kledzik + + Xcode 3.1 breaks linkage of libgcj.9.dylib from gcc 4.3.0 + * src/MachOWriterExecutable.cpp: Make sure all ivars in Writer are initialized. + + +2008-03-21 Nick Kledzik + + * src/Options.cpp: warn if -seg1addr value is not page aligned + + +2008-03-21 Nick Kledzik + + Move ARM support outside of __OPEN_SOURCE__ + * src/ld.cpp: remove __OPEN_SOURCE__ around arm support + * src/LLVMReader.hpp: remove __OPEN_SOURCE__ around arm support + * src/MachOReaderDylib.hpp: remove __OPEN_SOURCE__ around arm support + * src/ObjectFile.h: remove __OPEN_SOURCE__ around arm support + * src/MachOReaderRelocatable.hpp: remove __OPEN_SOURCE__ around arm support + * src/OpaqueSection.hpp: Cover arm support inside __OPEN_SOURCE__ macro check + * src/MachOWriterExecutable.hpp: remove __OPEN_SOURCE__ around arm support + * src/ObjectDump.cpp: remove __OPEN_SOURCE__ around arm support + * ld64.xcodeproj/project.pbxproj: remove ARM_SUPPORT from config.h + + +----- Tagged ld64-83.2 + +2008-03-15 Nick Kledzik + + ld64-83 removes OBJC_CLASS_$ symbols from projects, causes catastrophic results + * src/Options.cpp: restore "case CPU_TYPE_ARM" in switch statement for .objc_class symbols in .exp files + * unit-tests/test-cases/objc-exported_symbols_list: added test case + + +----- Tagged ld64-83.1 + +2008-03-14 Nick Kledzik + + -iphone_version_min ==> -iphoneos_version_min + * src/Options.cpp: support -iphoneos_version_min as well + + +----- Tagged ld64-83 + +2008-03-10 Nick Kledzik + + ld needs to strip iphone_version_min option if invoking ld_classic + * src/Options.cpp: suppress -iphone_version_min from being passed to ld_classic + + +2008-03-04 Nick Kledzik + + ADOBE XCODE: Linker option to lazy load frameworks (cause dyld is too slow) + * src/MachOWriterExecutable.hpp: create lazy stubs and LC_LAZY_LOAD_DYLIB for lazy load dylibs + * src/Options.cpp: support -lazy-l, -lazy_library, and -lazy_framework + * src/MachOFileAbstraction.hpp: add LC_LAZY_LOAD_DYLIB and S_LAZY_DYLIB_SYMBOL_POINTERS until in cctools + * src/MachOReaderDylib.hpp: add isLazyLoadedDylib() + * src/ld.cpp: pass lazy helper atom to writer + * doc/man/man1/ld.1: document new options + * unit-tests/test-cases/lazy-dylib-objc: add test case + * unit-tests/test-cases/lazy-dylib: add test case + + +----- Tagged ld64-82.7 + +2008-03-07 Nick Kledzik + + duplicate symbol literal-pointer@__OBJC@__message_refs@... + * src/MachOReaderRelocatable.hpp: AnonymousAtom from S_LITERAL_POINTERS section should be weak + * unit-tests/test-cases/objc-selector-coalescing: added test case + + +----- Tagged ld64-82.6 + +2008-03-04 Nick Kledzik + + ld crashes building XsanFS for Snow Leopard Builds + * src/ld.cpp: add bool dylibsOnly parameter to addJustInTimeAtoms() + * unit-tests/test-cases/tentative-and-archive: added test case + +2008-03-04 Nick Kledzik + + ld64 should not force building with gcc 4.0 + * ld64.xcodeproj/project.pbxproj: change rules to use "system" compiler instead of 4.0 + + +2008-02-29 Nick Kledzik + + Simulator frameworks are being build split-seg and not prebound + * src/Options.cpp: only splitseg if prebound + + +2008-02-29 Nick Kledzik + + Linker should not make GSYM debug note for .objc_category_* symbols + * src/ld.cpp: suppress GSYM debug notes for absolute symbols + * unit-tests/test-cases/objc-category-debug-notes: added test case + + +2008-02-29 Nick Kledzik + + non-ASCII CFString support is broken + * src/MachOReaderRelocatable.hpp: only name and coalesce cfstring constants if they use a __cstring + * unit-tests/test-cases/cfstring-utf16: add test case + + +2008-02-25 Nick Kledzik + + ld -r -x + * doc/man/man1/ld.1: update man page to explain -r -x produces auto-stripped labels + + +----- Tagged ld64-82.5 + +2008-02-12 Nick Kledzik + + x86_64: -stack_size failure when large __bss is used + * src/ld.cpp: only move section already in __DATA segment to new __huge section + * unit-tests/test-cases/stack_size_no_addr: updated test case to add large bss section + + +----- Tagged ld64-82.4 + +2008-02-06 Nick Kledzik + + comdat warnings with ld -r of C++ .o files + * unit-tests/test-cases/eh-coalescing-r: added test case + * src/ld.cpp: in ld -r mode don't warn about if .eh symbols are not static + + +2008-02-06 Devang Patel + + LTO of Bom framework with -dead_strip causes ld(1) crash + * src/LLVMReader.hpp: Check fAtom while determining LLVMReference target binding. + * unit-tests/test-cases/llvm-integration/Makefile: Add new test case. + * unit-tests/test-cases/llvm-integration/a15.c: New. + * unit-tests/test-cases/llvm-integration/b15.c: New. + * unit-tests/test-cases/llvm-integration/c15.c: New. + +2008-02-05 Nick Kledzik + + * src/ld.cpp: fix for -arch ppc -mdynamic-no-pic -pie so PPC_RELOC_HA16 reloc is used + +----- Tagged ld64-82.3 + +2008-02-04 Nick Kledzik + + ld doesn't seem to understand $ld$add$os... and $ld$hide$os... for 10.6 moves + * src/ObjectFile.h: add 10.6 + * src/Options.cpp: add 10.6 support + * src/MachOReaderDylib.hpp: recognize $os10.6$ + + +----- Tagged ld64-82.2 + +2008-01-30 Devang Patel + + Can't build 64-bit Intel binaries with LTO + ld64 fails to build with llvm-gcc-4.2 + * src/LLVMReader.hpp: Fix character count typo in strncmp call. + Use const char * to initialize temp. string. + * ld64.xcodeproj/project.pbxproj: use $(DEVELOPER_DIR) in header search construction + instead of hard coding /Developer. + +----- Tagged ld64-82.1 + +2008-01-23 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: don't bus error if S_LITERAL_POINTERS is missing relocs + + +2008-01-22 Nick Kledzik + + ld uses 32-bits in some places to hold addresses when parsing 64-bit mach-o files + * src/MachOReaderRelocatable.hpp: use AddrToAtomMap type that switch address to 64-bits for 64-bit archs + * src/MachOWriterExecutable.hpp: verify BR14 does not overflow for external relocs + * unit-tests/test-cases/relocs-c: update test case to slide addresses to verify x86_64 .o files + + +----- Tagged ld64-82 + +2008-01-18 Nick Kledzik + + Bad grammar used in ld warning: cannot exported hidden symbol + * src/ld.cpp: fix typo in warning string + + +2008-01-16 Nick Kledzik + + Bundle Loader does not work anymore when loader is a bundle + ld warns of incorrect architecture when linking a bundle to a bundle + * src/MachOReaderDylib.hpp: support linking against bundles via -bundle_loader. Clean up error messages + * unit-tests/test-cases/bundle_loader: update test case + + +2008-01-16 Nick Kledzik + + ld -r -x creates debug notes (stabs) when it should not with -x (keep only global symbols) + * src/Options.cpp: in reconfigureDefaults() if -r and -x then -S + + +2008-01-16 Nick Kledzik + + if ld crashes while writing output file, it should delete the half written file + * src/MachOWriterExecutable.hpp: wrap open/write/close in try block and add signal handlers all to delete + output file on failure. + + +2008-01-16 Devang Patel + + * src/LLVMReader.hpp: Use __gnu_cxx::hash_map instead of hash supported by LLVM. + + +2008-01-16 Nick Kledzik + + GC-supported library can't be linked into GC-required executable + * src/ld.cpp: loosen constraint that all objc code must be compiled with same GC settings and + allow gc-compatible code to be linked into anything. + * unit-tests/test-cases/objc-gc-checks: update test case + + +2008-01-15 Nick Kledzik + + no debug notes for custom named data + * src/ld.cpp: in synthesizeDebugNotes() check getSymbolTableInclusion() instead of for leading underscore + * unit-tests/test-cases/dwarf-debug-notes: update test case + +----- Tagged ld64-81.5 + +2008-01-14 Devang Patel + + llvm-gcc-4.2 fails to build Sqlite 3.5.4 with -O4 + * src/LLVMReader.hpp: Resolve proxy references. Collect new unbounded references + after optimization. + * src/ld.cpp: Resolve additional unbounded references after optimization. + + +2008-01-14 Nick Kledzik + + PPC Leopard (Xcode 3.0) linker ld gets "Bus error" sometimes + * src/MachOReaderRelocatable.hpp: use same code as x86 to parse ppc and arm sect-diff relocs + * src/MachOWriterExecutable.hpp: use same code as x86 to write ppc and arm sect-diff relocs + + +2008-01-11 Nick Kledzik + + PPC Leopard (Xcode 3.0) linker ld reports "unknown scattered relocation type 4" + * src/MachOReaderRelocatable.hpp: add PPC_RELOC_HI16 to scattered reloc parsing + * unit-tests/test-cases/relocs-asm/relocs-asm.s: added tests for scattered hi/lo instructions + + +2008-01-11 Nick Kledzik + + * doc/man/man1/ld.1: add doc for -no_implicit_dylibs, -read_only_stubs, -slow_stubs, -interposable_list + + +2008-01-11 Nick Kledzik + + ld64(1) man page uses ambiguous term "suffix" + * doc/man/man1/ld.1: make meaning of "suffix" more explicit + + +2008-01-11 Nick Kledzik + + Obj-C Symbols in Leopard Can't Be Weak Linked + * src/MachOWriterExecutable.hpp: set weak and lazy attributes on dummy .objc_class_name undefines + to dylibs to support Mac OS X 10.3.x dyld + + +2008-01-11 Nick Kledzik + + Unknown error with linker (dyld: unknown external relocation type) + * src/ld.cpp: fix crash when SO stabs are not balanced + + +2008-01-11 Devang Patel + + LTO does not work if expected output is a dynamic library + * src/LLVMReader.hpp: Supply arguments describing output kind to optimizer. Communicate + visibility info. + +2000-01-10 Nick Kledzik + + __cls_refs section is losing S_LITERAL_POINTERS section type + * src/MachOWriterExecutable.hpp: special case __cls_refs section + * unit-tests/test-cases/objc-literal-pointers: add test case + + +2008-01-03 Nick Kledzik + + wrong EH information might be used + Created new kGroupSubordinate reference kind to model group comdat. The "signature" atom + has kGroupSubordinate references to the other atoms in the group. If the signature atom + is coalesced away, the linker follows kGroupSubordinate references and throws away the + other members of the group. + * unit-tests/test-cases/eh-coalescing: added test case + * src/ld.cpp: added markDead() and use propagate to subordinates + * src/Architectures.hpp: added kGroupSubordinate + * src/MachOReaderRelocatable.hpp: add kGroupSubordinate reference from a function to its .eh atom + and if used, from .eh atom to its LSDA atom. + * src/MachOWriterExecutable.hpp: handle kGroupSubordinate like kNoFixUp + +----- Tagged ld64-81.4.1 + +2007-12-19 Devang Patel + + * src/LLVMReader.hpp: Add LLVM_LTO_VERSION #ifdef check. + +2007-12-19 Devang Patel + + * src/LLVMReader.hpp: Add fOptimizer NULL check before calling printVersion(). + +2007-12-19 Devang Patel + + print LLVM LTO version number in verbose mode + * src/LLVMReader.hpp: Add printLLVMVersion() to print llvm version string in verbose mode. + * src/Options.cpp: Use printLLVMVersion() in verbose mode. + +2007-12-19 Devang Patel + + print LLVM LTO version number in verbose mode + * src/Options.h: Add verbose() method to check fVerbose flag. + * src/LLVMReader.hpp: Print LLVM version string in verbose mode. + +----- Tagged ld64-81.4 + +2007-12-18 Devang Patel + + * src/LLVMReader.hpp: Invalidate input architecture when optimizer is not available. + +----- Tagged ld64-81.3 + +2007-12-17 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: remove extraneous header search paths + + +2007-12-17 Devang Patel + + * src/LLVMReader.hpp: Do not throw exception if LLVMReader is not able to + dlopen LTO library. Instead just flag input file as an invalid LLVM bitcode file. + + +2007-12-14 Nick Kledzik + + gcc DejaGnu failure: gcc.dg/20020312-2.c (test for excess errors) (-fstack-protector-all) + * src/MachOWriterExecutable.hpp: fix Writer::generatesExternalTextReloc() to allow text relocs + * unit-tests/test-cases/read-only-relocs: updated test case to link a dynamic main executable compiled with -static + + +2007-12-14 Devang Patel + + Enable Link Time Optimization in Opal + * src/LLVMReader.hpp: Locate LLVMlto.dylib relative to ld location in Developer folder. + * ld64.xcodeproj/project.pbxproj: Add {DEVELOPER_DIR}/usr/include in header search path. + * unit-tests/run-all-unit-tests: Set DYLD_FALLBACK_LIBRARY_PATH to find LLVMlto.dylib during unit testing. + * unit-tests/testcases/llvm-integration/Makefile: Point LLVMGCC and LLVMGXX to llvm-gcc-4.2 in Developer folder during unit testing. + + +2007-12-13 Nick Kledzik + + SWB: failures due to ld: pointer in read-only segment not allowed in slidable image, used in ... + * src/MachOReaderRelocatable.hpp: in Reader::addRelocReference() handle weak pc-rel 32-bit vanilla relocs properly + +----- Tagged ld64-81.2 + + + +2007-12-07 Nick Kledzik + + support 8-bit relocations for i386 + * src/Architectures.hpp: add kPCRel8 + * src/MachOReaderRelocatable.hpp: support 8-bit pc-rel relocations for intel + * src/MachOWriterExecutable.hpp: support 8-bit pc-rel relocations for intel + * unit-tests/test-cases/relocs-asm: add test cases + + +----- Tagged ld64-81.1 + +2007-12-06 Nick Kledzik + + * src/MachOReaderDylib.hpp: rework cycle detection to remove some false positives + + +2007-12-05 Nick Kledzik + + Duplicate probe firings in Security.framework + * src/ld.cpp: check dtrace probe sites are not in fDeadAtoms before using + * unit-tests/test-cases/dtrace-static-probes-coalescing: add test case + + +2007-12-05 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix CFString coalescing to work with -fwritable-strings + * unit-tests/test-cases/cfstring-coalesce: add -fwritable-strings to test case + + +----- Tagged ld64-81 + +2007-11-15 Nick Kledzik + + ld64 should support runtime text relocations + * src/MachOWriterExecutable.hpp: add generatesLocalTextReloc() and generatesExternalTextReloc() + * src/Options.cpp: process -read_only_relocs option + * src/Options.h: add allowTextRelocs() and warnAboutTextRelocs() + * src/MachOReaderRelocatable.hpp: add hasLongBranchStubs() + * src/machochecker.cpp: allow relocs in read only segments, if section flags are set + * unit-tests/test-cases/read-only-relocs: update test case + + +2007-11-08 Devang Patel + + * ld64.xcodeproj/project.pbxproj: add new build phase "build configure.h" for + ld target. + * src/ld.cpp: Include "configure.h" + + +----- Tagged ld64-80.11 + +2008-02-12 Nick Kledzik + + Wrong section name for objc info for ARM when OBJC2 is used + * src/MachOWriterExecutable.hpp: switch segment/section name for ARM objc2 image info + +----- Tagged ld64-80.10 + +2008-02-11 Nick Kledzik + + ld64 does not support -aspen_version_min 2.0 + * src/Options.cpp: allow 2.x for -aspen_version_min + + +2008-02-11 Nick Kledzik + + ld_classic: unknown flag: -aspen_version_min + * src/Options.cpp: change -aspen_version_min x.x to -macosx_version_min 10.5 when invoking ld_classic + + +----- Tagged ld64-80.9 + +2008-01-29 Nick Kledzik + + -iphone_version_min ==> -aspen_version_min + * src/Options.cpp: support -aspen_version_min + + +----- Tagged ld64-80.8 + +2008-01-10 Nick Kledzik + + * src/Options.cpp: support transition to new objc ABI for ARM by allowing old .objc_class_name_* + style names in export files and map them to new _OBJC_CLASS_$_ style names. + + +----- Tagged ld64-80.7 + +2008-01-02 Nick Kledzik + + BigBear5A18 isn't fully prebound + * src/Options.cpp: make fNeedsModuleTable true for arm + +----- Tagged ld64-80.6 + +2007-11-30 Nick Kledzik + + -iphone_version_min + * src/Options.cpp: handle -iphone_version_min option + + +----- Tagged ld64-80.5 + +2007-11-26 Nick Kledzik + + need to special case some dylibs in seg_addr_table + * src/Options.cpp: retry seg_add_table lookup for a couple of unusual dylibs + + +----- Tagged ld64-80.4 + +2007-11-06 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix parsing of external and scattered thumb branch22 relocs + * unit-tests/test-cases/thumb-blx: add test case to keep blx issues from coming back + +----- Tagged ld64-80.3 + +2007-11-03 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: remove recalc of dstAddr which could cause thumb branches to be +2 + * src/MachOWriterExecutable.hpp: remove incorrect test for relocateableExternal + +----- Tagged ld64-80.2 + +2007-11-01 Nick Kledzik + + * src/ld.cpp: hack my own prototype for log2() until math.h is cleaned up + + +----- Tagged ld64-80.1 + +2007-11-01 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: add HEADER_SEARCH_PATHS for cross builds + * src/ld.cpp: temporarily disable LLVM_SUPPORT + * src/MachOWriterExecutable.hpp: Don't use CC_MD5() directly + + +2007-10-26 Nick Kledzik + + Cannot build with libm_static.a statically linked + * src/MachOWriterExecutable.hpp: Fix makesExternalRelocatableReference() for -r -d case + * unit-tests/test-cases/tentative-to-real-hidden: add test case + + +----- Tagged ld64-80 + +2007-10-24 Nick Kledzik + + linker should probably warn about trying to export a hidden symbol + * src/ld.cpp: if using -exported_symbols_list check each hidden atom as it is added to symbol table + * src/Options.h,.cpp: add hasExportMaskList() + * unit-tests/test-cases/exported_symbols_list-hidden: added test case + + +2007-10-24 Nick Kledzik + + * src/MachOWriterExecutable.hpp: keep old style dtrace probes externel for kernel builds + + +2007-10-23 Nick Kledzik + + unify error and warning messages + -w should suppress warnings + * src/ld.cpp: use warning() function + * src/Options.h: remove emitWarnings() + * src/MachOReaderDylib.hpp: use warning() function + * src/MachOReaderRelocatable.hpp: use warning() function + * src/Options.cpp: use and implement warning() + * src/MachOWriterExecutable.hpp: use warning() function + * unit-tests/test-cases/visibility-warning: verify -w suppresses warnings + + +2007-10-23 Devang Patel + + * src/ld.cpp: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/LLVMReader.hpp: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/MachOReaderDylib.hpp: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/ObjectFile.h: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/MachOReaderRelocatable.hpp: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/OpaqueSection.hpp: Cover arm support inside __OPEN_SOURCE__ macro check + * src/MachOWriterExecutable.hpp: Cover arm support inside __OPEN_SOURCE__ macro check. + * src/ObjectDump.cpp: Cover arm support inside __OPEN_SOURCE__ macro check. + + +2007-10-22 Nick Kledzik + + * src/Options.cpp: add support for LD_DEAD_STRIP and LD_WARN_COMMONS + * src/MachOReaderRelocatable.hpp: fix problem with -dead_strip of ObjC literal pointers + + +2007-10-22 Nick Kledzik + + * src/Options.cpp: have -static arm code link with ld_classic (for now) + + +2007-10-22 Nick Kledzik + + Recognize all arm architectures + * src/MachOReaderRelocatable.hpp: add support for all ARM sub-types + * unit-tests/test-cases/cpu-sub-types: add test cases for all combinations of ARM sub-types + + +2007-10-19 Nick Kledzik + + * src/*: merge in arm support + * unit-tests/test-cases/*: fix to work for arm and thumb + +----- Tagged ld64-79 + +2007-10-16 Nick Kledzik + + * src/MachOWriterExecutable.hpp: if -r mode, always set custom alignment (SET_COMM_ALIGN) on common symbols + * unit-tests/test-cases/visibility-warning-dylib-v-archive/Makefile: fix warning + * unit-tests/test-cases/static-executable/Makefile: fix spurious failure + + +2007-10-16 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix edge case in branch island generation + + +2007-10-12 Nick Kledzik + + Add option to create old, slow stubs for i386 + * src/ObjectFile.h/.cpp: support -read_only_stubs + * src/MachOWriterExecutable.hpp: enhance StubAtom to support old style __symbol_stub/__la_symbol_ptr stubs + * unit-tests/test-cases/slow-x86-stubs: add test case + + +2007-10-12 Nick Kledzik + + ld64's re-export cycle detection logic prevents use of X11 libGL on Leopard + * src/Options.cpp: in findFileUsingPaths() don't search for embedded dylibs + * unit-tests/test-cases/indirect-path-search/Makefile: added case for a dylib embedded in a framework + + +2007-10-11 Nick Kledzik + + add option to disable implicit load commands for indirectly used public dylibs + * src/Options.cpp: add support for -no_implicit_dylibs + * src/ObjectFile.h: add fImplicitlyLinkPublicDylibs + * src/MachOReaderDylib.hpp: test fImplicitlyLinkPublicDylibs before hoisting an implicitly linked dylib + * unit-tests/test-cases/implicit_dylib: add test case + + +2007-10-11 Nick Kledzik + + -interposable_list + * src/Options.h/cpp: Add fInterposeList and fInterposeMode to support -interposable_list + * src/MachOWriterExecutable.hpp: pass symbol name to fOptions.interposable() + * unit-tests/test-cases/interposable_list: add test case + + +2007-10-10 Nick Kledzik + + If only weak_import symbols are used, linker should use LD_LOAD_WEAK_DYLIB + * src/MachOWriterExecutable.hpp: automatically use LC_LOAD_WEAK_DYLIB if all symbols used from a dylib are weak_import + * unit-tests/test-cases/weak_dylib: added test case + + +2007-10-10 Nick Kledzik + + linker does not error when dylib ordinal exceeds 250 + * src/MachOWriterExecutable.hpp: error out if ordinals exceed max allowed + + +2007-10-10 Nick Kledzik + + overriding 'operator new' or 'operator delete' fails if no weak symbols are present + * src/ld.cpp: at end of checkUndefines() search dylibs for weak versions of any global external symbols + * src/ObjectFile.h: add hasWeakExternals() method to Reader + * src/MachOReaderDylib.hpp: implement hasWeakExternals() method in Reader + * src/ExecutableFile.h: add overridesDylibWeakDefines parameter to write() + * src/MachOWriterExecutable.hpp: use overridesDylibWeakDefines parameter to write() + * unit-tests/test-cases/operator-new: add test case + + +2007-10-05 Nick Kledzik + + No warning about tentative definition conflicting with dylib definition + .comm variables in shared library, worked with XCode 2.4.1, broken with XCode 3? + * src/ld.cpp: at end of checkUndefines() verify if any remaining commons conflict with dylibs + * doc/man/man1/ld.1: document -commons and -warn_commons options + * unit-tests/test-cases/tentative-and-dylib: added test case + + +2007-10-05 Nick Kledzik + + NS/CFString constants are not dead strippable + * src/MachOReaderRelocatable.hpp: break up __cfstring section into one atom per cfstring, make them coalesable + * unit-tests/test-cases/cfstring-coalesce: added test case + + +2007-10-05 Nick Kledzik + + Dead stripping + exported symbols list using wildcards doesn't seem to do the right thing + * src/Options.cpp/h: add hasWildCardExportRestrictList() + * src/ld.cpp: if dead stripping code and have wildcard exports, add all global atoms matching wildcards as roots + * unit-tests/test-cases/exported-symbols-wildcards-dead_strip: added test case + + +2007-10-04 Nick Kledzik + + ld shouldn't search /Network/Library/Frameworks by default + * src/Options.cpp: remove /Network/Library/Frameworks/ from default search path + * doc/man/man1/ld.1: document the change + + +2007-10-04 Nick Kledzik + + all binaries should get LD_UUID load commands, not just those with DWARF symbols + * src/ld.cpp: default fCreateUUID to be true for non object file output types + * unit-tests/test-cases/no-uuid/Makefile: update test case to match new rules + + +----- Tagged ld64-78 + +2007-09-27 Nick Kledzik + + range check load commands + * src/MachOReaderDylib.hpp: check that load commands all fit in load command size from header + * src/MachOReaderRelocatable.hpp: check that load commands all fit in load command size from header + + +2007-09-27 Nick Kledzik + + Xc8M2540a: ld64 crashes when linking Pascal program + * src/ld.cpp: fix findAtomAndOffset() to handle where there are no function atoms + + +2007-09-27 Nick Kledzik + + ADOBE Xcode 3: ld -dead_strip does not work with -init from an archive + * src/ld.cpp: add bool parameter to entryPoint() so -init atom not looked for too soon + * unit-tests/test-cases/dead_strip-init-archive: added test case + + +2007-09-26 Nick Kledzik + + Spurious link warnings for inline members of C++ template classes + * src/ld.cpp: check definition kinds before warning about visibility mismatches + * unit-tests/test-cases/visibility-warning: added test case + + +2007-09-26 Nick Kledzik + + an empty .o file with zero load commands will crash linker + * src/MachOReaderRelocatable.hpp: have Reader constructor return early of no load commands + * unit-tests/test-cases/empty-object: added test case + + +2007-09-26 Nick Kledzik + + 9a527: ppc64 branch islands fail with 4GB pagezeo + * src/MachOWriterExecutable.hpp: start range calculations at start of __text not at zero. + + +----- Tagged ld64-77 (Xcode 3.0) + +2007-07-23 Nick Kledzik + + Kernel is linked with some global symbols unsorted + * src/MachOWriterExecutable.hpp: Add NListNameSorter to allow global atoms and extra labels to be sorted + + +2007-07-20 Nick Kledzik + + Can't do objc_msgSendSuper dispatches after loading a Fix&Continue bundle + * src/MachOWriterExecutable.hpp: when calculating what kind of reloc to use, never use an + external reloc to reference 32-bit ObjC symbols. + + +2007-07-20 Nick Kledzik + + Runtime crash with ICC math library on Leopard + * src/MachOReaderRelocatable.hpp: detect if section starts with a symbol that is not + aligned to section and correct it. + + +----- Tagged ld64-76 + +2007-06-29 Nick Kledzik + + export hiding does not work for frameworks + * src/MachOReaderDylib.hpp: fix checks in isPublicLocation() + * unit-tests/test-cases/symbol-moving: update to test frameworks as well as dylibs + + +2007-06-27 Nick Kledzik + + linker should use undefines from flat dylibs when linking a main flat + * src/ObjectFile.h: added fLinkingMainExecutable + * src/Options.cpp: set up fLinkingMainExecutable + * src/MachOReaderDylib.hpp: when linking a main executable for flat namespace, the reader for + any loaded flat namespace dylib will have a new atoms that has references to all undefined + symbols in the dylib + * unit-tests/test-cases/flat-indirect-undefines: added test case + * doc/man/man1/ld.1: update man page to describe when dylib undefines are used + + +2007-06-27 Nick Kledzik + + OpenGL.framework and X11 both have a libGL.dylib which can cause ld to segfault if both are found + * src/MachOReaderDylib.hpp: add assertNoReExportCycles() method + * unit-tests/test-cases/dylib-re-export-cycle: added test case + + +2007-06-27 Nick Kledzik + + ld64 has slightly different warning message formats than the old ld + * src/ld.cpp: standardize all warning messages to start with "ld: warning" + * src/MachOWriterExecutable.hpp: ditto + * src/MachOReaderRelocatable.hpp: ditto + * src/MachOReaderDylib.hpp:ditto + + +2007-06-26 Nick Kledzik + + -dead_strip can cause duplicate external commons + * src/ld.cpp: don't use discarded coalesced global atoms as dead strip roots + * src/machochecker.cpp: error if duplicate external symbols + * unit-tests/test-cases/commons-coalesced-dead_strip: added test case + + +2007-06-26 Nick Kledzik + + update man page that linker does not search indirect libraries with two-level namespace + * doc/man/man1/ld.1: add new "Indirect dynamic libraries" section to man page + + +2007-06-26 Nick Kledzik + + Xc9A466: Exports file cannot use Mac line ends + * src/Options.cpp: check for \r or \n when parsing .exp files + * unit-tests/test-cases/exported_symbols_list-eol: added test case + + +----- Tagged ld64-75 + +2007-05-31 Nick Kledzik + + Simplier, generalized way to re-export dylibs: LC_REEXPORT_DYLIB + * src/MachOWriterExecutable.hpp: Use LC_REEXPORT_DYLIB when targetting 10.5 + + +----- Tagged ld64-74.5 + +2007-05-31 Nick Kledzik + + set OSO timestamp to zero for when building in buildit + * src/ld.cpp: check for RC_RELEASE and if exists set all OSO timestamps to zero + + +2007-05-30 Nick Kledzik + + BUILD_STABS now causes ld of xnu to bus error + * src/ld.cpp: Change || to && in collectStabs() + + +----- Tagged ld64-74.4 + +2007-05-18 Nick Kledzik + + static probes don't work with libraries in dyld shared cache + * src/OpaqueSection.hpp: the __TEXT segment is executable + + +----- Tagged ld64-74.3 + +2007-05-16 Nick Kledzik + + ppc: linker adds stubs to cstring references + * src/MachOWriterExecutable.hpp: update ppc stubableReference() to only allow high/low references + to be stubed if they reference a symbol in some other dylib. + * unit-tests/test-cases/stub-generation: added test case + + +2007-05-16 Nick Kledzik + + ppc64: need to make LOCAL indirect symbol table entry for now local symbol + * src/MachOWriterExecutable.hpp: factored local tests into indirectSymbolIsLocal() + * unit-tests/test-cases/non-lazy-r: added test case + + +2007-05-15 Nick Kledzik + + ld64 drops fix&continue bit in __OBJC, __image_info. + * src/MachOReaderRelocatable.hpp: implement objcReplacementClasses() + + +2007-05-15 Nick Kledzik + + support __image_info in __DATA segment for 64-bits + * src/MachOReaderRelocatable.hpp: use strncmp() for __objc_imageinfo since it is 16 bytes long + * src/MachOWriterExecutable.hpp: specialize segment/section names for synthesized objc image info section + + +2007-05-15 Nick Kledzik + + * unit-tests/include/common.makefile: set COMPILER_PATH so harness works with latest compiler + + +----- Tagged ld64-74.2 + +2007-05-11 Nick Kledzik + + ld64-74.1 breaks libstdc++ DejaGnu test (G5 only) + * src/MachOWriterExecutable.hpp: don't stub a reference if the target offset is non-zero + + +----- Tagged ld64-74.1 + +2007-05-09 Nick Kledzik + + * src/Options.h: add emitWarnings() + * src/Options.cpp: wire up -w to emitWarnings() + + +2007-05-09 Nick Kledzik + + ld64 won't link wine (regression from Tiger) + * src/Architectures.hpp: add x86::kPointerDiff16 and x86::kPCRel16 + * src/MachOReaderRelocatable.hpp: add support to parse new relocs + * src/MachOWriterExecutable.hpp: add support fo new relocs + + +2007-05-08 Nick Kledzik + + need way for ld and dyld to see different exported symbols in a dylib + * src/MachOReaderDylib.hpp: update parse and use $ld$ symbols + * src/Options.h: move VersionMin to ReaderOptions + * src/ObjectFile.h: move VersionMin to ReaderOptions + * src/Options.cpp: move VersionMin to ReaderOptions + * src/MachOWriterExecutable.hpp: move VersionMin to ReaderOptions + * unit-tests/test-cases/symbol-moving: added test case + + +2007-05-03 Nick Kledzik + + typo in error message for linking -pie + * src/MachOWriterExecutable.hpp: fix typo in error messages + + +----- Tagged ld64-74 + +2007-05-03 Nick Kledzik + + ld64 can't find @executable _path relative dylibs from our umbrella frameworks + ld64 should handle linking against dylibs that have @loader_path based dylib load commands + * src/ObjectFile.h: add from parameter to findDylib() + * src/MachOReaderDylib.hpp: supply from parameter to findDylib() + * src/ld.cpp: use from parameter for @loader_path substitution in findDylib() + * unit-tests/test-cases/re-export-relative-paths: added test case + + +2007-05-02 Nick Kledzik + + * src/ObjectFile.h: add fLogObjectFiles and fLogAllFiles + * src/Options.cpp: hook up -t to fLogAllFiles and -whatsloaded to fLogObjectFiles + * src/MachOReaderDylib.hpp: log if fLogAllFiles + * src/MachOReaderRelocatable.hpp: log if fLogObjectFiles or fLogAllFiles + * src/MachOReaderArchive.hpp: log if fLogAllFiles + * doc/man/man1/ld.1: update man page + + +2007-05-02 Nick Kledzik + + typo in message, frameowrk + * src/Options.cpp: fix typo + + +2007-05-01 Nick Kledzik + + "ld" man page is missing the description for many options + * doc/man/man1/ld.1: add documentation on all obsolete options + + +2007-05-01 Nick Kledzik + + ld doesn't handle -mlong-branch .o files that have had local symbols stripped + warning about dwarf line info with -mlong-branch + * src/MachOReaderRelocatable.hpp: don't lop -mlong-branch stubs off end of functions + * src/MachOWriterExecutable.hpp: allow code references besides BR24 to be stubable + + +2007-04-30 Nick Kledzik + + unable to link VTK because __textcoal_nt too large + * src/MachOReaderRelocatable.hpp: when doing a final link map __textcoal_nt to __text + + +2007-04-30 Nick Kledzik + + ld does not report error when -r is used and exported symbols are not defined. + ld leaves global common symbols not in exported symbols list. + * src/ld.cpp: stop special casing -r mode in checkUndefines() + * src/MachOWriterExecutable.hpp: don't create proxy atom in -r mode if it is supposed to be exported. + mark tentative definitions are private extern in -r mode even without -keep_private_externs + * unit-tests/test-cases/exported_symbols_list-r: added test case + + +2007-04-27 Nick Kledzik + + ld should keep looking when it finds a weak definition in a dylib + * src/ld.cpp: modified addJustInTimeAtoms() to keep looking when a weak defintion is found + * unit-tests/test-cases/weak-def-ordinal: added test case + + +2007-04-27 Nick Kledzik + + better error message for indirect dylibs missing required architecture + * src/ld.cpp: when loading indirect dylib add path to error messages + + +2007-04-25 Nick Kledzik + + the i386 slice of dyld does not need __IMPORT segment + * src/ObjectFile.h: add fForDyld + * src/Options.cpp: set up fForDyld + * src/MachOReaderRelocatable.hpp: if fForDyld, change __IMPORT segment to __DATA + * src/MachOWriterExecutable.hpp: recognize __DATA/__pointers in dyld as a non-lazy section + + +2007-04-24 Nick Kledzik + + ppc64: need to make LOCAL indirect symbol table entry for now local symbol + * src/MachOWriterExecutable.hpp: use INDIRECT_SYMBOL_LOCAL for any non-global symbol + * unit-tests/test-cases/strip_local: update test case + + +2007-04-24 Nick Kledzik + + ld64 -sectorder and -order_file files don't accept white space following the : + * src/Options.cpp: prune white space after colon and before symbol name + * unit-tests/test-cases/order_file: update test case to have a space after the colon + + +2007-04-24 Nick Kledzik + + ld64 corrupts debug symbol table entries, nm doesn't print them + * src/MachOWriterExecutable.hpp: properly set ilocalsym in module table + + +2007-04-24 Nick Kledzik + + support __image_info in __DATA segment for 64-bits + * src/MachOReaderRelocatable.hpp: look for new objc info section name too + + +2007-04-24 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix -non_global_symbols_strip_list to work with -r + * unit-tests/test-cases/local-symbol-partial-stripping: update test case + + + +----- Tagged ld64-73.7 + +2007-05-10 Nick Kledzik + + can't use dtrace static probes in x86_64 dylib + * src/MachOWriterExecutable.hpp: x86_64:kPointerDiff32 is ok in shared region + * unit-tests/test-cases/dtrace-static-probes: update to build dylib too + + +2007-05-09 Nick Kledzik + + 9A430: using -dead_strip with static dtrace probes causes ld to crash + * src/ld.cpp: fix markLive() to look at right name in dtrace probe refernce + * unit-tests/test-cases/dtrace-static-probes: added -dead_strip case + + +----- Tagged ld64-73.6 + +2007-04-17 Nick Kledzik + + Add options to do partial stripping of local symbols + * src/MachOWriterExecutable.hpp: use fOptions.keepLocalSymbol() + * src/Options.cpp: implement -non_global_symbols_no_strip_list and -non_global_symbols_strip_list + * src/Options.h: replace stripLocalSymbols() with localSymbolHandling() and keepLocalSymbol() + * doc/man/man1/ld.1: document -non_global_symbols_no_strip_list and -non_global_symbols_strip_list + * unit-tests/test-cases/local-symbol-partial-stripping: added test case + + +----- Tagged ld64-73.5 + +2007-04-17 Nick Kledzik + + ld64-73.3 XBS logging incorrectly reporting "direct" dynamic libraries + * src/ld.cpp: restore direct vs indirect library for LD_TRACE_DYLIBS logging + + +2007-04-16 Nick Kledzik + + data initialized to a weak imported symbol is missing relocation + * src/MachOWriterExecutable.hpp: check for A::kPointerWeakImport in buildExecutableFixups() + * unit-tests/test-cases/weak_import: updated test case to catch this problem + + +2007-04-13 Nick Kledzik + + Support -U + * src/MachOWriterExecutable.hpp: create proxies for -U symbols + * src/Options.cpp: process -U + * src/Options.h: add allowedUndefined() and someAllowedUndefines() + * src/ld.cpp: create proxies for -U symbols + * doc/man/man1/ld.1: document -U and -undefined options + * unit-tests/test-cases/undefined-dynamic-lookup: added test case + + +----- Tagged ld64-73.4 + +2007-04-12 Nick Kledzik + + ld changes needed to support read-only DOF + * src/Options.cpp: remove -read_only_dof + * src/Options.h: remove fReadOnlyDOFs + * src/ld.cpp: only generate read-only DOF sections + + +----- Tagged ld64-73.3.1 + +2007-04-13 Nick Kledzik + + -framework vecLib -framework Accelerate causes bad ordinals + * src/MachOWriterExecutable.hpp: fix bug optimizeDylibReferences() when there are two readers with same install name + + +----- Tagged ld64-73.3 + +2007-04-03 Nick Kledzik + + * src/ld.cpp: read-only-dofs should use 32-bit offsets for x86_64 + * src/MachOReaderDylib.hpp: if "public" re-export is not marked implict, still mark it as re-exported + + +2007-04-02 Nick Kledzik + + if replacement file for -dylib_file is missing, warn instead of error + * src/ld.cpp: a try/catch to turn -dylib_file error into a warning. + * unit-tests/test-cases/dylib_file-missing: add test case + * doc/man/man1/ld.1: update man page about -dead_strip_dylibs + + +----- Tagged ld64-73.2 + +2007-03-31 Nick Kledzik + + ld64-73: atom sorting error with duplicate zero sized bss symbols + * src/MachOReaderRelocatable.hpp: suppress warning on sorting zero size zero fill atoms + +2007-03-31 Nick Kledzik + + ld64-73 fails anything linking with -lm + * src/ld.cpp: when processing dylbs that are sylinks ensure that fDylibMap contains all paths + * src/MachOWriterExecutable.hpp: when dead stripping dylibs and renumbering ordinals make sure + aliases dylib get renumbered too + * unit-tests/test-cases/dylib-aliases: added + + +----- Tagged ld64-73.1 + +2007-03-30 Nick Kledzik + + * src/MachOWriterExecutable.hpp: back out use of LC_REEXPORT_DYLIB until rdar://problem/5009909 is in build fleet + + +----- Tagged ld64-73 + +2007-03-30 Nick Kledzik + + ER: -dead_strip_dylibs + linker should add implicit load commands for indirectly used public dylibs + * src/ObjectFile.h: change dylib reader interface to implictly/explicitlyLinked + * src/ld.cpp: use new dylib reader interface + * src/Options.h: add deadStripDylibs() + * src/Options.cpp: support -dead_strip_dylibs + * src/MachOReaderDylib.hpp: use new dylib reader interface + * src/MachOWriterExecutable.hpp: remove dylib load commands for unused dylibs and alter ordinals + * unit-tests/test-cases/re-export-optimizations: added + * unit-tests/test-cases/dead_strip_dylibs: added + + +2007-03-30 Nick Kledzik + + * src/Options.cpp: enable -lfoo to search for libfoo.so as well as libfoo.dylib, + remove seg addr table hack for transitioning to new linker + +2007-03-30 Nick Kledzik + + ADOBE XCODE3: Linker is slow with large C++ .o files + * src/MachOReaderRelocatable.hpp: the compiler generates stubs to weak functions in the + same translation unit. Don't treat those like the spurios stubs to static functions. + + +2007-03-29 Nick Kledzik + + ld64 should link mach_kernel during xnu builds to support dtrace + * src/MachOReaderRelocatable.hpp: To handle duplicate labels properly, rework how atoms sizes are set + by iterating through sorted fAtoms rather than fAddrToAtom, . Change default alignment of commons + to be the natural alignment of the size rounded up to the closest power of two and max it at 12. + Build atoms in reverse symbol table order so that global atoms are constructed before locals. + This assures that if there is a global and local label at the same location, the global label + will become the atom's name and the local will be an alias. Properly handle a label + at the end of a section. Handle R_ABS in relocations. Handle sect-diff relocs with addends. + Don't auto-strip 'l' symbols in static executables (mach_kernel). + * src/OpaqueSection.hpp: opaque_section now has an ordinal + * src/ld.cpp: opaque_section now requires an ordinal + * src/ObjectFile.h: add ReaderOptions.fForStatic + * src/Options.cpp: set fForStatic when building a static executable + * src/MachOWriterExecutable.hpp: add from atom to StubAtom. Properly write out i386 + sect-diff relocs with addends. properly write out ppc PICbase relocs where pic base + is not in the atom. + + +2007-03-27 Nick Kledzik + + Typo in ld man page (-exported_symbols_list) + * doc/man/man1/ld.1: fix typo + + +2007-03-26 Nick Kledzik + + consider generating LC_UUID from a checksum of the file + * src/Options.h: change emitUUID() to getUUIDMode() + * src/Options.cpp: support -random_uuid + * src/MachOWriterExecutable.hpp: set uuid to be md5 hash of entire output file + + +2007-03-24 Nick Kledzik + + * src/MachOWriterExecutable.hpp: restructure writeAtoms() to copy all atoms in memory if possible + + +2007-03-24 Nick Kledzik + + ld -r of stripped .o file can incorrectly merge non-lazy pointers + * src/MachOWriterExecutable.hpp: when generating a .o file, non-lazy pointer with target offsets should be + encoded as LOCAL in the indirect symbol table + * unit-tests/test-cases/stripped-indirect-symbol-table: added test case + + +2007-03-23 Nick Kledzik + + SWB: ld64-72 errors building with gcc-4.2 + * src/MachOReaderDylib.hpp: add curly brackets in switch cases + * src/MachOWriterExecutable.hpp: rearrange classes so there are no template specialization forward references + + +2007-03-23 Nick Kledzik + + * src/ld.cpp: fix -print_statistics when using -dead_strip + + +2007-03-23 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: generate better names for non-lazy pointers to the interior of atoms + + +2007-03-16 Nick Kledzik + + * src/MachOWriterExecutable.hpp: speed up ld -r a little by reversing relocs en mas + + +2007-03-16 Nick Kledzik + + ld Bus Error on missing command line arguments + * src/Options.cpp: check next argv[] is not NULL + + +2007-03-16 Nick Kledzik + + need to be able to order symbols in anonymous namespaces + * src/ld.cpp: add logic to do fuzzy matching of symbols with anonymous namespace usage + * unit-tests/test-cases/order_file-ans: added test case + + +2007-03-16 Nick Kledzik + + headerpad_max_install_names deprecated for 64-bit + * src/ld.cpp: make sure dylib load command order matches command line order + * src/Options.h: add maxMminimumHeaderPad() + * src/Options.cpp: add maxMminimumHeaderPad() set by -headerpad_max_install_names + * src/src/MachOWriterExecutable.hpp: check maxMminimumHeaderPad() + * doc/man/man1/ld.1: update man page about -headerpad_max_install_names + + +2007-03-16 Nick Kledzik + + Linker returns success although exported symbols are undefined. + * src/ld.cpp: turn missing symbols back into an error + + +2007-03-16 Nick Kledzik + + ld64 should handle linking against dylibs that have @loader_path based dylib load commands + * unit-tests/test-cases/loader_path: added test case + + +2007-03-16 Nick Kledzik + + linker should add implicit load commands for indirectly used public dylibs + Indirect libraries should be found using -F and -L options + Simplier, generalized way to re-export dylibs: LC_REEXPORT_DYLIB + * src/ld.cpp: reworked all dylib processing. Readers can now add the dylib list. + * src/Options.h: add findFileUsingPaths() + * src/MachOReaderDylib.hpp: look in re-exported children instead of requring linker to do that + * src/ObjectFile.h: add processIndirectLibraries(), remove getDependentLibraryPaths() + * src/machochecker.cpp: support LC_REEXPORT_DYLIB + * src/ExecutableFile.h: simplify DyLibUsed + * src/Options.cpp: add findFileUsingPaths(). add new re-export options + * src/MachOWriterExecutable.hpp: Use LC_REEXPORT_DYLIB when targetting 10.5 + * doc/man/man1/ld.1: updated with new re-export options + * unit-tests/test-cases/indirect-path-search: added tests that -F and -L work with indirect dylibs + * unit-tests/test-cases/re-export-cases: added tests for all combinations of re-exporting + + +2007-03-14 Nick Kledzik + + sort external relocations to optimize dyld performance + * src/MachOWriterExecutable.hpp: added ExternalRelocSorter + * src/machochecker.cpp: verify external relocations are grouped by symbol number + * unit-tests/test-cases/external-reloc-sorting: added test case + + +----- Tagged ld64-72 + +2007-03-06 Nick Kledzik + + * src/Options.cpp: ignore .objc_category_name_* symbols in .exp files + + +2007-03-06 Nick Kledzik + + * src/Options.cpp: stop special casing mach_kernel and instead requre kernel to be built with -new_linker + + +2007-03-06 Nick Kledzik + + ld64-72 (experimental) is causing DejaGnu test failures + * src/MachOWriterExecutable.hpp: add optimizableGOTReferenceKind() to track GOT uses that cannot be optimized + + +2007-03-06 Nick Kledzik + + minimum header padding should be 32 to allow code signing + * src/Options.cpp: initialize fMinimumHeaderPad to 32 + * src/MachOWriterExecutable.hpp: better calculation of header padding + + +2007-03-06 Nick Kledzik + + Linker crashes with -flat_namespace against two-level dylibs that might have re-exports + * src/ld.cpp: flat namespace should not allow NULL indirect readers + + +2007-03-06 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: don't error on S_COALESCED sections with anonymous atoms + * src/MachOWriterExecutable.hpp: set MH_PIE bit when linking -pie + * ld64.xcodeproj/project.pbxproj: don't echo environment when running unit test + + +2007-03-01 Nick Kledzik + + * doc/man/man1/ld.1: Add descriptions to all "rarely used options" + + +2007-03-01 Nick Kledzik + + Remove support for Essential Symbols: Warn about use of -Sp option; remove man page entry + * src/Options.cpp: make -Sp obsolete + * doc/man/man1/ld.1: make -Sp obsolete + + +2007-03-01 Nick Kledzik + + Support -pie + * src/Options.h: Add positionIndependentExecutable() + * src/Options.cpp: Support -pie option to set positionIndependentExecutable() + * src/MachOWriterExecutable: if -pie is used, add extra local relocations and error if any + absolute addressing is used + + +2007-03-01 Nick Kledzik + + ld64 should link mach_kernel during xnu builds to support dtrace + * src/ld.cpp: Ensure segments are laid out in discovery order. Add support for kAbsoluteSymbol. + Warn when merging symbols of different visiblity. Warn when a tentative definition + is replaced by one a real definition with a smaller size. Lay out __common section + so that ones built with -fno-commons come before regular commons. + * src/ObjectFile.h: remove SegmentOffset ivar and getter/setters + * src/machochecker.cpp: allow images with no r/w segments + * src/MachOReaderRelocatable: Add AbsoluteAtom. Sort tentative definitions by name instead of by size + Add support for custom commons alignment. + * src/Options.cpp: Fix spurious -sectalign warnings. Don't use ld_classic when linking mach_kernel + * src/MachOWriterExecutable.hpp: Support kAbsoluteSymbol atoms. In -r mode, set custom alignment + for commons if alignment is not its size. Support global __dtrace_probe labels. + * src/ObjectDump.cpp: add support for kAbsoluteSymbol atoms. + * unit-tests/test-cases/commons-alignment: Added test case for custom commons alignment + * unit-tests/test-cases/absolute-symbol: Added test case for basic absolute symbols + * unit-tests/test-cases/segment-order: Added test case that segments lay out in discovery order + * unit-tests/test-cases/commons-order: Added test case that commons lay out correctly + * unit-tests/test-cases/end-label: Added test case that a label used to mark the end of a section does not + get associcated with the next section. + + +2007-02-23 Nick Kledzik + + gcc-5005: DejaGnu failures due to -frepo + * src/ld.cpp: Add quotes to referenced from name to make collect2 and -frepo happy + + +2007-02-22 Nick Kledzik + + * src/MachOWriterExecutable.hpp: rework how padding after load commands is calculated + + +2007-02-21 Nick Kledzik + + * src/MachOWriterExecutable.hpp: extend special case of __mh_execute_header to static executables too + + +2007-02-21 Nick Kledzik + + gcc link map option ( "-M" ) should be redirectable to file + * doc/man/man1/ld.1: added -map option description + * src/Options.h: added generatedMapPath() + * src/Options.cpp: set up generatedMapPath() if -map option is used + * src/MachOWriterExecutable.hpp: add writeMap() method to generate map file + + +2007-02-19 Nick Kledzik + + Implement GOT Load elimination optimization + * src/ld.cpp: track size of all atoms and if > 2GB sort large zero-fill atoms to end + * src/MachOWriterExecutable.hpp: If image size < 2GB, only generate GOT entries if value must be + updatable by dyld. If > 2GB, only eliminate GOT entries to non-zero-fill atoms. Any use + of an eliminated GOT entry has its code changed from MOVQ _foo@GOT(%rip) to LEAQ _foo(%rip). + * unit-tests/test-cases/large-data: added + * unit-tests/test-cases/got-elimination: added + + +----- Tagged ld64-71.2 + +2007-02-13 Nick Kledzik + + new ld ignores -segprot option + * src/Options.h: expose customSegmentProtections() + * src/Options.cpp: parse -segprot option and populate customSegmentProtections() + * src/MachOWriterExecutable.hpp: use customSegmentProtections() + + +2007-02-13 Nick Kledzik + + i386 -stack_addr doesn't work + * src/MachOWriterExecutable.hpp: use correct offset into thread state record + + +----- Tagged ld64-71.1 + +2007-02-07 Nick Kledzik + + * src/ld.cpp: sort __OBJC2 segment to be next to __OBJC segment + + +2007-02-07 Nick Kledzik + + * src/Options.cpp: change missing -seg_addr_table from an error to a warning + + +2007-02-06 Nick Kledzik + + Leopard 9A357: -dylib_file broken? + * src/MachOWriterExecutable.hpp: remove use of fInstallPathOverride + * src/Options.cpp: wire up -dylib_file option + * src/Options.h: remove fInstallPathOverride. add fDylibOverrides + * src/ld.cpp: check dylibOverrides() for indirect libraries + * unit-tests/test-cases/dylib_file: add test case + + +2007-02-05 Nick Kledzik + + * src/MachOReaderDylib.hpp: don't warn about zero size __image_info sections + + +2007-02-04 Rick Balocca + Enable the failing cases for missing command line arguments + +2007-02-04 Rick Balocca + Make sure that all .o's are checked by ObjectDump + and all macho are checked by machochecker + +2007-02-04 Rick Balocca + Fix an endian problem with machochecker + Fix blank-stubs Makefile + +----- Tagged ld64-71 + +2007-02-02 Rick Balocca + blank-stubs test case: handle the case of a native ppc compile--this + sets the subtype, which must be passed to lipo + +2007-02-01 Rick Balocca + make cpu-sub-types test more robust + +2007-02-01 Rick Balocca + auto-arch tests were resulting in a false FAILs + +2007-02-01 Rick Balocca + test cpu-sub-types was resulting in a false FAIL + +2007-02-01 Nick Kledzik + + STD:VSC: c99 -o writes to file that does not have write permission + * src/MachOWriterExecutable.hpp: check file is writable before using it + +2007-02-01 Nick Kledzik + + debug map (N_OSO) timestamps for object files in ranlib archive are incorrect + * src/MachOReaderArchive.hpp: parse modTime for .o files out of archive header + +2007-01-31 Nick Kledzik + + 9A354: ld -all_load does *NOT* produce the same dSYM as *.o or -u + * src/ld.cpp: when using -all_load don't assume that all atoms have same reader + * unit-tests/test-cases/dwarf-archive-all_load: added + +----- Tagged ld64-70.1 + +2007-01-31 Nick Kledzik + + * src/MachOWriterExecutable.hpp: in addObjectRelocs_powerpc() mask scattered r_address to 16-bits + +----- Tagged ld64-70 + + +2007-01-30 Nick Kledzik + + linker should verify GC consistency of modules being linked into library + Support cpu-sub-types for ppc + * src/ObjectFile.h: Add getObjCConstraint() and getCpuConstraint() + * src/MachOReaderRelocatable.hpp: don't make atom for __image_info section, instead parse constaints + * src/MachOReaderDylib.hpp: look at __image_info content to get constaints + * src/ld.cpp: add updateContraints() and checkObjc() + * src/MachOWriterExecutable.hpp: add ObjCInfoAtom to sythesize __image_info content + + +2007-01-28 Nick Kledzik + + src/*: remove ObjectFile::requiresFollowOnAtom() method + + +2007-01-28 Nick Kledzik + + src/ld.cpp: enable LLVM_SUPPORT by default + src/LLVMReader.hpp: don't use absolute paths for llvm headers and libraries + + +2007-01-26 Rick Balocca + * src/ObjectDump.cpp: The usage() message was incorrect. + + +2007-01-25 Rick Balocca + * unit-tests/test-cases/zero-fill3: It was reporting FAIL on ld64 error return. + It should have been checking for non-error return. + + +2007-01-24 Nick Kledzik + + x86 fast stubs should not cross 64-byte boundries + * src/MachOWriterExecutable.hpp: for x86, 64-byte align __jump_table section + and make 64-btye crossing stubs be empty entries with indirect symbol table + entry of INDIRECT_SYMBOL_ABS + + +2007-01-19 Nick Kledzik + + * src/Options.h: add readOnlyx86Stubs() + * src/Options.cpp: support -read_only_stubs + * src/MachOWriterExecutable.hpp: make __IMPORT segment not writable if -read_only_stubs is used + + +2007-01-16 Eric Christopher + + ld64 --help isn't recognized + * src/Options.cpp (Options::parse): Support --help and -help. + + +2007-01-15 Nick Kledzik + + * src/MachOFileAbstraction.hpp: add range checking on macho_scattered_relocation_info::set_r_address() + + +2007-01-14 Nick Kledzik + + Support wildcards in contents of -exported_symbols_list + * src/Options.h: add SetWithWildcards class + * src/Options.cpp: add -exported_symbol and -unexported_symbol and use SetWithWildcards + * doc/man/man1/ld.1: add -exported_symbol and wildcard explanation + * unit-tests/test-cases/exported-symbols-wildcards: added test case + + +2007-01-10 Nick Kledzik + + [U]SDT probes should use C calling convention + * src/Options.cpp: Add -read_only_dof + * src/ld.cpp: create __dof section(s) based on probe and isenabled sites + * src/MachOReaderRelocatable.hpp: parse new sdt 2.0 probes encoded in .o files + * src/MachOWriterExecutable.hpp: handle regenerating dtrace probes into .o files + * unit-tests/test-cases/dtrace-static-probes: added test case + + +----- Tagged ld64-69.8 + +2007-01-30 Nick Kledzik + + Support LD_FORCE_NO_SEG_ADDR_TABLE + * src/Options.cpp: Support LD_FORCE_NO_SEG_ADDR_TABLE + + +----- Tagged ld64-69.7 + +2007-01-25 Nick Kledzik + + Leopard9A351: CFM Apps Are Broken because CFM glue is missing + * src/MachOReaderRelocatable.hpp: check S_ATTR_NO_DEAD_STRIP in dontDeadStrip() + + +----- Tagged ld64-69.6 + +2007-01-24 Nick Kledzik + + LD_TRACE_ARCHIVES should only print out when a .o is actually used from an archive + * src/ld.cpp: create and use logArchive() + + +----- Tagged ld64-69.5 + +2007-01-22 Nick Kledzik + + 9A350: can't link ppc programs with ld_classic + * src/Options.cpp: Remove support for LD_NO_CLASSIC_LINKER. Add support for -classic_linker + + +----- Tagged ld64-69.4 + +2007-01-17 Nick Kledzik + + QTComponents does not link with ld64 + * src/MachOReaderRelocatable.hpp: handle N_RSYM and N_PSYM stabs + + +----- Tagged ld64-69.3 + +2007-01-03 Nick Kledzik + + * src/Options.cpp: If the same dylib is specified twice and the second is specified weak, make it weak + + +----- Tagged ld64-69.2 + +2006-12-18 Nick Kledzik + + -dead_strip without -exported_symbols_list should not strip global functions from archives + * src/ld.cpp: when adding a .o file from an archive, add all its global symbols to live roots + * unit-tests/test-cases/dead_strip-archive: added + + +2006-12-18 Nick Kledzik + + flat_namespace main executables do not need to indirect interior references + * src/MachOWriterExecutable.hpp: don't indirect references to global symbols in main executables + * unit-tests/test-cases/flat-main: updated to test for indirection + * unit-tests/test-cases/flat-dylib: added + + +----- Tagged ld64-69.1 + +2006-12-15 Nick Kledzik + + -flat_namespace does not work with -mdynamic-no-pic + * src/MachOWriterExecutable.hpp: rework checking for use of ppc absolute addressing to allow them as long as + the target is within the same linkage unit. + + +2006-12-15 Nick Kledzik + + -ObjC should only load .o with .objc_ symbols + * src/Options.cpp: remove warning from -ObjC and have it instead set fLoadAllObjcObjectsFromArchives + * src/MachOReaderArchive.hpp: when -ObjC is used, preload all .o files from archives that contain .objc_ symbols + + +----- Tagged ld64-69 + +2006-12-13 Nick Kledzik + + prebound interior pointers must be non-zero + * src/MachOWriterExecutable.hpp: in fixUpReference_powerpc() set lazy pointers bound to with the dylib to + their target value. Properly set REFERENCE_FLAG_UNDEFINED_* flags in reference table and n_desc + + +2006-12-09 Nick Kledzik + + ld64 fails to detect error that ld_classic does + * src/MachOWriterExecutable.hpp: check for absolute reloc to an external symbol + * src/MachOReaderRelocatable.hpp: ignore -mlong-branch stubs in .o files + + +2006-12-09 Nick Kledzik + + symbols with REFERENCED_DYNAMICALLY should never be stripped + * src/MachOWriterExecutable.hpp: update Writer::shouldExport() to check for kSymbolTableInAndNeverStrip + * unit-tests/test-cases/main-stripped: add test that dynamically referenced symbol cannot be stripped + + +2006-12-08 Nick Kledzik + + * unit-tests/test-cases/allowable-client: add variant test cases (e.g. CoreServices_profile) + * src/ld.cpp: allow frameworks with variant install names (e.g. CoreServices_profile) to be private clients + + +2006-12-08 Nick Kledzik + + * doc/man/man1/ld.1: rewrite man page + * src/Options.h: add warnObsolete() + * src/Options.cpp: use warnObsolete() on many options. Make nonWeak the weak-mis-match default. + Make -ObjC mean -all_load. + +----- Tagged ld64-68.3 + +2006-12-05 Nick Kledzik + + * src/ld.cpp: allow umbrella frameworks to have variant install names (e.g. CoreServices_profile) and still link + + +----- Tagged ld64-68.2 + +2006-12-05 Nick Kledzik + + * src/MachOWriterExecutable.cpp: Use N_PBUD in the symbol table for undefined symbols in prebound dylibs + + +----- Tagged ld64-68.1 + +2006-12-01 Nick Kledzik + + * src/Options.cpp: always generate module tables for 32-bit architectures so that ld_classic + can link against them + + +----- Tagged ld64-68 + +2006-12-01 Nick Kledzik + + seg_addr_table needs matching fuzziness + * src/Options.cpp: special case a how a dozen dylib are looked up in the seg_addr_table + + +2006-12-01 Nick Kledzik + + * src/Options.cpp: have all -static links for 32-bit archs roll over to ld_classic unless + LD_NO_CLASSIC_LINKER_STATIC is set. + * unit-tests/bin/make-recursive.pl: set LD_NO_CLASSIC_LINKER_STATIC for unit tests + + +2006-11-29 Nick Kledzik + + ld64-67: QTComponents fails to build + * src/MachOReaderRelocatable.hpp: don't error out when a local non-lazy pointer does not point to a symbol + * unit-tests/test-cases/strip_local: added test case + + +2006-11-28 Nick Kledzik + + Need a way to mark libraries usable by dynamic linker but unusable by static linker + * src/Options.cpp: allow -client_name to be used with main executables + * src/ld.cpp: generalize -allowable_client. Any dylib can now restrict who can link against it. As a convention + linking with -allowable_client '!' will mean no one can statically link with the dylib. It can still be loaded + dynamically, or by any existing clients, but no new clients can link with it. + * unit-tests/test-cases/allowable-client/Makefile: enable previously commented out test cases. Add test cases + of a dylib that allows no clients and just one client + +2006-11-27 Nick Kledzik + + -final_output should be used if -install_name not used + * src/Options.cpp: fall back to using -final_output for install name + + +----- Tagged ld64-67 + +2006-11-17 Nick Kledzik + + * src/MachOWriterExecutable.hpp: support __IMPORT segment being slide independently of __DATA segment in shared cache + + +2006-11-16 Nick Kledzik + + 9a303: ld -filelist Bus Error + * src/Options.cpp: add check that -filelist is followed by an argument + + +2006-11-16 Nick Kledzik + + * src/MachOWriterExecutable.hpp: when building split-seg dylibs, LINKEDIT goes in read-only side + + +2006-11-15 Nick Kledzik + + * src/MachOWriterExecutable.hpp: set proper attributes for __eh_frame in ld -r mode + * unit-tests/test-cases/eh_frame: added test case + + +2006-11-10 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: redirect references to static weak stubs to the real target + + +2006-11-09 Nick Kledzik + + * src/MachOWriterExecutable.hpp: r_address is offset from first LC_SEGMENT vmaddr - not from segment with lowest address + + +----- Tagged ld64-66.1 + +2006-11-09 Nick Kledzik + + * src/MachOWriterExecutable.hpp: initialize fModuleInfoAtom to zero + + +2006-11-08 Nick Kledzik + + FSF GCC's libjava doesn't link with Ochre ld64 + * src/MachOReaderRelocatable.hpp: ignore debug_line section if debug_info section is missing or empty + +----- Tagged ld64-66 + +2006-11-07 Nick Kledzik + + SWB: d64-65 does not built usage split-seg dylibs + * src/MachOWriterExecutable.hpp: when prebinding split-seg correctly set r_address fields and on + disk values for external relocations + * unit-tests/test-cases/prebound-split-seg: added test case + + +2006-11-03 Nick Kledzik + + * src/MachOReaderDylib.hpp: don't report dependent libraries if MH_NO_REEXPORTED_DYLIBS bit is set + * src/MachOWriterExecutable.hpp: set MH_NO_REEXPORTED_DYLIBS bit if dylib does not logically re-export any other dylibs + * unit-tests/test-cases/re-export-flag: added test case + * src/machochecker.cpp: validate use of MH_NO_REEXPORTED_DYLIBS + + +2006-11-02 Nick Kledzik + + Mysterious messages from ld64 with MACOSX_DEPLOYMENT_TARGET = 10.5 + * src/MachOWriterExecutable.hpp: kPointerWeakImport is a valid reference type to cross segments + + +2006-11-02 Nick Kledzik + + * src/Options.cpp,h: Add support for -rpath + * src/MachOFileAbstraction.hpp: add macho_rpath_command + * src/MachOWriterExecutable.hpp: add RPathLoadCommandsAtom to create LC_RPATH for each -rpath + + +----- Tagged ld64-65 + +2006-10-30 Nick Kledzik + + x86_64 default stack_addr is wrong + * src/Options.cpp: change default 64-bit stack location when using -stack_size + + +2006-10-30 Nick Kledzik + + dylibs need modules for 10.3 and for ld_classic in Salt + * src/MachOWriterExecutable.hpp: add ModuleInfoLinkEditAtom to create module table stuff + * src/Options.cpp,h: Add needsModuleTable() + * src/MachOFileAbstraction.hpp: Add macho_dylib_module, macho_dylib_reference, and macho_dylib_table_of_contents + + +2006-10-27 Nick Kledzik + + * unit-tests/test-cases/no-uuid/Makefile: add -gstabs+ to be compatible with latest compiler + * unit-tests/test-cases/stabs-coalesce/Makefile: add -gstabs+ to be compatible with latest compiler + + +2006-10-26 Nick Kledzik + + i386 -mdynamic-no-pic switch statement jump table is out of line + * src/MachOWriterExecutable.hpp: for i386 don't check for direct references to weak symbols + + +2006-10-26 Devang Patel + + * src/LLVMReader.hpp: Supply final output file path to optimizer. + +2006-10-26 Devang Patel + + * src/ObjectFile.h: Make setSection* methods virtual. + * src/LLVMReader.hpp: Override setSection* methods. + +2006-10-26 Devang Patel + + * unit-tests/test-case/llvm-integration/a13.h: New. + * unit-tests/test-case/llvm-integration/a13.cc: New. + * unit-tests/test-case/llvm-integration/main13.cc: New. + +2006-10-26 Devang Patel + + * src/options.h, src/options.cpp: Add -save-temps command line option. + * src/LLVMReader.hpp: Use saveTemps option. + + +2006-10-26 Devang Patel + + * src/LLVMReader.hpp: Remove invalid module from memory. + +2006-10-26 Devang Patel + + * src/LLVMReader.hpp: Collect symbol alignment info from LLVM optimizer. + +2006-10-21 Eric Christopher + + * src/ld.cpp (Linker::Linker): Check for LD_NO_CLASSIC_LINKER before + invoking ld_classic. + * unit-tests/test-cases/relocs-literals/Makefile: Run for -mdynamic-no-pic + and pic. + * unit-tests/test-cases/static-executable/Makefile: Skip for 64-bit. Add + -dead_strip to command line. + +----- Tagged ld64-64.2 + +2006-10-19 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: stop copying LLVMReader.hpp into man1 directory + +----- Tagged ld64-64.1 + +2006-10-19 Nick Kledzik + + ld64-63.1 erroneously coalesces an empty string with a non-empty string + * src/MachOReaderRelocatable.hpp: rework cstring parsing to not assume all strings are start + at section alignment boundaries, and when coalescing empty strings always use one with greatest + alignment requirement + * src/MachOWriterExecutable.hpp: in -r mode, don't pad end of cstring section + * src/ObjectFile.h: correctly name leadingZeros() as trailingZeros() + * src/ld.cpp: leadingZeros() --> trailingZeros() + + +2006-10-18 Eric Christopher + + * unit-tests/test-cases/read-only-relocs/Makefile: Skip for x86_64. + * unit-tests/test-cases/llvm-integration/Makefile: Skip if llvm isn't + present. + +2006-10-18 Nick Kledzik + + ld64 change required to go with assembler cstring change + ld64 should error when a local relocation references an address outside its section + * src/MachOReaderRelocatable.hpp: for x86_64 in order to work with local or external relocations to cstrings + change parser to allow atoms with a pending name that is resolved after references are instantiated. + Make direct references to kRegularDefinition atoms. + * src/MachOWriterExecutable.hpp: in -r mode for x86_64 generate L* labels for cstrings and use external relocations + * unit-tests/test-cases/relocs-literals/test.c: add two cases of cstring literal plus addend + + +2006-10-06 Nick Kledzik + + check MACOSX_DEPLOYMENT_TARGET if -macosx_version_min is not used + * src/Options.cpp: if -macosx_version_min is not used, check MACOSX_DEPLOYMENT_TARGET, if + that is unused, default to 10.5 + +----- Tagged ld64-64 + +2006-10-06 Nick Kledzik + + crash in ppc64 program - bl to saveFP, but saveFP is too far away? + * src/MachOWriterExecutable.hpp: in addPPCBranchIslands(), properly account for growth of __text + + +2006-10-06 Nick Kledzik + + Linker-defined alias converts reference into definition and generates error. + * src/MachOReaderRelocatable.hpp: only alias symbols actually in the symbol table + + +2006-10-06 Nick Kledzik + + * unit-tests/test-cases/dwarf-debug-notes/Makefile: crt1.o no longer has stabs, so don't need to strip it + * unit-tests/test-cases/dwarf-debug-notes-r/Makefile: crt1.o no longer has stabs, so don't need to strip it + + +2006-10-06 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: rework dwarf line parsing to fix warnings that starting + showing up with gcc-5421 + + +2006-10-05 Eric Christopher + + ld64 needs to support libtool options + * src/Options.cpp (Options::parse): Add -noall_load, -install_name, + -current_version and -compatibility_version. + +2006-10-03 Eric Christopher + + * src/Options.cpp (Options::gotoClassicLinker): Use execvp + to call ld_classic. + +2006-10-03 Eric Christopher + + * unit-tests/test-cases/tentative-to-real/Makefile: Clean up after tests. + +2006-10-03 Eric Christopher + + * unit-tests/include/common.makefile (VALID_ARCHS): Add x86_64. + (OTOOL): Remove munging based on ARCH. + +2006-09-29 Nick Kledzik + + problem merging .o files built with and without -fno-common + src/Options.*: make MakeTentativeDefinitionsReal a reader option + src/ObjectFile.h: make MakeTentativeDefinitionsReal a reader option + src/MachOWriterExecutable.hpp: make MakeTentativeDefinitionsReal a reader option + src/MachOReaderRelocatable.hpp: only assign a section name of __common to + tentative defintions when making a final linked image + + +2006-09-28 Nick Kledzik + + src/Options.h/.cpp: add support for -segaddr option + src/MachOWriterExecutable.hpp: In Writer::assignFileOffsets(), use -segaddr info + + +2006-09-28 Nick Kledzik + + Emit new CPU subtypes for ppc64 and x86-64 when targeting 10.5 or later + src/MachOWriterExecutable.hpp: set high bit of cpusubtype of 64-bit main executables when targeting 10.5 or later + + +2006-09-28 Devang Patel + + Add LLVM LTO support + src/LLVMReader.hpp: New file. + src/ld.cpp: Add optimization phase. Use LLVM LTO. + unit-tests/test-cases/llvm-integration: New tests. + +2006-09-27 Nick Kledzik + + ld64.xcodeproj/project.pbxproj: remove accidental install of source file into man1 + + +2006-09-25 Nick Kledzik + + src/Architectures.hpp: add kPointerDiff16 for ppc and ppc64 + src/MachOReaderRelocatable.hpp: support kPointerDiff16 + src/MachOWriterExecutable.hpp: support kPointerDiff16 + +----- Tagged ld64-63.1 + +2006-09-22 Nick Kledzik + + src/MachOWriterExecutable.hpp: include stubs in LC_SEGMENT_SPLIT_INFO + + +2006-09-21 Nick Kledzik + + src/Options.cpp: disable split-seg dylibs for 64-bit architectures + + +2006-09-19 Nick Kledzik + + src/MachOReaderRelocatable.hpp: rework __cstring parsing to better handle mixed alignment cstrings + src/MachOWriterExecutable.hpp: in -r mode, make all __cstrings aligned to section alignment + + +2006-09-19 Nick Kledzik + + src/MachOWriterExecutable.hpp: rework encoding of LC_SEGMENT_SPLIT_INFO + + +2006-09-19 Nick Kledzik + + src/Options.cpp: check for -search_paths_first in first pass + + +----- Tagged ld64-63 + +2006-09-15 Nick Kledzik + + src/Options.cpp: since the ld64 will repeatedly search an archive, and some project list archives + multiple times on command line to work with traditional linkers, automatically ignore duplicate libraries + unit-tests/test-cases/archive-duplicate: added test case + + +2006-09-15 Nick Kledzik + + src/Options.cpp: support -r -static + src/MachOWriterExecutable.hpp: support -r -static an don't generate LC_DYSYMTAB + + +2006-09-14 Nick Kledzik + + src/MachOWriterExecutable.hpp: in -r mode references to weak symbols should not create external relocations + as that can cause nmedit to errror later. + + +2006-09-13 Nick Kledzik + + ld64: Handle .objc_class_name exports specially + src/Options.cpp: add hack so that .objc_class_name_XXX in -exported_symbols_list imples _OBJC_CLASS_$_XXX + src/ld.cpp: add hack to supporess errors about .objc_class_name_XXX or _OBJC_CLASS_$_XXX being undefined + + +2006-09-12 Nick Kledzik + + Support -prebind when targeting ppc and OS < 10.4 + src/Options.h: add splitSeg() and baseWritableAddress() + src/Options.cpp: Add support for -seg_addr_table and LD_SEG_ADDR_TABLE, and -prebind and LD_PREBIND. + src/src/MachOWriterExecutable.hpp: support split-seg and canonical prebound files to be generated + + +2006-09-11 Nick Kledzik + + Linking a dylib or binary from identical binaries should produce the same output + src/MachOWriterExecutable.hpp: set the timestamps to be constant + + +2006-09-11 Nick Kledzik + + Linker support for ordering all sections and symbols + src/Options.cpp: Add -order_file_statistics. Allow architecture prefixes in order files + src/ld.cpp: Use fOptions.printOrderFileStatistics() + + +2006-09-11 Nick Kledzik + + Support -sectorder + unit-tests/test-cases/order_file: added test case + src/ld.cpp: Implement order file support in Linker::sortAtoms() + src/Options.h: add Options.orderedSymbols() + src/Options.cpp: add parseOrderFile(), implement -order_file + + +2006-09-07 Nick Kledzik + + need -i for 64-bit (or equivalent) + Support -i for aliasing exported symbols + unit-tests/test-cases/alias-objects: added + unit-tests/test-cases/alias-command-line: added + src/ObjectFile.h: Added Atom::getOrdinal() as new way to sort atoms. Added ReaderOptions.fAliases + src/MachOReaderRelocatable.hpp: Added SymbolAliasAtom to handle multiple symbols to same address + src/MachOReaderArchive.hpp: implement Atom::getOrdinal() to space out atom ordinals across member objects + src/Options.cpp: support -i, -alias, -alias_list. Move search of /Network/Library/Frameworks to after /System/Library/Frameworks + src/MachOWriterExecutable.hpp: pad out seg_info data. Implement getOrdinal(). + src/ObjectDump.cpp: call constructors directly instead of using make() wrapper + + +2006-09-01 Nick Kledzik + + Need the ability to tag libraries/plug-ins with security attributes + src/MachOReaderDylib.hpp: add warning if using -root_safe or -setuid_safe and link against dylib that is not + src/ObjectFile.h: add ReaderOption fRootSafe and fSetuidSafe + src/Options.cpp: handle -root_safe or -setuid_safe command line options + src/MachOWriterExecutable.hpp: set MH_ROOT_SAFE and MH_SETUID_SAFE flags + + +2006-08-31 Nick Kledzik + + src/ld.cpp: Add Linker::processDTrace() for processing dtrace static probes + src/OpaqueSection.hpp: renamed, add symbol name, add ability to add references + ld64.xcodeproj/project.pbxproj: remove SectCreate.cpp, add OpaqueSection.hpp + + +2006-08-28 Nick Kledzik + + Add convention for removing symbols at link time + Assembler -L option causes ld64 to split stubs + unit-tests/test-cases/special-labels: added test case + src/MachOReaderRelocatable.hpp: ignore L* labels, make l* labels as kSymbolTableNotIn + + +2006-08-28 Nick Kledzik + + src/lObjectFile.h: refactor isTargetUnbound() into getTargetBinding() + src/ld.cpp: create __dof section in final linked images from dtrace static probes + src/Architectures.hpp: add kDtraceProbe + src/Options.h/cpp: Add support for -dtrace + src/machochecker.cpp: support LC_SEGMENT_SPLIT_INFO + src/MachOWriterExecutable.hpp: support kDtraceProbe + src/MachOReaderRelocatable.hpp: suppport kDtraceProbe + + +2006-08-25 Nick Kledzik + + generate LC_SEGMENT_SPLIT_INFO for 10.5 or later dylibs + src/Options.h&.cpp: implement sharedRegionEligible() to control when LC_SEGMENT_SPLIT_INFO is added + src/MachOFileAbstraction.hpp: add macho_linkedit_data_command + src/MachOWriterExecutable.hpp: generate LC_SEGMENT_SPLIT_INFO load command and linkedit content + +----- Tagged ld64-62 + +2006-08-15 Nick Kledzik + + wrong error message when symbol is found in unused indirect library + src/ld.cpp: remove indirect libraries if they are not re-exported + unit-tests/test-cases/indirect-dylib: added test case + + +2006-08-15 Nick Kledzik + + alignment needs to be richer + src/ObjectFile.h: define ObjectFile::Alignment class for tracking rich alignment info + src/ld.cpp: modify SymbolTable::add() to work with new Alignment type + src/MachOReaderRelocatable.hpp: use new Alignment type. Remove alignAtLeast() and handleAnonymousNonLazyPointers() + src/MachOWriterExecutable.hpp: update for new Alignment type, use modulus when calculating layout address + src/ObjectDump.cpp: print richer Alignment info + unit-tests/test-cases/align-modulus: added test case + + +2006-08-11 Nick Kledzik + + remove OPEN_SOURCE conditionals around x86_64 support + + +2006-07-31 Nick Kledzik + + ld64 while linking cc1 [ when dead_strip is ON] + src/ld.cpp: Add ivar fAtomsWithUnresolvedReferences to track atoms not initially resolvable + unit-tests/test-cases/dead_strip-archive: added test case + + +2006-07-31 Nick Kledzik + + x86_64: instructions with immediate and rip-relative operands need to use new relocation types + src/MachOWriterExecutable.hpp: generate new reloc types in -r mode + src/MachOReaderRelocatable.hpp: parse new reloc types + unit-tests/test-cases/relocs-asm/relocs-asm.s: add test cases for new reloc type + + +2006-07-18 Nick Kledzik + + src/MachOReaderRelocatable.hpp: suppress warning about dwarf info parsing for one benign no-op case + the compiler emits when there are not functions in the __text section + + +2006-07-17 Nick Kledzik + + faster debug note generation + src/ld.cpp: rework collectDebugInfo() to produce all debug notes in one pass, intead of a + pass per .o file. Added timing info for collectDebugInfo() to -print_statistics + unit-tests/test-cases/dwarf-debug-notes-r/Makefile: add expliced -arch to ld -r + unit-tests/test-cases/dwarf-debug-notes-r/expected-stabs: alter for new debug notes order + + +2006-07-17 Nick Kledzik + + ld64 VSIZE is 1.18GB when building Finder ppc64 + src/ld.cpp: fixed typo in createReader() that prevented dylibs from being unmapped + +----- Tagged ld64-61.1 + +2006-07-11 Nick Kledzik + + ld64-61: gcc DejaGnu tests failing due to -arch followed by unknown architecture name + src/Options.cpp: map ppc750, ppc7400, ppc7450, and ppc970 to ppc. Improve error message + +2006-07-11 Nick Kledzik + + If -arch is missing, rollover to ld_classic does not happen + src/Options.h: make gotoClassicLinker() public + src/ld.cpp: call gotoClassicLinker() if the inferred architecture is ppc or i386 + +----- Tagged ld64-61 + +2006-06-29 Nick Kledzik + + ld64 should be renamed to ld + src/Options.cpp: exec() ld_classic if -arch ppc or -arch i386 is seen + src/ld.cpp: alter version string + ld64.xcodeproj/project.pbxproj: change install location to /usr/bin/ld, add symlink from /usr/bin/ld64 + doc/man/man1/ld.1: added + +----- Tagged ld64-60 + +2006-06-28 Nick Kledzik + + Can't link large ppc64 program: ld64 says "bl out of range" + MachOWriterExecutable.hpp: fix branch island generation to work for weak_import functions + and properly chain together branch islands + MachOReaderRelocatable.hpp: improve performance of huge .o file reading by sorted references + only when done + +2006-06-28 Nick Kledzik + + MySQL-36 fails to build with ld64-59 + src/MachOReaderRelocatable.hpp: back out fix for 4585335 + src/MachOWriterExecutable.hpp: back out fix for 4585335 + +2006-06-27 Nick Kledzik + + src/MachOReaderRelocatable.hpp: handle N_GSYM without ending :G() since that is how + dwarf debug notes are formed. + +2006-06-23 Nick Kledzik + + + + ld64 doesn't support variant linking -framework fw,_debug + src/Options.cpp: enhance findFramework() to support suffixes + +----- Tagged ld64-59 + +2006-06-22 Nick Kledzik + + ld64 lost DWARF debug notes + src/MachOReaderRelocatable.hpp: add fHasUUID so kDebugInfoStabsUUID can be set later + unit-tests/test-cases/dwarf-debug-notes-r: added test case + +2006-06-21 Nick Kledzik + + python 64-bit address miscalculation + src/MachOReaderRelocatable.hpp: change getTargetOffset() to sign extend the 32-bit value to 64-bits + +2006-06-21 Nick Kledzik + + ld64 seems to offset things incorrectly when using -r + src/MachOWriterExecutable.hpp: in -r mode, virtual sections should not increment address + + +----- Tagged ld64-58 + +2006-06-16 Nick Kledzik + + src/rebase.cpp: fix page alignment problem + src/rebase.cpp: fix endianess problem with local non-lazy pointers + +2006-06-15 Nick Kledzik + + src/rebase.cpp: fix to build in CurryWeed + ld64.xcodeproj/project.pbxproj: fix to build properly in CurryWeed + +2006-06-15 Nick Kledzik + + Support .objc_class_name_* symbols + src/ObjectFile.h: Add kSymbolTableInAsAbsolute + src/MachOReaderRelocatable.hpp: synthesize references to required objc classes + src/MachOWriterExecutable.hpp: write objc_class_name as absolute symbol + unit-tests/test-cases/objc-references: added + +2006-06-15 Nick Kledzik + + SECTION_ATTRIBUTES unset in ppc64 mach-o header + src/MachOWriterExecutable.hpp: add section attribute for sections with code + +2006-06-15 Nick Kledzik + + ld64 bogus duplicate symbol name linking GNU libobjc + src/MachOReaderRelocatable.hpp: only special case Apple objc runtime objc classes + +2006-06-15 Nick Kledzik + + x86_64: ".align" directive not honored + src/MachOReaderRelocatable.hpp: change code alignment to not depend on atom size + +2006-06-14 Nick Kledzik + + jump table into middle of weak symbol causes error + src/MachOReaderRelocatable.hpp: create direct references to the interior of weak symbols + src/MachOWriterExecutable.hpp: do not error on absolute references to interior of weak symbols + +2006-06-13 Nick Kledzik + + src/Options.cpp: allow -image_base as an alias for -seg1addr + +2006-06-13 Nick Kledzik + + implement -d + src/Options.h: add fMakeTentativeDefinitionsReal + src/Options.cpp: set fMakeTentativeDefinitionsReal if -d option is found + src/MachOWriterExecutable.hpp: turn tentative into real definition if makeTentativeDefinitionsReal + unit-tests/test-cases/btentative-to-real: added test case + +2006-06-13 Nick Kledzik + + implement -bundle_loader + src/Options.h: add fBundleLoader bit to DynamicLibraryOptions + src/Options.cpp: handle -bundle_loader + src/ld.cpp: pass fBundleLoader bit to MachOReaderDylib + src/MachOReaderDylib.hpp: support reading MH_EXECUTE files if fBundleLoader is set + src/MachOWriterExecutable.hpp: set bundle loader ordinal as EXECUTABLE_ORDINAL + unit-tests/test-cases/bundle_loader: added test case + +2006-06-12 Nick Kledzik + + -syslibroot can cause "can't find ordinal for imported" error + src/MachOReaderDylib.hpp: in Reader::reExports() compare install path in addition to load path + + +2006-06-10 Nick Kledzik + + Need rebasing tool + src/rebase.cpp: added + unit-tests/test-cases/rebase-basic: added + doc/man/man1/rebase.1: added + ld64.xcodeproj/project.pbxproj: added rebase target. changed all targets to build with dwarf + + +2006-06-10 Nick Kledzik + + src/machochecker.cpp: add some ppc reloc sanity checking + +----- Tagged ld64-57 + +2006-06-06 Nick Kledzik + + ld64 is not adding a final '/' char on the initial directory-name SO stab debug map entry + ld.cpp: Change Linker::synthesizeStabs() to assure directory SO always has a trailing slash + unit-tests/test-cases/dwarf-debug-notes/expected-stabs: update with trailing / + +2006-06-06 Nick Kledzik + + -sectcreate of a 0-byte section fails + MachOWriterExecutable.cpp: Don't error out on zero length segments + MachOWriterExecutable.cpp: For ppc64 reloc base address is the first writable segment iff + there is a writable segment >4GB from base address + +2006-06-04 Eric Christopher + + Radar 4560240 + Radar 3964999 + * src/ld.cpp (createReader): Fixed error message. + (resolve): Ditto. + (resolveFrom): Ditto. + (checkUndefines): Ditto. + +----- Tagged ld64-56 + +2006-05-23 Nick Kledzik + + No debug notes for ObjC methods when linking with ld64 + ld.cpp: don't limit debug notes to functions starting with underscore + +2006-05-22 Nick Kledzik + + ld64 spends much time in mach_o::relocatable::Reader::findAtomByName + * src/MachOReaderRelocatable.hpp: add makeReferenceToSymbol() so that x86_64 does not need to do by-name lookups + +2006-05-22 Nick Kledzik + + remove inferring warning + * ld.cpp: Remove "inferring" warning. If a link failed and now arch was specifed add which arch was + inferred to error message + +2006-05-19 Nick Kledzik + + ld64 does not honor -arch_multiple + * ld.cpp: If fOptions.printArchPrefix(), add architecture name to error message + +2006-05-19 Nick Kledzik + + Support S_16BYTE_LITERALS section types + * src/MachOReaderRelocatable.hpp: support S_16BYTE_LITERALS + * src/MachOWriterExecutable.hpp: support S_16BYTE_LITERALS + +2006-05-19 Nick Kledzik + + "warning can't parse dwarf compilation unit info" warnings building debug + * src/MachOReaderRelocatable.hpp: fix bugs in dwarf line table parsing + +----- Tagged ld64-55 + +2006-05-18 Nick Kledzik + + Default the pagezero size to 4GB for x86-64 + * src/Options.cpp: Chnage default the pagezero size to 4GB for x86-64 + +2006-05-18 Nick Kledzik + + x86_64 CarbonCore fails to link with "atom not found in symbolIndex" + * src/MachOWriterExecutable.hpp: in buildObjectFileFixups() don't call addObjectRelocs() on kNoFixUp references + +2006-05-18 Nick Kledzik + + ld64: .section defaults to read-only + * src/MachOReaderRelocatable.hpp: default unknown segments to r/w + +2006-05-18 Nick Kledzik + + -fvisibility=hidden causes crashes for x86_64 + * src/MachOWriterExecutable.hpp: properly handle RIP relative tentative definitions + +2006-05-12 Nick Kledzik + + * src/Architectures.hpp: add x86::kAbsolute32 + * src/MachOReaderRelocatable.hpp: generate x86::kAbsolute32 for mdynamic-no-pic instructions + * src/MachOWriterExecutable.hpp: process x86::kAbsolute32 reference kind + +----- Tagged ld64-54 + +2006-05-11 Nick Kledzik + + CF-393 failes to link for x86_64 + * src/MachOWriterExecutable.cpp: fix sign extension for Rel32 relocs in Writer::fixUpReferenceRelocatable + +2006-05-11 Nick Kledzik + + warning arch x86_64 not found using i386 + * src/ld.cpp: remove hack to allow x86_64 to link against i386 dylibs + + +2006-05-10 Nick Kledzik + + x86_64: .objc_class_name symbol names scrambled + * src/MachOReaderRelocatable.hpp: properly compute alignment of __OBJC __class sections + + +2006-05-08 Nick Kledzik + + Support -dead_strip + * src/Options.h/cpp: implement -why_load and -why_live. Enable -dead_strip. + * src/MachOReaderArchive.hpp: implement -why_load + * src/MachOReaderRelocatable.hpp: suppress GCC_except_table* symbols in final output + * src/ld.cpp: implement dead code stripping + * unit-tests/test-cases/dead_strip: added + +----- Tagged ld64-53 + +2006-05-05 Nick Kledzik + + * src/Options.cpp: make 10.4 be minimum OS version for newer architectures + +2006-05-05 Nick Kledzik + + N_SO symbols in 64-bit builds have a zero address for n.n_value + * src/ld.cpp: for SO stabs, associate first and last atom in the SO range + * src/MachOWriterExecutable.hpp: use atom associated with SO stab to set ins n_value + +2006-05-05 Nick Kledzik + + * MachOWriterExecutable.hpp: fix end FUN stab to have length of function + + +2006-05-02 Nick Kledzik + + 64-bit main executables should have 4GB zero page by default + * src/Opptions.cpp: change default pagezero_size to 4GB for ppc64 + 64 bit: apps with -mdynamic-no-pic seg fault when page zero > 4GB + * src/MachOWriterExecutable.cpp: rework pagezero for ppc64 so that if any mdynamic-no-pic code + is found, the code is kept in the low 2GB, and a new segment is create to map away up to 4GB. + +2006-05-02 Nick Kledzik + + * src/Opptions.cpp: remove warning about -stack_addr not specified. Add warning if 32-bit stack + overlaps shared region + +----- Tagged ld64-52.1 + +2006-05-01 Nick Kledzik + + * src/MachOReaderRelocatable.cpp: rework handleAnonymousNonLazyPointers() to handle anl's in the middle + the __data section too. + +----- Tagged ld64-52 + +2006-04-28 Nick Kledzik + + 64-bit: 9A152 TextEdit crashes in dlopen on bring-up + * src/MachOReaderRelocatable.cpp: rework anonymous non-lazy-pointer detection + +2006-04-28 Nick Kledzik + + 64 Bit: Development build of ppc64 TextEdit gets confused about static variables + * src/MachOReaderRelocatable.cpp: mark non-lazy-pointer atoms as scopeTranslationUnit if targetting a static symbol + + + +2006-04-21 Nick Kledzik + + * src/Options.cpp: fix default address for ppc64 custom stack + * src/MachOWriterExecutable.cpp: fix set up of ppc64 custom stack + + +2006-04-14 Nick Kledzik + + * src/Options.cpp: fix -sub_library processing to work it dylib is specifed with leaf name + +----- Tagged ld64-51.1 + +2006-04-13 Nick Kledzik + + 64-bit: 9A152 TextEdit crashes in dlopen on bring-up + * src/MachOReaderRelocatable.hpp: when detecting anonymous non-lazy-pointers disqualify data + that points to static or global symbols + * src/ld.cpp: print version of ld64 in error messages + + +----- Tagged ld64-51 + +2006-04-11 Nick Kledzik + + exported symbols not properly stripped + * src/MachOReaderRelocatable.hpp: enable AnonymousAtom::setScope() + +2006-03-31 Nick Kledzik + + ld64 fails when linking debug ppc64 HIToolbox + * src/MachOReaderRelocatable.hpp: handle anonymous non-lazy pointers encoded with local relocations + * src/MachOWriterExecutable.hpp: in -r mode, only generated INDIRECT_SYMBOL_LOCAL for non-lazy targets that + + +2006-03-31 Nick Kledzik + + ld64 should remove generated file if link errors out + * src/MachOWriterExecutable.hpp: catch exceptions in Writer::write(), delete output file, and rethrow + + +----- Tagged ld64-50 + + +2006-03-29 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: synthesize .objc_class_name symbols + * src/MachOFileAbstraction.hpp: use strncpy for sect/seg names to zero fill trailing space + +2006-03-28 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix spurious warning about dwarf line info + +----- Tagged ld64-49.1 + +2006-03-25 Nick Kledzik + + * MachOWriterExecutable.hpp : don't complain about ppc64 dyld being based > 4GB + +----- Tagged ld64-49 + +2006-03-24 Nick Kledzik + + * src/MachOWriterExecutable.hpp: dyld is allowed to have synthesized non-lazy pointers + ld64 is after processing bad GSYM stabs + * src/MachOReaderRelocatable.hpp: if a GSYM is found that does not match any data symbol, suppress it + +2006-03-23 Nick Kledzik + + * src/MachOWriterExecutable.hpp: in Writer::fixUpReferenceFinal() fix when x86::kPointer is for an + external relocation + +2006-03-23 Nick Kledzik + + * src/Options.cpp: change macosx-min-version to default to a per-architecture setting + add warning if -pagezero_size is not page aligned + * src/MachOWriterExecutable.hpp: properly handle external relocations for ppc64 with 4GB pagezero + * src/machochecker.cpp: sanity check relocation records + +----- Tagged ld64-48 + +2006-03-21 Nick Kledzik + + 64bit: passing function pointer to another function passes the wrong function address + * src/MachOReaderRelocatable.hpp: when processing a non-lazy pointer to a static function, don't accidentally + match it to a STAB symbol. + +2006-03-21 Nick Kledzik + + .eh symbols make up 13% of libstdc++'s stripped binary size + * src/ObjectFile.h: add ReaderOptions.fForFinalLinkedImage + * src/Options.cpp: setup ReaderOptions.fForFinalLinkedImage + * src/MachOReaderRelocatable.hpp: mark .eh symbols kSymbolTableNotIn when building final linked image + +2006-03-21 Nick Kledzik + + ld64 does not parse optional second argument to -filelist + * unit-tests/test-cases/filelist: added + * src/Options.cpp: in Options::loadFileList() handle comma option + + +----- Tagged ld64-47.1 + + +----- Tagged ld64-47 + + +----- Tagged ld64-46 + +2006-03-10 Nick Kledzik + + ld64 should figure out architecture from .o files + * unit-tests/test-cases/auto-arch: added + * src/ld.cpp: added Linker::inferArchitecture() to scan .o files are infer architecture to link + * src/MachOReaderArchive.hpp: enhanced validFile() to look deeper into archive and really valdate + * src/MachOWriterExecutable.hpp: stop using fOptions.architecture() + * src/Options.cpp: stop defaulting to ppc64 + + +2006-03-09 Nick Kledzik + + Need "intentionally left blank" dylib stubs + * unit-tests/include/common.makefile: add VALID_ARCHS + * unit-tests/run-all-unit-tests: set up VALID_ARCHS + * unit-tests/test-cases/blank-stubs: add test case + * src/ld.cpp: in addDylib(), detect and ignore blank stubs + * src/MachOReaderDylib.hpp: in constructor, handle blank stubs + +2006-03-09 Nick Kledzik + + crash in stub with 2GB pagezero + * src/MachOWriterExecutable.hpp: StubAtom can't be no-pic if a large zero-page is used + +2006-03-06 Nick Kledzik + + * src/Options.cpp: addSectionAlignment, warn if -sectalign alignment is not a power of two + +----- Tagged ld64-45 + + +2006-03-06 Nick Kledzik + + LP64/9A122: ld64: hang when trying to link DiscRecording framework + * src/Options.cpp: addSectionAlignment, warn on zero. Use log2() for alignment conversion + + +----- Tagged ld64-44 + +2006-03-04 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix again test for detection of anonymous non-lazy-pointer. + Error out if .o file contains old __DWARFA style dwarf. + +2006-03-02 Nick Kledzik + + * src/ld.cpp: only re-map page aligned sub-parts of a fat file. A conformat mmap() requires alignment. + +----- Tagged ld64-43 + + +2006-03-02 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: tighten detection of anonymous non-lazy-pointer + +----- Tagged ld64-42 + +2006-02-28 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix x86 __IMPORT permissions for class Segment + +2006-02-28 Nick Kledzik + + SWB: ld64-37 (can't resolve symbol ___dso_handle) + * src/MachOWriterExecutable.hpp: add class DsoHandleAtom + +2006-02-28 Nick Kledzik + + * unit-tests/test-cases/literals-coalesce-alignment: added test case + * src/ld.cpp: when coalescing strings pick one with greater alignment + ld64: CG link failed because lo14 reference to anonymous non-lazy-pointer not aligned + * unit-tests/test-cases/relocs-c/test.c: tweak to fail like 4458660 + * src/MachOReaderRelocatable.hpp: detect anonymous non-lazy-pointer and transform into real non-lazy-pointers + +----- Tagged ld64-41 + +2006-02-24 Nick Kledzik + + * src/Options.cpp: Warning about -no_dead_strip_inits_and_terms and -i options. + Fix -weak-l option. + +----- Tagged ld64-40 + +2006-02-24 Nick Kledzik + + Leopard9A113: ppc64 libstdc++.dylib initializer crashes in pthread_once + * unit-tests/test-cases/multiple-entry-points: added + * src/MachOReaderRelocatable.hpp: make sure that if there are multiple symbols with the same + address, that we properly make zero length atoms for all but last symbol + +2006-02-24 Nick Kledzik + + * src/Options.cpp: ld64 doesn't realpath(3) B&I tracing paths + +2006-02-24 Nick Kledzik + + * src/Options.cpp: 9A110: ld64 can't deal with section names >16 chars + +2006-02-23 Nick Kledzik + + * src/MachOWriterExecutable.hpp: use vector.reserve() to minimize re-allocations + * src/Options.cpp: use vector.reserve() to minimize re-allocations + * src/MachOReaderRelocatable.hpp: use vector.reserve() to minimize re-allocations + * src/MachOReaderDylib.hpp: use vector.reserve() to minimize re-allocations + * src/ld.cpp: use vector.reserve() to minimize re-allocations + +2006-02-23 Nick Kledzik + + ld64 creates corrupt executables (and has malloc errors) with -headerpad option + * src/MachOWriterExecutable.hpp: Change LoadCommandsPaddingAtom::setSize() to update fLargestAtomSize + * unit-tests/test-cases/header-pad: added + +2006-02-23 Nick Kledzik + + ld64 creates invalid static executables + * src/MachOWriterExecutable.hpp: Change MachHeaderAtom::copyRawContent() to create correct header + for static executables. Change SymbolTableLoadCommandsAtom to skip LC_DYSYMTAB for static executables + * src/machochecker.cpp: Add tests that static executables are well formed + * unit-tests/test-cases/static-executable: added + +2006-02-22 Nick Kledzik + + * src/Options.cpp: chnage printf on unknown arg to a throw + +----- Tagged ld64-39 + +2006-02-20 Nick Kledzik + + * unit-tests/test-cases/read-only-relocs: added new test case + * src/MachOWriterExecutable.hpp: detect and error on relocs in read-only sections + * src/MachOReaderRelocatable.hpp: fix parsing of i386 absolute addressing relocs + +2006-02-20 Nick Kledzik + + * unit-tests/test-cases/stabs-coalesce: added new test case + * src/ld.cpp.hpp: in collectStabs removed unused stabs + +----- Tagged ld64-38 + +2006-02-17 Nick Kledzik + + * src/MachOWriterExecutable.hpp: set correct n_sect field of stabs + +2006-02-15 Nick Kledzik + + * src/MachOReaderArchive.hpp: with -all_load skip over both kinds of SYMDEFs + * unit-tests/test-cases/archive-basic/Makefile: add -all_load test case + +----- Tagged ld64-37 + +2006-02-13 Eric Christopher + + * src/MachOWriterExecutable.hpp (assignFileOffsets): Simplify. Add comments. + Adjust whitespace. + +2006-02-13 Nick Kledzik + + * src/MachOWriterExecutable.hpp: in Writer::fixUpReferenceRelocatable() fix kPCRel32 for external case + +2006-02-13 Nick Kledzik + + * unit-tests/test-cases/zero-fill: added + * src/machochecker.cpp: check that S_ZEROFILL have no file offset + * src/MachOWriterExecutable.hpp: rework assignFileOffsets() to fix rdar://problem/4441145 + +2006-02-12 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix use of first zero-length c-string in .o file + +2006-02-12 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix uninitialized fAlignment + +2006-02-12 Nick Kledzik + + * unit-tests/test-cases/relocs-asm/relocs-asm.s: add pointer-diff cases + * src/Architectures.hpp: make size explicit in ppc/ppc64 kPointerDiff + * src/MachOReaderRelocatable.hpp: don't allow kPointerDiff64 for ppc (just ppc64) + * src/MachOWriterExecutable.cpp: set proper r_length for ld -r of kPointerDiff + +----- Tagged ld64-36 + +2006-02-08 Nick Kledzik + + * src/MachOReaderRelocatable.cpp: rdar://problem/4438677 Handle when a .o file dwarf line info entries but no functions + +2006-02-08 Nick Kledzik + + * src/MachOWriterExecutable.cpp: Properly set address of first TEXT section + Keep S_COALESCED attribute for __eh_frame + +2006-02-08 Nick Kledzik + + * src/ld.cpp: Temporarily turn allowable client errors into warnings + * unit-tests/test-cases/allowable-clientMakefile: Temporarily let warnings be ok for above + * src/MachOWriterExecutable.hpp: fix ld -r to not use external relocations for symbols make static + +2006-02-08 Nick Kledzik + + * src/ld.cpp: A sibling in an umbrella can always link with its other siblings + * unit-tests/test-cases/allowable-client: add test case for above + +2006-02-08 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: support LOCAL non-lazy pointers to hidden symbols + * src/machochecker.cpp: verify indirect symbol table + * unit-tests/test-cases/private-non-lazy: added test case + +2006-02-07 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix calculation of file offsets in ld -r mode + * src/machochecker.cpp: verify segment file offsets are within file + +----- Tagged ld64-35 + +2006-02-06 Nick Kledzik + + * ld.cpp: allow parent of sub-framework to link + * unit-tests/test-cases/allowable-client/Makefile: added cases for parent and clients of parent + +2006-02-04 Nick Kledzik + + * unit-tests/test-cases/relocs-c/test.c: added some array cases + * src/MachOReaderRelocatable.hpp: factor out makeReferenceToEH() + * src/MachOWriterExecutable.hpp: add initial support for non-lazy pointer synthesis + +----- Tagged ld64-34 + +2006-02-04 Nick Kledzik + + * src/ld.cpp: fix -no_arch_warnings + fix -undefined warning + Do BINCL/EINCL optimization for gfull stabs + Implement "essential symbols" for stabs (-Sp) + Fix allowable clients to only test on direct libraries + * src/MachOReaderRelocatable.hpp: support BINCL/EINCL stabs + +2006-02-03 Nick Kledzik + + * src/machochecker.cpp: add code to check load command alignment + * src/MachOWriterExecutable.hpp: make load command alignment depend on architecture + +2006-02-03 Nick Kledzik + + * unit-tests/test-cases/literals-coalesce: added + * src/MachOReaderRelocatable.hpp: assure all targets of low14 ppc relocs are at least 4-byte alignmented + +----- Tagged ld64-33 + +2006-02-02 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: properly coalesce 8-byte literals + * src/MachOWriterExecutable.hpp: support ppc64::kPointerDiff32 + +----- Tagged ld64-32 + +2006-02-02 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: support anonymous zero fill atoms + +2006-02-02 Nick Kledzik + + * src/ld.cpp: A weak definition is good enough, do not search archives for a non-weak one + * unit-tests/test-cases/archive-weak: add test case for above + * src/MachOReaderRelocatable.hpp: an atom should never have a by-name reference to itself + * src/Options.cpp: prevent .eh symbols from being exported via a -exported_symbols_list + +2006-02-01 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: Support -macosx_version_min 10.5 + +2006-02-01 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: don't try to parse debug_line dwarf if no symboled atoms + +----- Tagged ld64-31 + +2006-02-01 Eric Christopher + + * unit-tests/test-cases/allow-stack-execute/Makefile: Move otool handling... + * unit-tests/include/common.makefile: ... here. + * unit-tests/bin/fail-if-stdin.pl: New. + * unit-tests/test-cases/no-uuid: Ditto. + * src/ld.cpp (Linker::) Add fCreateUUID. + (::Linker): Initialize. + (::collectStabs): Use. Set if dwarf or we have a UUID already. + (::writeOutput): Pass as argument to Writer::write along with option. + * src/Options.h (Option::emitUUID): Declare. + (Option::fEmitUUID): Ditto. + * src/Options.cpp (Option::emitUUID): New. + (parse): Handle -no_uuid. + * src/MachOReaderRelocatable (Reader::Reader): Handle LC_UUID. + * src/ExecutableFile.h (Writer::Write): Add createUUID boolean. + * src/MachOWriterExecutable: Add UUID forward declaration. + (fUUIDAtom): New. + (UUIDLoadCommandAtom): Emit LC_UUID if fEmit. New function emit. Size + to zero at start. + (Writer::writer): Add handle for LC_UUID. If createUUID emit LC_UUID. + (MachHeaderAtom::copyRawContent): Don't count a load command if its size is + 0. + (UUIDLoadCommandAtom::copyRawContent): Depend on fEmit. + + +2006-01-31 Nick Kledzik + + * unit-tests/test-cases/dwarf-debug-notes : Added + * src/ld.cpp: don't generate debug note for .eh symbols + * src/MachOReaderRelocatable.hpp: make dwarf line info to atom matching faster and better + +2006-01-31 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj : Make buildable on Leopard + * src/MachOFileAbstraction.hpp: make buildable without latest cctools headers + +2006-01-31 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: better error message for bad relocs + * src/ObjectDump.cpp: add emacs tab settings + * src/SectCreate.h: ditto + * src/SectCreate.cpp: ditto + * src/machochecker.cpp: ditto + * src/ExecutableFile.h: ditto + +2006-01-30 Eric Christopher + + * src/ExecutableFile.h: Indent. + +2006-01-30 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: performance improvements + * src/ld.cpp: now that stubs are synthesized in write, don't need to special case anymore + +2006-01-30 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix parsing of pcc relocs + * unit-tests/test-cases/relocs-asm/relocs-asm.s: add test case for above + +2006-01-29 Nick Kledzik + + * unit-tests/test-cases/weak_import: added test case + * src/ld.cpp: move code for weak_import mismatch to writer + * src/ObjectFile.h: remove ImportWeakness methods + * src/MachOReaderDylib.hpp: ditto + * src/SectCreate.cpp: ditto + * src/Architectures.hpp: add new ReferenceKinds for weak_imports + * src/MachOReaderRelocatable.hpp: implement new ReferenceKinds + * src/MachOWriterExecutable.hpp: handle new ReferenceKinds and weak_import mismatches + +2006-01-29 Nick Kledzik + + * src/Options.cpp: verify -allow_stack_execute is only used on main executables + +2006-01-29 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: sync with latest dwarf reader from Geoff + * src/debugline.c: sync with latest dwarf reader from Geoff + +2006-01-27 Eric Christopher + + * src/ld.cpp (Linker::syntesizeStabs): Correct spelling. Update all uses. + +2006-01-27 Eric Christopher + + * src/Options.h (Options): Add hasExecutableStack, fExecutableStack. + * src/Options.cpp (Options::hasExecutableStack): New. + (Options::parse): Parse -allow_stack_execute. + * src/MachOWriterExecutable.hpp (MachHeaderAtom::copyRawContent): + Implement MH_ALLOW_STACK_EXECUTION. + * unit-tests/include/common.makefile (FAIL_IF_EMPTY): New. + * unit-tests/bin/fail-if-no-stdin.pl: New file. + * unit-tests/test-cases/allow-stack-execute: New directory. + +2006-01-27 Nick Kledzik + + * src/MachOFileAbstraction.hpp: rely on latest system headers + * src/MachOWriterExecutable.hpp: fix ppc stubs. + wrote new relocationNeededInFinalLinkedImage() to replace common code + +2006-01-27 Eric Christopher + + * src/ld.cpp (logTraceInfo): New. + (Linker::addArchive): Use. + (Linker::addDylib): Ditto. + * src/ObjectFile (ReaderOptions::fTraceOutputFile): New. + * src/MachOReaderArchive.hpp (Reader::Reader): Move trace + logging to Linker::addArchive. + * src/Options.cpp (parsePreCommandLineEnvironment): Check + LD_PRINT_FILE if tracing dylibs or archives. + +2006-01-26 Nick Kledzik + + * src/MachOWriterExecutable.hpp: handle NULL strings in SO debug notes + +2006-01-26 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix header padding calculation and thread state + +2006-01-26 Nick Kledzik + + Rewrite all stabs processing. + Move sythesize of debug notes into ld.cpp + +2006-01-26 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix ppc and ppc64 stub relocs + +2006-01-25 Nick Kledzik + + * ld64.xcodeproj/project.pbxproj: special case building in Curry + +2006-01-25 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix bugs in stub/lazy-pointer synthesis + +2006-01-24 Eric Christopher + + * src/ld.cpp (Linker::createReaders): Change logging title to XBS. + (Linker::addDylib): Ditto. + * src/MachOReaderArchive.hpp (Reader::Reader): Ditto. + * src/Options.h (fPrintOptions): New. + * src/Options.cpp (Options::Options): Initialize above. + (Options::checkForFile): Change logging title to XBS. + (Options::findFramework): Ditto. + (Options::parse): Add log for options. + (Options::parsePreCommandLineEnvironmentSettings): Add LD_TRACE_ARCHIVES, + LD_TRACE_DYLIBS, and LD_PRINT_OPTIONS. + +2006-01-24 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: better C++ eh parsing + +2006-01-23 Eric Christopher + + * unit-tests/bin/fail-if-exit-zero.pl: New. + * unit-tests/include/common.makefile (FAIL_IF_SUCCESS): Use. + * unit-tests/allowable-client: New test. + * src/ld.cpp (Linker::addDylib): Check allowable clients before adding dylib. + * src/Options.h (allowableClients): New. + (clientName): Ditto. + (fAllowableClients): Ditto. + (fClientName): Ditto. + * src/Options.cpp: Implement above. + (parse): Handle -allowable_client and -client_name. + * src/MachOReaderDylib.hpp (getAllowableClients): New. + (fAllowableClients): Ditto. + (Reader): Process LC_SUB_CLIENT load command. + * src/ObjectFile.h (parentUmbrella): New. + (getAllowableClients): New. + * src/MachOWriterExecutable.hpp (AllowableClientLoadCommandsAtom): New. + +2006-01-23 Nick Kledzik + + * unit-tests/test-cases/archive-basic: added + * src/ld.cpp: fix shadowed local variable + * src/FileAbstraction.hpp: ld64 shouldn't inline when building debug + +2006-01-23 Nick Kledzik + + * src/ld.cpp: fix symbol not found error message + * src/MachOReaderDylib.hpp: add logging to hash table + * src/MachOReaderRelocatable.hpp: enable stabs processing. Handle static functions with stubs + handle labeled cstrings. + * src/MachOWriterExecutable.hpp: properly suppress atoms not in symbol table. fix low14 error check. + add StubAtomHelper. + * unit-tests/test-cases/relocs-literals/test.c: add more interesting edge cases + +2006-01-17 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: tweaks to synthesizing debug notes + +2006-01-16 Nick Kledzik + + * src/debugline.{sh}: added + * src/MachOReaderRelocatable.hpp: synthesize debug notes SOL from dwarf + * src/MachOWriterExecutable.hpp: fix lazy pointer section + * src/ObjectDump.hpp: Fix conditionalization + * unit-tests/test-cases/dwarf-strip: added + +2006-01-11 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: support Tiger crt1.o build with old ld64 + * src/ObjectDump.hpp: Support -arch option + +2006-01-10 Nick Kledzik + + * src/MachOWriterExecutable.hpp: fix stubs for ppc64 + * src/MachOFileAbstraction.hpp: fix typo for macho_routines + * ld64.xcodeproj/project.pbxproj: add machochecker target + * src/machochecker.cpp: new skeleton for checking mach-o file bit + * unit-tests/: Add support for running machochecker + +2006-01-10 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: warn if dwarf can't be parsed + * src/MachOReaderArchive.hpp: modTime for OSO stabs from archives is .a modTime + +2006-01-09 Nick Kledzik + + * track modification time of .o files so that sythesized OSO stab will have it + +2006-01-09 Nick Kledzik + + * src/MachOFileAbstraction.hpp: add macho_uuid_command + * src/MachOWriterExecutable.cpp: add UUID load command to generated files + +2006-01-09 Nick Kledzik + + * src/MachOReaderDylib.hpp: no longer keep dylib memory mapped + * src/ld.cpp: don't track dylib sizes because they are not longer memory mapped + +2006-01-05 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: support new relocations + +2006-01-05 Nick Kledzik + + * src/MachOReaderDylib.hpp: support MH_DYLIB_STUB + * src/MachOReaderRelocatable.hpp: Add Geoff's comp unit extractor + +2006-01-05 Nick Kledzik + + refactor: transform Atom::dontStripName() to getSymbolTableInclusion() + * src/ld.cpp: pass dyld_stub_binding_helper to writer + * src/MachOReaderRelocatable.hpp: update synthesized stabs + Ignore stubs and lazy pointers in .o files + Support initializers and terminators + * src/MachOWriterExecutable.hpp: synthesize stubs and lazy pointers as needed + * ld64.xcodeproj/project.pbxproj: change Release target to build with dwarf + +2006-01-03 Eric Christopher + + * src/Options.h (multipleDefinitionsInDylibs): Declare. + (overridingDefinitionInDependentDylib): Ditto. + (warnOnMultipleDefinitionsInObjectFiles): Ditto. + (multiplyDefined): Remove. + (multiplyDefinedUnused): Ditto. + (fMultiplyDefined): Ditto. + (fWarnOnMultiplyDefined): New. + (fMultiplyDefinedDynamic): Ditto. + * src/Options.cpp (Options::Options): Initialize above. + (overridingDefinitionInDependentDylib): New. + (multipleDefinitionsInDylibs): Ditto. + (warnOnMultipleDefinitionsInObjectFiles): Ditto. + (parse): Update comments. Fix parsing of -y option. + Update error message for -dead_strip. Parse above + options. + +2006-01-02 Nick Kledzik + + * Refactor: move Atom::writeContent() to Writer + +2005-12-23 Nick Kledzik + + * Reworked, simplify, and document test harness + * unit-tests/README: Added + +2005-12-23 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fixes for Objective-C + * unit-tests/test-cases/relocs-objc: Added + +2005-12-22 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: fix check that next reloc is pair + * src/MachOReaderRelocatable.hpp: Add code to synthesize essential stabs from dwarf + +2005-12-21 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: Fix parsing of literal sections + * src/MachOWriterExecutable.hpp: Fix writing of literal sections + * unit-tests/test-cases/relocs-literals: Added + +2005-12-15 Eric Christopher + + * src/Options.h (enum Treatment): New. + (enum PICTreatment): Delete. + (enum VersionMin): New. + (prebind): Declare. + (macosxVersionMin): Ditto. + (multiplyDefined): Ditto. + (multiplyDefinedUnused): Ditto. + (setVersionMin): Ditto. + (setPICTreatment): Delete. + (setReadOnlyRelocTreatment): Ditto. + (picTreatment): Adjust return type. + (parseTreatment): New. + (fPrebind): Ditto. + (fVersionMin): Ditto. + (fPICTreatment): Change type. + (fMultiplyDefined): New. + (fMultiplyDefinedUnused): Ditto. + (fLimitUndefinedSymbols): Ditto. + + * src/Options.cpp: Fix whitespace. Add comments on options. + (Options::Options): Add initializers for new variables. + (Options::prebind): New. + (Options::macosxVersionMin): Ditto. + (Options::parseTreatment): Ditto. + (Options::setVersionMin): Ditto. + (Options::setReadOnlyRelocTreatment): Delete. + (Options::setPICTreatment): Ditto. + (Options::Parse): Update for above. Add comments. + +2005-12-15 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: Add comments about dwarf + +2005-12-14 Nick Kledzik + + * src/ELFFileAbstraction.hpp: Added + * src/ELFReaderRelocatable.hpp: Added + * Lot of fixes for new architecture + * Added __OPEN_SOURCE__ to "Preprocessor Macros" to disable new architecture support by default + +2005-12-13 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: check for S_ATTR_DEBUG and ignore those sections + * unit-tests/test-cases/dwarf-ignore: added + +2005-12-12 Nick Kledzik + + * Added test harness and three initial tests: + relocs-asm, relocs-c, and hello-world + +2005-12-12 Nick Kledzik + + * src/MachOReaderRelocatable.hpp: Massive refactoring: + Now there are three Atom classes, Chopping into Atoms + is done on label boundaries or by knowledge of special + sections, Share lots of ppc/ppc64 code. + Stabs process code is temporarily disabled. + +2005-12-12 Nick Kledzik + + * src/ObjectDump.cpp: Add command line options: -no_content, -stabs, -no_sort + +2005-12-11 Eric Christopher + + * src/Options.cpp: Reformat. + * src/Options.h: Ditto. + +2005-12-07 Eric Christopher + + * src/MachOReaderRelocatable.hpp (Atom::getAlignment): + When calculating alignment of an Atom, take into account + the alignment from which we pulled the Atom. + +2005-12-06 Nick Kledzik + + * src/Options.cpp src/Options.h: Add design comments + +2005-12-05 Eric Christopher + + * src/ld.cpp (Linker::createWriter): Uncomment ppc64 and + i386 linkers. + +2005-12-05 Eric Christopher + + * ChangeLog: New file. + +2005-12-02 Nick Kledzik + + * src/ObjectFile.h: Add design comments + +2005-11-30 Nick Kledzik + + * Fix uses of __OPEN_SOURCE__ + +2005-11-28 Nick Kledzik + + * Refactor Atom to use getDefinitionKind() + +2005-11-21 Nick Kledzik + + * src/MachOWriterExecutable.hpp: don't generate section for commons in -r mode + +2005-11-18 Nick Kledzik + + * x86 tweaks + +2005-11-18 Nick Kledzik + + * src/ObjectDump.cpp: make work with command line arguments + +2005-11-18 Nick Kledzik + + * Massive rework to remove preprocessor conditionals and use templates + +2005-11-14 Nick Kledzik + + * Created new Subversion repository for ld64 from cvs tag ld64-27.2 diff --git a/doc/man/man1/dyldinfo.1 b/doc/man/man1/dyldinfo.1 new file mode 100644 index 0000000..3dafedc --- /dev/null +++ b/doc/man/man1/dyldinfo.1 @@ -0,0 +1,47 @@ +.Dd November 20, 2008 +.Dt dyldinfo 1 +.Os Darwin +.Sh NAME +.Nm dyldinfo +.Nd "Displays information used by dyld in an executable" +.Sh SYNOPSIS +.Nm +.Op Fl arch Ar arch-name +.Op Fl rebase +.Op Fl bind +.Op Fl weak_bind +.Op Fl lazy_bind +.Op Fl export +.Op Fl opcodes +.Ar file(s) +.Sh DESCRIPTION +Executables built for Mac OS X 10.6 and later have a new format for the +information in the __LINKEDIT segment. The dyldinfo tool will display +that information. +.Pp +The options are as follows: +.Bl -tag -width indent +.It Fl arch Ar arch +Only display the specified architecture. Other architectures in a universal image are ignored. +.It Fl rebase +Display the table of rebasing information. Rebasing is what dyld does when an image is +not loaded at its preferred address. Typically, this involves updating pointers in the __DATA +segment which are point within the image. +.It Fl bind +Display the table of binding information. These are the symbolic fix ups that dyld must +do when an image is loaded. +.It Fl weak_bind +Display the table of weak binding information. Typically, only C++ progams will have any +weak binding. These are symbols which dyld must unique accross all images. +.It Fl lazy_bind +Display the table of lazy binding information. These are symbols which dyld delays binding +until they are first used. Lazy binding is automatically used for all function calls to +functions in some external dylib. +.It Fl export +Display the table symbols which this image exports. +.It Fl opcodes +Display the low level opcodes used to encode all rebase and binding information. +.El +.Sh SEE ALSO +.Xr otool 1 +.Xr nm 1 diff --git a/doc/man/man1/ld.1 b/doc/man/man1/ld.1 old mode 100755 new mode 100644 index a8b0188..c910e04 --- a/doc/man/man1/ld.1 +++ b/doc/man/man1/ld.1 @@ -1,4 +1,4 @@ -.Dd December 8, 2006 +.Dd December 15, 2008 .Dt ld 1 .Os Darwin .Sh NAME @@ -192,6 +192,9 @@ and before the default search path. Loads all members of static archive libraries. .It Fl ObjC Loads all members of static archive libraries that implement an Objective-C class or category. +.It Fl force_load Ar path_to_archive +Loads all members of the specified static archive library. Note: -all_load forces all members of all +archives to be loaded. This option allows you to target a specific archive. .El .Ss Options that control additional content .Bl -tag @@ -217,15 +220,10 @@ Enables dtrace static probes when producing a final linked image. The file .Ar file must be a DTrace script which declares the static probes. .El -.Ss Options that control optimizations +.Ss Options that control optimizations .Bl -tag .It Fl dead_strip Remove functions and data that are unreachable by the entry point or exported symbols. -.It Fl dead_strip_dylibs -Remove dylibs that are unreachable by the entry point or exported symbols. That is, -suppresses the generation of load command commands for dylibs which supplied no -symbols during the link. This option should not be used when linking against a dylib which -is required at runtime for some indirect reason such as the dylib has an important initializer. .It Fl order_file Ar file Alters the order in which functions and data are laid out. For each section in the output file, any symbol in that section that are specified in the order file @@ -238,6 +236,14 @@ This is useful for static functions/data that occur in multiple files. A symbol name may also be optionally preceded with the architecture (e.g. ppc:_foo or ppc:foo.o:_foo). This enables you to have one order file that works for multiple architectures. Literal c-strings may be ordered by by quoting the string (e.g. "Hello, world\\n") in the order file. +.It Fl no_order_inits +When the -order_file option is not used, the linker lays out functions in object file order and +it moves all initializer routines to the start of the __text section and terminator routines +to the end. Use this option to disable the automatic rearrangement of initializers and terminators. +.It Fl no_order_data +By default the linker reorders global data in the __DATA segment so that all global variables that +dyld will need to adjust at launch time will early in the __DATA segment. This reduces the number +of dirty pages at launch time. This option disables that optimization. .It Fl macosx_version_min Ar version This is set to indicate the oldest Mac OS X version that that the output is to be used on. Specifying a later version enables the linker to assumes features of that OS in the output file. The format of @@ -260,13 +266,22 @@ If you link with -framework Cocoa and use a symbol from Foundation, the linker w command to load Foundation and encode the symbol as coming from Foundation. If you use this option, the linker will not add a load command for Foundation and encode the symbol as coming from Cocoa. Then at runtime dyld will have to search Cocoa and AppKit before finding the symbol in Foundation. +.It Fl exported_symbols_order Ar file +When targeting Mac OS X 10.6 or later, the format of the exported symbol information can be optimized to +make lookups of popular symbols faster. This option is used to pass a file containing a list of +the symbols most frequently used by clients of the dynamic library being built. Not all exported symbols +need to be listed. .El -.Ss Options when creating a dynamic library (dylib) +.Ss Options when creating a dynamic library (dylib) .Bl -tag .It Fl install_name Ar name Sets an internal "install path" (LC_ID_DYLIB) in a dynamic library. Any clients linked against the library will record that path as the way dyld should locate this library. If this option is not specified, then the -o path will be used. This option is also called -dylib_install_name for compatibility. +.It Fl mark_dead_strippable_dylib +Specifies that the dylib being built can be dead strip by any client. That is, the dylib has +no initialization side effects. So if a client links against the dylib, but never uses +any symbol from it, the linker can optimize away the use of the dylib. .It Fl compatibility_version Ar number Specifies the compatibility version number of the library. When a library is loaded by dyld, the compatibility version is checked and if the program's version is greater that the library's version, it is an error. @@ -463,6 +478,28 @@ of wildcards. .Bl -tag .It Fl v Prints the version of the linker. +.It Fl no_compact_linkedit +Normally when targeting Mac OS X 10.6, the linker will generate compact information +in the __LINKEDIT segment. +This option causes the linker to instead produce traditional relocation information. +.It Fl no_eh_labels +Normally in -r mode, the linker produces .eh labels on all FDEs in the __eh_frame section. +This option suppresses those labels. Those labels are not needed by the Mac OS X 10.6 +linker but are needed by earlier linker tools. +.It Fl warn_compact_unwind +When producing a final linked image, the linker processes the __eh_frame section and +produces an __unwind_info section. Most FDE entries in the __eh_frame can be represented +by a 32-bit value in the __unwind_info section. The option issues a warning for +any function whose FDE cannot be expressed in the compact unwind format. +.It Fl dead_strip_dylibs +Remove dylibs that are unreachable by the entry point or exported symbols. That is, +suppresses the generation of load command commands for dylibs which supplied no +symbols during the link. This option should not be used when linking against a dylib which +is required at runtime for some indirect reason such as the dylib has an important initializer. +.It Fl allow_sub_type_mismatches +Normally the linker consisders different cpu-subtype for ARM (e.g. armv4t and armv6) to be different +different architectures that cannot be mixed at build time. This option relaxes that requirement, +allowing you to mix object files compiled for different ARM subtypes. .It Fl no_uuid Do not generate an LC_UUID load command in the output file. .It Fl root_safe @@ -516,6 +553,9 @@ specified is a hexadecimal number that indicates the base address for the read-o .It Fl segaddr Ar name Ar address Specifies the starting address of the segment named name to be address. The address must be a hexadecimal number that is a multiple of 4K page size. +.It Fl seg_page_size Ar name Ar size +Specifies the page size used by the specified segment. By default the page size is 4096 for all segments. +The linker will lay out segments such that size of a segment is always an even multiple of its page size. .It Fl dylib_file Ar install_name:file_name Specifies that a dynamic shared library is in a different location than its standard location. Use this option when you link with a library that is dependent on a dynamic library, and the dynamic library is in a location other diff --git a/doc/man/man1/ld64.1 b/doc/man/man1/ld64.1 old mode 100755 new mode 100644 diff --git a/doc/man/man1/rebase.1 b/doc/man/man1/rebase.1 old mode 100755 new mode 100644 diff --git a/doc/man/man1/unwinddump.1 b/doc/man/man1/unwinddump.1 new file mode 100644 index 0000000..3aefe93 --- /dev/null +++ b/doc/man/man1/unwinddump.1 @@ -0,0 +1,22 @@ +.Dd November 7, 2008 +.Dt unwinddump 1 +.Os Darwin +.Sh NAME +.Nm unwinddump +.Nd "Displays compact unwind information in an executable" +.Sh SYNOPSIS +.Nm +.Op Fl arch Ar arch-name +.Ar file(s) +.Sh DESCRIPTION +When a C++ (or x86_64 Objective-C) exception is thrown, the runtime must unwind +the stack looking for some function to catch the exception. Traditionally, +the unwind information is stored in the __TEXT/__eh_frame section of each executable +as Dwarf CFI (call frame information). Beginning in Mac OS X 10.6, the unwind +information is also encoded in the __TEXT/__unwind_info section using a two-level +lookup table of compact unwind encodings. +.Pp +The unwinddump tool displays the content of the __TEXT/__unwind_info section. +.Sh SEE ALSO +.Xr ld 1 +.Xr dwarfdump 1 diff --git a/ld64.xcodeproj/project.pbxproj b/ld64.xcodeproj/project.pbxproj old mode 100755 new mode 100644 index b5ec62a..fd0213c --- a/ld64.xcodeproj/project.pbxproj +++ b/ld64.xcodeproj/project.pbxproj @@ -18,6 +18,7 @@ F96D536C094A275F008E9EE8 /* PBXTargetDependency */, F96904890A4333AC00B77D2A /* PBXTargetDependency */, F9EA73970974999B008B4F1D /* PBXTargetDependency */, + F9B693890EC4D28C00076912 /* PBXTargetDependency */, ); name = "unit-tests"; productName = "unit-tests"; @@ -30,6 +31,9 @@ dependencies = ( F9B1A2690A3A568200DA8FAB /* PBXTargetDependency */, F9B1A26B0A3A568400DA8FAB /* PBXTargetDependency */, + F9C12EEA0ED65765005BC69D /* PBXTargetDependency */, + F9B8135D0EC2620E00F94C13 /* PBXTargetDependency */, + F9A3DE160ED76D9A00C590B9 /* PBXTargetDependency */, ); name = all; productName = all; @@ -39,14 +43,19 @@ /* Begin PBXBuildFile section */ F9023C4E06D5A272001BBF46 /* ld.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9023C3F06D5A254001BBF46 /* ld.cpp */; }; F933E3D9092E855B0083EAC8 /* ObjectDump.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F971EED706D5AD240041D381 /* ObjectDump.cpp */; }; - F97F5029070D0BB200B9FCD7 /* ld.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = F97F5028070D0BB200B9FCD7 /* ld.1 */; }; - F9B1A2640A3A563E00DA8FAB /* rebase.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = F9B1A2580A3A448800DA8FAB /* rebase.1 */; }; + F97F5029070D0BB200B9FCD7 /* ld.1 in copy man page */ = {isa = PBXBuildFile; fileRef = F97F5028070D0BB200B9FCD7 /* ld.1 */; }; + F9A3DDD30ED762E400C590B9 /* PruneTrie.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9A3DDD20ED762E400C590B9 /* PruneTrie.cpp */; }; + F9A3DE1E0ED7738300C590B9 /* prune_trie.h in CopyFiles */ = {isa = PBXBuildFile; fileRef = F9A3DE0F0ED76D1900C590B9 /* prune_trie.h */; }; + F9B1A2640A3A563E00DA8FAB /* rebase.1 in install man page */ = {isa = PBXBuildFile; fileRef = F9B1A2580A3A448800DA8FAB /* rebase.1 */; }; + F9B670120DDA17E800E6D0DA /* UnwindDump.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9B670110DDA17E800E6D0DA /* UnwindDump.cpp */; }; + F9B813850EC2657800F94C13 /* unwinddump.1 in install man page */ = {isa = PBXBuildFile; fileRef = F9B813810EC2653000F94C13 /* unwinddump.1 */; }; + F9BA51650ECE58C800D1D62E /* dyldinfo.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9BA515B0ECE58AA00D1D62E /* dyldinfo.cpp */; }; F9C0D4BD06DD28D2001C7193 /* Options.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9C0D48A06DD1E1B001C7193 /* Options.cpp */; }; + F9C12EA30ED63DE7005BC69D /* dyldinfo.1 in install man page */ = {isa = PBXBuildFile; fileRef = F9C12E9F0ED63DB1005BC69D /* dyldinfo.1 */; }; F9EA72D5097454FF008B4F1D /* machochecker.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9EA72D4097454FF008B4F1D /* machochecker.cpp */; }; F9EA7584097882F3008B4F1D /* debugline.c in Sources */ = {isa = PBXBuildFile; fileRef = F9EA7582097882F3008B4F1D /* debugline.c */; }; F9EA75BC09788857008B4F1D /* debugline.c in Sources */ = {isa = PBXBuildFile; fileRef = F9EA7582097882F3008B4F1D /* debugline.c */; }; F9EC78060A2F8674002A3E39 /* rebase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = F9EC78050A2F8674002A3E39 /* rebase.cpp */; }; - F9FCC3F20A54A75600CEB866 /* ld64.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = F9FCC3F10A54A75600CEB866 /* ld64.1 */; }; /* End PBXBuildFile section */ /* Begin PBXBuildRule section */ @@ -90,6 +99,13 @@ remoteGlobalIDString = F971EED206D5ACF60041D381; remoteInfo = ObjectDump; }; + F9A3DE150ED76D9A00C590B9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = F9023C3006D5A227001BBF46 /* Project object */; + proxyType = 1; + remoteGlobalIDString = F9A3DDC90ED762B700C590B9; + remoteInfo = libprunetrie; + }; F9B1A2680A3A568200DA8FAB /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = F9023C3006D5A227001BBF46 /* Project object */; @@ -104,6 +120,27 @@ remoteGlobalIDString = F9EC77ED0A2F85F6002A3E39; remoteInfo = rebase; }; + F9B693880EC4D28C00076912 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = F9023C3006D5A227001BBF46 /* Project object */; + proxyType = 1; + remoteGlobalIDString = F9B670010DDA176100E6D0DA; + remoteInfo = unwinddump; + }; + F9B8135C0EC2620E00F94C13 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = F9023C3006D5A227001BBF46 /* Project object */; + proxyType = 1; + remoteGlobalIDString = F9B670010DDA176100E6D0DA; + remoteInfo = unwinddump; + }; + F9C12EE90ED65765005BC69D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = F9023C3006D5A227001BBF46 /* Project object */; + proxyType = 1; + remoteGlobalIDString = F9BA51600ECE58BE00D1D62E; + remoteInfo = dyldinfo; + }; F9EA73960974999B008B4F1D /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = F9023C3006D5A227001BBF46 /* Project object */; @@ -114,57 +151,99 @@ /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ - F97F5025070D0B6300B9FCD7 /* CopyFiles */ = { + F97F5025070D0B6300B9FCD7 /* copy man page */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 8; dstPath = /usr/share/man/man1; dstSubfolderSpec = 0; files = ( - F97F5029070D0BB200B9FCD7 /* ld.1 in CopyFiles */, - F9FCC3F20A54A75600CEB866 /* ld64.1 in CopyFiles */, + F97F5029070D0BB200B9FCD7 /* ld.1 in copy man page */, ); + name = "copy man page"; runOnlyForDeploymentPostprocessing = 1; }; - F9B1A25E0A3A44CB00DA8FAB /* CopyFiles */ = { + F9A3DE140ED76D7700C590B9 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 8; + dstPath = "/usr/local/include/mach-o"; + dstSubfolderSpec = 0; + files = ( + F9A3DE1E0ED7738300C590B9 /* prune_trie.h in CopyFiles */, + ); + runOnlyForDeploymentPostprocessing = 1; + }; + F9B1A25E0A3A44CB00DA8FAB /* install man page */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 8; dstPath = /usr/share/man/man1; dstSubfolderSpec = 0; files = ( - F9B1A2640A3A563E00DA8FAB /* rebase.1 in CopyFiles */, + F9B1A2640A3A563E00DA8FAB /* rebase.1 in install man page */, + ); + name = "install man page"; + runOnlyForDeploymentPostprocessing = 1; + }; + F9B813870EC2659600F94C13 /* install man page */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 8; + dstPath = usr/share/man/man1; + dstSubfolderSpec = 0; + files = ( + F9B813850EC2657800F94C13 /* unwinddump.1 in install man page */, ); + name = "install man page"; + runOnlyForDeploymentPostprocessing = 1; + }; + F9C12EA50ED63E05005BC69D /* install man page */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 8; + dstPath = usr/share/man/man1; + dstSubfolderSpec = 0; + files = ( + F9C12EA30ED63DE7005BC69D /* dyldinfo.1 in install man page */, + ); + name = "install man page"; runOnlyForDeploymentPostprocessing = 1; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 3DA587190ACC53BE0015C432 /* LTOReader.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = LTOReader.hpp; path = src/LTOReader.hpp; sourceTree = ""; }; + 3DA587190ACC53BE0015C432 /* LTOReader.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = LTOReader.hpp; path = src/ld/LTOReader.hpp; sourceTree = ""; }; C02A29DE0953B26E001FB8C1 /* ChangeLog */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; path = ChangeLog; sourceTree = ""; }; F9023C3906D5A23E001BBF46 /* ld */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = ld; sourceTree = BUILT_PRODUCTS_DIR; }; - F9023C3E06D5A254001BBF46 /* ExecutableFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ExecutableFile.h; path = src/ExecutableFile.h; sourceTree = ""; }; - F9023C3F06D5A254001BBF46 /* ld.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ld.cpp; path = src/ld.cpp; sourceTree = ""; }; - F9023C4106D5A254001BBF46 /* ObjectFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ObjectFile.h; path = src/ObjectFile.h; sourceTree = ""; }; - F933D9460929277C0083EAC8 /* FileAbstraction.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = FileAbstraction.hpp; path = src/FileAbstraction.hpp; sourceTree = ""; }; - F933D9470929277C0083EAC8 /* MachOFileAbstraction.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOFileAbstraction.hpp; path = src/MachOFileAbstraction.hpp; sourceTree = ""; }; - F933DC37092A82480083EAC8 /* Architectures.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = Architectures.hpp; path = src/Architectures.hpp; sourceTree = ""; }; - F933E3CC092E84250083EAC8 /* MachOReaderDylib.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOReaderDylib.hpp; path = src/MachOReaderDylib.hpp; sourceTree = ""; }; - F933E3CD092E84250083EAC8 /* MachOReaderRelocatable.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOReaderRelocatable.hpp; path = src/MachOReaderRelocatable.hpp; sourceTree = ""; }; - F933E3CE092E84250083EAC8 /* MachOWriterExecutable.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOWriterExecutable.hpp; path = src/MachOWriterExecutable.hpp; sourceTree = ""; }; + F9023C3E06D5A254001BBF46 /* ExecutableFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ExecutableFile.h; path = src/ld/ExecutableFile.h; sourceTree = ""; }; + F9023C3F06D5A254001BBF46 /* ld.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ld.cpp; path = src/ld/ld.cpp; sourceTree = ""; }; + F9023C4106D5A254001BBF46 /* ObjectFile.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = ObjectFile.h; path = src/ld/ObjectFile.h; sourceTree = ""; }; + F933D9460929277C0083EAC8 /* FileAbstraction.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = FileAbstraction.hpp; path = src/abstraction/FileAbstraction.hpp; sourceTree = ""; }; + F933D9470929277C0083EAC8 /* MachOFileAbstraction.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOFileAbstraction.hpp; path = src/abstraction/MachOFileAbstraction.hpp; sourceTree = ""; }; + F933DC37092A82480083EAC8 /* Architectures.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = Architectures.hpp; path = src/ld/Architectures.hpp; sourceTree = ""; }; + F933E3CC092E84250083EAC8 /* MachOReaderDylib.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOReaderDylib.hpp; path = src/ld/MachOReaderDylib.hpp; sourceTree = ""; }; + F933E3CD092E84250083EAC8 /* MachOReaderRelocatable.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOReaderRelocatable.hpp; path = src/ld/MachOReaderRelocatable.hpp; sourceTree = ""; }; + F933E3CE092E84250083EAC8 /* MachOWriterExecutable.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = MachOWriterExecutable.hpp; path = src/ld/MachOWriterExecutable.hpp; sourceTree = ""; }; F971EED306D5ACF60041D381 /* ObjectDump */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = ObjectDump; sourceTree = BUILT_PRODUCTS_DIR; }; - F971EED706D5AD240041D381 /* ObjectDump.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ObjectDump.cpp; path = src/ObjectDump.cpp; sourceTree = ""; }; + F971EED706D5AD240041D381 /* ObjectDump.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = ObjectDump.cpp; path = src/other/ObjectDump.cpp; sourceTree = ""; }; F97F5028070D0BB200B9FCD7 /* ld.1 */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.man; name = ld.1; path = doc/man/man1/ld.1; sourceTree = ""; }; - F98D26850AA779BD00416316 /* OpaqueSection.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = OpaqueSection.hpp; path = src/OpaqueSection.hpp; sourceTree = ""; }; - F99F63CE0D99A291007F5394 /* ArchiveReader.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ArchiveReader.hpp; path = src/ArchiveReader.hpp; sourceTree = SOURCE_ROOT; }; + F98D26850AA779BD00416316 /* OpaqueSection.hpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.h; name = OpaqueSection.hpp; path = src/ld/OpaqueSection.hpp; sourceTree = ""; }; + F99F63CE0D99A291007F5394 /* ArchiveReader.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = ArchiveReader.hpp; path = src/ld/ArchiveReader.hpp; sourceTree = ""; }; + F9A3DDCA0ED762B700C590B9 /* libprunetrie.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libprunetrie.a; sourceTree = BUILT_PRODUCTS_DIR; }; + F9A3DDD20ED762E400C590B9 /* PruneTrie.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = PruneTrie.cpp; path = src/other/PruneTrie.cpp; sourceTree = ""; }; + F9A3DE0F0ED76D1900C590B9 /* prune_trie.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = prune_trie.h; path = src/other/prune_trie.h; sourceTree = ""; }; F9B1A2580A3A448800DA8FAB /* rebase.1 */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.man; name = rebase.1; path = doc/man/man1/rebase.1; sourceTree = ""; }; - F9C0D48A06DD1E1B001C7193 /* Options.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Options.cpp; path = src/Options.cpp; sourceTree = ""; }; - F9C0D48B06DD1E1B001C7193 /* Options.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = Options.h; path = src/Options.h; sourceTree = ""; }; + F9B670080DDA176100E6D0DA /* unwinddump */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = unwinddump; sourceTree = BUILT_PRODUCTS_DIR; }; + F9B670110DDA17E800E6D0DA /* UnwindDump.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = UnwindDump.cpp; path = src/other/unwinddump.cpp; sourceTree = ""; }; + F9B813810EC2653000F94C13 /* unwinddump.1 */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.man; name = unwinddump.1; path = doc/man/man1/unwinddump.1; sourceTree = ""; }; + F9B813BF0EC27C6700F94C13 /* MachOTrie.hpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.h; name = MachOTrie.hpp; path = src/abstraction/MachOTrie.hpp; sourceTree = ""; }; + F9BA515B0ECE58AA00D1D62E /* dyldinfo.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = dyldinfo.cpp; path = src/other/dyldinfo.cpp; sourceTree = ""; }; + F9BA51610ECE58BE00D1D62E /* dyldinfo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = dyldinfo; sourceTree = BUILT_PRODUCTS_DIR; }; + F9C0D48A06DD1E1B001C7193 /* Options.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = Options.cpp; path = src/ld/Options.cpp; sourceTree = ""; }; + F9C0D48B06DD1E1B001C7193 /* Options.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = Options.h; path = src/ld/Options.h; sourceTree = ""; }; + F9C12E9F0ED63DB1005BC69D /* dyldinfo.1 */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.man; name = dyldinfo.1; path = doc/man/man1/dyldinfo.1; sourceTree = ""; }; F9EA72CB097454A6008B4F1D /* machocheck */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = machocheck; sourceTree = BUILT_PRODUCTS_DIR; }; - F9EA72D4097454FF008B4F1D /* machochecker.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = machochecker.cpp; path = src/machochecker.cpp; sourceTree = ""; }; - F9EA7582097882F3008B4F1D /* debugline.c */ = {isa = PBXFileReference; fileEncoding = 30; indentWidth = 2; lastKnownFileType = sourcecode.c.c; name = debugline.c; path = src/debugline.c; sourceTree = ""; tabWidth = 4; usesTabs = 1; }; - F9EA7583097882F3008B4F1D /* debugline.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = debugline.h; path = src/debugline.h; sourceTree = ""; }; + F9EA72D4097454FF008B4F1D /* machochecker.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = machochecker.cpp; path = src/other/machochecker.cpp; sourceTree = ""; }; + F9EA7582097882F3008B4F1D /* debugline.c */ = {isa = PBXFileReference; fileEncoding = 30; indentWidth = 2; lastKnownFileType = sourcecode.c.c; name = debugline.c; path = src/ld/debugline.c; sourceTree = ""; tabWidth = 8; usesTabs = 1; }; + F9EA7583097882F3008B4F1D /* debugline.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = debugline.h; path = src/ld/debugline.h; sourceTree = ""; }; F9EC77EE0A2F85F6002A3E39 /* rebase */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = rebase; sourceTree = BUILT_PRODUCTS_DIR; }; - F9EC78050A2F8674002A3E39 /* rebase.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = rebase.cpp; path = src/rebase.cpp; sourceTree = ""; }; - F9FCC3F10A54A75600CEB866 /* ld64.1 */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.man; name = ld64.1; path = doc/man/man1/ld64.1; sourceTree = ""; }; + F9EC78050A2F8674002A3E39 /* rebase.cpp */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.cpp.cpp; name = rebase.cpp; path = src/other/rebase.cpp; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -182,6 +261,20 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + F9B670040DDA176100E6D0DA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F9BA515F0ECE58BE00D1D62E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; F9EA72C9097454A6008B4F1D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -203,10 +296,55 @@ isa = PBXGroup; children = ( C02A29DE0953B26E001FB8C1 /* ChangeLog */, - F933DC37092A82480083EAC8 /* Architectures.hpp */, + F9B813A80EC27B6300F94C13 /* abstraction */, + F9B813AD0EC27B8500F94C13 /* ld */, + F9B813B00EC27B9E00F94C13 /* other */, + F9B8137E0EC2651200F94C13 /* doc */, + F9023C3A06D5A23E001BBF46 /* Products */, + ); + sourceTree = ""; + }; + F9023C3A06D5A23E001BBF46 /* Products */ = { + isa = PBXGroup; + children = ( + F9023C3906D5A23E001BBF46 /* ld */, + F971EED306D5ACF60041D381 /* ObjectDump */, + F9EA72CB097454A6008B4F1D /* machocheck */, + F9EC77EE0A2F85F6002A3E39 /* rebase */, + F9B670080DDA176100E6D0DA /* unwinddump */, + F9BA51610ECE58BE00D1D62E /* dyldinfo */, + F9A3DDCA0ED762B700C590B9 /* libprunetrie.a */, + ); + name = Products; + sourceTree = ""; + }; + F9B8137E0EC2651200F94C13 /* doc */ = { + isa = PBXGroup; + children = ( + F97F5028070D0BB200B9FCD7 /* ld.1 */, + F9B1A2580A3A448800DA8FAB /* rebase.1 */, + F9C12E9F0ED63DB1005BC69D /* dyldinfo.1 */, + F9B813810EC2653000F94C13 /* unwinddump.1 */, + ); + name = doc; + sourceTree = ""; + }; + F9B813A80EC27B6300F94C13 /* abstraction */ = { + isa = PBXGroup; + children = ( + F933D9470929277C0083EAC8 /* MachOFileAbstraction.hpp */, F933D9460929277C0083EAC8 /* FileAbstraction.hpp */, + F9B813BF0EC27C6700F94C13 /* MachOTrie.hpp */, + ); + name = abstraction; + sourceTree = ""; + }; + F9B813AD0EC27B8500F94C13 /* ld */ = { + isa = PBXGroup; + children = ( + F9023C3F06D5A254001BBF46 /* ld.cpp */, + F933DC37092A82480083EAC8 /* Architectures.hpp */, F99F63CE0D99A291007F5394 /* ArchiveReader.hpp */, - F933D9470929277C0083EAC8 /* MachOFileAbstraction.hpp */, F933E3CD092E84250083EAC8 /* MachOReaderRelocatable.hpp */, F933E3CC092E84250083EAC8 /* MachOReaderDylib.hpp */, F933E3CE092E84250083EAC8 /* MachOWriterExecutable.hpp */, @@ -214,30 +352,26 @@ F9023C3E06D5A254001BBF46 /* ExecutableFile.h */, F9023C4106D5A254001BBF46 /* ObjectFile.h */, F98D26850AA779BD00416316 /* OpaqueSection.hpp */, - F9023C3F06D5A254001BBF46 /* ld.cpp */, F9C0D48A06DD1E1B001C7193 /* Options.cpp */, F9C0D48B06DD1E1B001C7193 /* Options.h */, - F9EA7583097882F3008B4F1D /* debugline.h */, F9EA7582097882F3008B4F1D /* debugline.c */, - F9EA72D4097454FF008B4F1D /* machochecker.cpp */, - F971EED706D5AD240041D381 /* ObjectDump.cpp */, - F9EC78050A2F8674002A3E39 /* rebase.cpp */, - F97F5028070D0BB200B9FCD7 /* ld.1 */, - F9FCC3F10A54A75600CEB866 /* ld64.1 */, - F9B1A2580A3A448800DA8FAB /* rebase.1 */, - F9023C3A06D5A23E001BBF46 /* Products */, + F9EA7583097882F3008B4F1D /* debugline.h */, ); + name = ld; sourceTree = ""; }; - F9023C3A06D5A23E001BBF46 /* Products */ = { + F9B813B00EC27B9E00F94C13 /* other */ = { isa = PBXGroup; children = ( - F9023C3906D5A23E001BBF46 /* ld */, - F971EED306D5ACF60041D381 /* ObjectDump */, - F9EA72CB097454A6008B4F1D /* machocheck */, - F9EC77EE0A2F85F6002A3E39 /* rebase */, + F9EA72D4097454FF008B4F1D /* machochecker.cpp */, + F971EED706D5AD240041D381 /* ObjectDump.cpp */, + F9BA515B0ECE58AA00D1D62E /* dyldinfo.cpp */, + F9B670110DDA17E800E6D0DA /* UnwindDump.cpp */, + F9EC78050A2F8674002A3E39 /* rebase.cpp */, + F9A3DE0F0ED76D1900C590B9 /* prune_trie.h */, + F9A3DDD20ED762E400C590B9 /* PruneTrie.cpp */, ); - name = Products; + name = other; sourceTree = ""; }; /* End PBXGroup section */ @@ -250,8 +384,7 @@ 0B12F6A50CE39466008ABCAE /* build configure.h */, F9023C3606D5A23E001BBF46 /* Sources */, F9023C3706D5A23E001BBF46 /* Frameworks */, - F97F5025070D0B6300B9FCD7 /* CopyFiles */, - F9FCC3EF0A54A4ED00CEB866 /* Run Script */, + F97F5025070D0B6300B9FCD7 /* copy man page */, ); buildRules = ( F9E8D4BE07FCAF2A00FD5801 /* PBXBuildRule */, @@ -280,6 +413,56 @@ productReference = F971EED306D5ACF60041D381 /* ObjectDump */; productType = "com.apple.product-type.tool"; }; + F9A3DDC90ED762B700C590B9 /* libprunetrie */ = { + isa = PBXNativeTarget; + buildConfigurationList = F9A3DDCF0ED762C100C590B9 /* Build configuration list for PBXNativeTarget "libprunetrie" */; + buildPhases = ( + F9A3DDC70ED762B700C590B9 /* Sources */, + F9A3DE140ED76D7700C590B9 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = libprunetrie; + productName = libmachotrie; + productReference = F9A3DDCA0ED762B700C590B9 /* libprunetrie.a */; + productType = "com.apple.product-type.library.static"; + }; + F9B670010DDA176100E6D0DA /* unwinddump */ = { + isa = PBXNativeTarget; + buildConfigurationList = F9B670050DDA176100E6D0DA /* Build configuration list for PBXNativeTarget "unwinddump" */; + buildPhases = ( + F9B670020DDA176100E6D0DA /* Sources */, + F9B670040DDA176100E6D0DA /* Frameworks */, + F9B813870EC2659600F94C13 /* install man page */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = unwinddump; + productName = machocheck; + productReference = F9B670080DDA176100E6D0DA /* unwinddump */; + productType = "com.apple.product-type.tool"; + }; + F9BA51600ECE58BE00D1D62E /* dyldinfo */ = { + isa = PBXNativeTarget; + buildConfigurationList = F9BA516D0ECE58DA00D1D62E /* Build configuration list for PBXNativeTarget "dyldinfo" */; + buildPhases = ( + F9BA515E0ECE58BE00D1D62E /* Sources */, + F9BA515F0ECE58BE00D1D62E /* Frameworks */, + F9C12EA50ED63E05005BC69D /* install man page */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = dyldinfo; + productName = dyldinfo; + productReference = F9BA51610ECE58BE00D1D62E /* dyldinfo */; + productType = "com.apple.product-type.tool"; + }; F9EA72CA097454A6008B4F1D /* machocheck */ = { isa = PBXNativeTarget; buildConfigurationList = F9EA72CF097454D5008B4F1D /* Build configuration list for PBXNativeTarget "machocheck" */; @@ -302,7 +485,7 @@ buildPhases = ( F9EC77EB0A2F85F6002A3E39 /* Sources */, F9EC77EC0A2F85F6002A3E39 /* Frameworks */, - F9B1A25E0A3A44CB00DA8FAB /* CopyFiles */, + F9B1A25E0A3A44CB00DA8FAB /* install man page */, ); buildRules = ( ); @@ -329,8 +512,11 @@ F9B1A2670A3A567B00DA8FAB /* all */, F9023C3806D5A23E001BBF46 /* ld */, F9EC77ED0A2F85F6002A3E39 /* rebase */, + F9B670010DDA176100E6D0DA /* unwinddump */, F971EED206D5ACF60041D381 /* ObjectDump */, F9EA72CA097454A6008B4F1D /* machocheck */, + F9BA51600ECE58BE00D1D62E /* dyldinfo */, + F9A3DDC90ED762B700C590B9 /* libprunetrie */, F96D5368094A2754008E9EE8 /* unit-tests */, ); }; @@ -350,7 +536,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/bash; - shellScript = "echo \"#undef LTO_SUPPORT\t\" > ${DERIVED_FILE_DIR}/configure.h\n"; + shellScript = "if [ -f /Developer/usr/local/include/llvm-c/lto.h ]; then\n\techo \"#define LTO_SUPPORT 1\" > ${DERIVED_FILE_DIR}/configure.h\n\techo \"-Wl,-lazy_library,/Developer/usr/lib/libLTO.dylib\" > ${DERIVED_FILE_DIR}/linker_opts\nelse\n\techo \"#undef LTO_SUPPORT\" > ${DERIVED_FILE_DIR}/configure.h\n\techo \"\" > ${DERIVED_FILE_DIR}/linker_opts\nfi\n"; showEnvVarsInLog = 0; }; F96D5367094A2754008E9EE8 /* ShellScript */ = { @@ -367,21 +553,6 @@ shellScript = "# Let tests set MACOSX_DEPLOYMENT_TARGET as they need\nunsetenv MACOSX_DEPLOYMENT_TARGET\n\n# always use new linker\nsetenv LD_NO_CLASSIC_LINKER\nsetenv LD_NO_CLASSIC_LINKER_STATIC\n\n# run full test suite\n\"$SRCROOT\"/unit-tests/run-all-unit-tests\n\nexit 0"; showEnvVarsInLog = 0; }; - F9FCC3EF0A54A4ED00CEB866 /* Run Script */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 8; - files = ( - ); - inputPaths = ( - ); - name = "Run Script"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 1; - shellPath = /bin/sh; - shellScript = "cd ${DSTROOT}/usr/bin\nln -s ld ld64"; - showEnvVarsInLog = 0; - }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -404,6 +575,30 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + F9A3DDC70ED762B700C590B9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F9A3DDD30ED762E400C590B9 /* PruneTrie.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F9B670020DDA176100E6D0DA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F9B670120DDA17E800E6D0DA /* UnwindDump.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F9BA515E0ECE58BE00D1D62E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + F9BA51650ECE58C800D1D62E /* dyldinfo.cpp in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; F9EA72C8097454A6008B4F1D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -438,6 +633,11 @@ target = F971EED206D5ACF60041D381 /* ObjectDump */; targetProxy = F96D536B094A275F008E9EE8 /* PBXContainerItemProxy */; }; + F9A3DE160ED76D9A00C590B9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = F9A3DDC90ED762B700C590B9 /* libprunetrie */; + targetProxy = F9A3DE150ED76D9A00C590B9 /* PBXContainerItemProxy */; + }; F9B1A2690A3A568200DA8FAB /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = F9023C3806D5A23E001BBF46 /* ld */; @@ -448,6 +648,21 @@ target = F9EC77ED0A2F85F6002A3E39 /* rebase */; targetProxy = F9B1A26A0A3A568400DA8FAB /* PBXContainerItemProxy */; }; + F9B693890EC4D28C00076912 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = F9B670010DDA176100E6D0DA /* unwinddump */; + targetProxy = F9B693880EC4D28C00076912 /* PBXContainerItemProxy */; + }; + F9B8135D0EC2620E00F94C13 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = F9B670010DDA176100E6D0DA /* unwinddump */; + targetProxy = F9B8135C0EC2620E00F94C13 /* PBXContainerItemProxy */; + }; + F9C12EEA0ED65765005BC69D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = F9BA51600ECE58BE00D1D62E /* dyldinfo */; + targetProxy = F9C12EE90ED65765005BC69D /* PBXContainerItemProxy */; + }; F9EA73970974999B008B4F1D /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = F9EA72CA097454A6008B4F1D /* machocheck */; @@ -496,9 +711,10 @@ "$(DEVELOPER_DIR)/usr/include", ); INSTALL_PATH = /usr/bin; + LINKER_DISPLAYS_MANGLED_NAMES = NO; MACOSX_DEPLOYMENT_TARGET = ""; OTHER_CPLUSPLUSFLAGS = "$(OTHER_CPLUSPLUSFLAGS)"; - OTHER_LDFLAGS = ""; + OTHER_LDFLAGS = "@$(DERIVED_FILE_DIR)/linker_opts"; PREBINDING = NO; PRODUCT_NAME = ld; SECTORDER_FLAGS = ""; @@ -510,7 +726,8 @@ F933D91D09291AC90083EAC8 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - COPY_PHASE_STRIP = YES; + ARCHS = x86_64; + COPY_PHASE_STRIP = NO; CURRENT_PROJECT_VERSION = "$(RC_ProjectSourceVersion)"; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_DYNAMIC_NO_PIC = YES; @@ -548,10 +765,16 @@ ); INSTALL_PATH = /usr/bin; OTHER_CPLUSPLUSFLAGS = "$(OTHER_CPLUSPLUSFLAGS)"; + OTHER_LDFLAGS = ( + "@$(DERIVED_FILE_DIR)/linker_opts", + "-Wl,-exported_symbol,__mh_execute_header", + ); PREBINDING = NO; PRODUCT_NAME = ld; SECTORDER_FLAGS = ""; - VALID_ARCHS = "i386 ppc"; + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = debugging; + VALID_ARCHS = "x86_64 i386 ppc"; VERSIONING_SYSTEM = "apple-generic"; WARNING_CFLAGS = "-Wall"; }; @@ -565,7 +788,7 @@ GCC_GENERATE_DEBUGGING_SYMBOLS = YES; GCC_MODEL_TUNING = G5; GCC_OPTIMIZATION_LEVEL = 0; - HEADER_SEARCH_PATHS = "$(DEVELOPER_DIR)/usr/include"; + HEADER_SEARCH_PATHS = "$(DEVELOPER_DIR)/usr/local/include"; INSTALL_PATH = "$(HOME)/bin"; OTHER_LDFLAGS = "-Wl,-lazy_library,/Developer/usr/lib/libLTO.dylib"; OTHER_REZFLAGS = ""; @@ -588,6 +811,7 @@ GCC_GENERATE_DEBUGGING_SYMBOLS = YES; GCC_MODEL_TUNING = G5; GCC_OPTIMIZATION_LEVEL = s; + HEADER_SEARCH_PATHS = "$(DEVELOPER_DIR)/usr/local/include"; INSTALL_PATH = "$(HOME)/bin"; OTHER_LDFLAGS = "-Wl,-lazy_library,/Developer/usr/lib/libLTO.dylib"; OTHER_REZFLAGS = ""; @@ -614,7 +838,6 @@ buildSettings = { GCC_DYNAMIC_NO_PIC = NO; GCC_TREAT_WARNINGS_AS_ERRORS = NO; - HEADER_SEARCH_PATHS = "$(DEVELOPER_DIR)/SDKs/Extra/usr/include"; }; name = Release; }; @@ -636,6 +859,37 @@ }; name = Release; }; + F9A3DDCB0ED762B800C590B9 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; + INSTALL_PATH = /usr/local/lib; + PREBINDING = NO; + PRODUCT_NAME = prunetrie; + }; + name = Debug; + }; + F9A3DDCC0ED762B800C590B9 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + GCC_ENABLE_FIX_AND_CONTINUE = NO; + GCC_MODEL_TUNING = G5; + GCC_SYMBOLS_PRIVATE_EXTERN = YES; + INSTALL_PATH = /usr/local/lib; + PREBINDING = NO; + PRODUCT_NAME = prunetrie; + }; + name = Release; + }; F9B1A26D0A3A568700DA8FAB /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -658,6 +912,72 @@ }; name = Release; }; + F9B670060DDA176100E6D0DA /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; + INSTALL_PATH = "$(HOME)/bin"; + PREBINDING = NO; + PRODUCT_NAME = unwinddump; + }; + name = Debug; + }; + F9B670070DDA176100E6D0DA /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_MODEL_TUNING = G5; + GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES; + HEADER_SEARCH_PATHS = ""; + INSTALL_PATH = /usr/bin; + OTHER_LDFLAGS = "-Wl,-exported_symbol,__mh_execute_header"; + PREBINDING = NO; + PRODUCT_NAME = unwinddump; + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = debugging; + }; + name = Release; + }; + F9BA51630ECE58BF00D1D62E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + GCC_OPTIMIZATION_LEVEL = 0; + INSTALL_PATH = /usr/local/bin; + PREBINDING = NO; + PRODUCT_NAME = dyldinfo; + }; + name = Debug; + }; + F9BA51640ECE58BF00D1D62E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_ENABLE_FIX_AND_CONTINUE = NO; + GCC_MODEL_TUNING = G5; + INSTALL_PATH = /usr/bin; + OTHER_LDFLAGS = "-Wl,-exported_symbol,__mh_execute_header"; + PREBINDING = NO; + PRODUCT_NAME = dyldinfo; + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = debugging; + ZERO_LINK = NO; + }; + name = Release; + }; F9EA72D0097454D5008B4F1D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -679,6 +999,7 @@ DEBUG_INFORMATION_FORMAT = dwarf; GCC_GENERATE_DEBUGGING_SYMBOLS = YES; GCC_MODEL_TUNING = G5; + HEADER_SEARCH_PATHS = ""; INSTALL_PATH = "$(HOME)/bin"; PREBINDING = NO; PRODUCT_NAME = machocheck; @@ -703,15 +1024,19 @@ F9EC77F20A2F8616002A3E39 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - COPY_PHASE_STRIP = YES; + COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; GCC_GENERATE_DEBUGGING_SYMBOLS = YES; GCC_MODEL_TUNING = G5; GCC_PREPROCESSOR_DEFINITIONS = "$(GCC_PREPROCESSOR_DEFINITIONS_$(RC_RELEASE))"; + HEADER_SEARCH_PATHS = ""; INSTALL_PATH = /usr/bin; + OTHER_LDFLAGS = "-Wl,-exported_symbol,__mh_execute_header"; PREBINDING = NO; PRODUCT_NAME = rebase; - VALID_ARCHS = "i386 ppc"; + STRIP_INSTALLED_PRODUCT = YES; + STRIP_STYLE = debugging; + VALID_ARCHS = "i386 ppc x86_64"; }; name = Release; }; @@ -754,6 +1079,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + F9A3DDCF0ED762C100C590B9 /* Build configuration list for PBXNativeTarget "libprunetrie" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F9A3DDCB0ED762B800C590B9 /* Debug */, + F9A3DDCC0ED762B800C590B9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; F9B1A26C0A3A568700DA8FAB /* Build configuration list for PBXAggregateTarget "all" */ = { isa = XCConfigurationList; buildConfigurations = ( @@ -763,6 +1097,24 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + F9B670050DDA176100E6D0DA /* Build configuration list for PBXNativeTarget "unwinddump" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F9B670060DDA176100E6D0DA /* Debug */, + F9B670070DDA176100E6D0DA /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F9BA516D0ECE58DA00D1D62E /* Build configuration list for PBXNativeTarget "dyldinfo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F9BA51630ECE58BF00D1D62E /* Debug */, + F9BA51640ECE58BF00D1D62E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; F9EA72CF097454D5008B4F1D /* Build configuration list for PBXNativeTarget "machocheck" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/src/FileAbstraction.hpp b/src/abstraction/FileAbstraction.hpp old mode 100755 new mode 100644 similarity index 100% rename from src/FileAbstraction.hpp rename to src/abstraction/FileAbstraction.hpp diff --git a/src/MachOFileAbstraction.hpp b/src/abstraction/MachOFileAbstraction.hpp old mode 100755 new mode 100644 similarity index 76% rename from src/MachOFileAbstraction.hpp rename to src/abstraction/MachOFileAbstraction.hpp index 83a8ee1..330a8cb --- a/src/MachOFileAbstraction.hpp +++ b/src/abstraction/MachOFileAbstraction.hpp @@ -32,18 +32,14 @@ #include #include #include +#include +#include #include #include "FileAbstraction.hpp" -#include "Architectures.hpp" + // stuff that will eventually go away once newer cctools headers are widespread -#ifndef LC_LAZY_LOAD_DYLIB - #define LC_LAZY_LOAD_DYLIB 0x20 -#endif -#ifndef S_LAZY_DYLIB_SYMBOL_POINTERS - #define S_LAZY_DYLIB_SYMBOL_POINTERS 0x10 -#endif #ifndef CPU_SUBTYPE_ARM_V5TEJ #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7) #endif @@ -53,32 +49,88 @@ #ifndef CPU_SUBTYPE_ARM_V7 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9) #endif +#ifndef ARM_THUMB_32BIT_BRANCH + #define ARM_THUMB_32BIT_BRANCH 7 +#endif #ifndef N_ARM_THUMB_DEF #define N_ARM_THUMB_DEF 0x0008 #endif -enum reloc_type_arm -{ - ARM_RELOC_VANILLA, /* generic relocation as discribed above */ - ARM_RELOC_PAIR, /* the second relocation entry of a pair */ - ARM_RELOC_SECTDIFF, /* a PAIR follows with subtract symbol value */ - ARM_RELOC_LOCAL_SECTDIFF, /* like ARM_RELOC_SECTDIFF, but the symbol - referenced was local. */ - ARM_RELOC_PB_LA_PTR,/* prebound lazy pointer */ - ARM_RELOC_BR24, /* 24 bit branch displacement (to a word address) */ - ARM_THUMB_RELOC_BR22, /* 22 bit branch displacement (to a half-word - address) */ -}; - -#ifndef LC_ENCRYPTION_INFO - #define LC_ENCRYPTION_INFO 0x21 - struct encryption_info_command { - uint32_t cmd; - uint32_t cmdsize; - uint32_t cryptoff; /* file offset of encrypted range */ - uint32_t cryptsize; /* file size of encrypted range */ - uint32_t cryptid; /* which enryption system, 0 means not-encrypted yet */ - }; +#ifndef MH_DEAD_STRIPPABLE_DYLIB + #define MH_DEAD_STRIPPABLE_DYLIB 0x400000 +#endif +#ifndef MH_KEXT_BUNDLE + #define MH_KEXT_BUNDLE 11 #endif +#ifndef LC_DYLD_INFO + #define LC_DYLD_INFO 0x22 /* compressed dyld information */ + #define LC_DYLD_INFO_ONLY (0x22|LC_REQ_DYLD) /* compressed dyld information only */ + + struct dyld_info_command { + uint32_t cmd; /* LC_DYLD_INFO or LC_DYLD_INFO_ONLY */ + uint32_t cmdsize; /* sizeof(struct dyld_info_command) */ + uint32_t rebase_off; /* file offset to rebase info */ + uint32_t rebase_size; /* size of rebase info */ + uint32_t bind_off; /* file offset to binding info */ + uint32_t bind_size; /* size of binding info */ + uint32_t weak_bind_off; /* file offset to weak binding info */ + uint32_t weak_bind_size; /* size of weak binding info */ + uint32_t lazy_bind_off; /* file offset to lazy binding info */ + uint32_t lazy_bind_size; /* size of lazy binding infs */ + uint32_t export_off; /* file offset to lazy binding info */ + uint32_t export_size; /* size of lazy binding infs */ + }; + + #define REBASE_TYPE_POINTER 1 + #define REBASE_TYPE_TEXT_ABSOLUTE32 2 + #define REBASE_TYPE_TEXT_PCREL32 3 + + #define REBASE_OPCODE_MASK 0xF0 + #define REBASE_IMMEDIATE_MASK 0x0F + #define REBASE_OPCODE_DONE 0x00 + #define REBASE_OPCODE_SET_TYPE_IMM 0x10 + #define REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x20 + #define REBASE_OPCODE_ADD_ADDR_ULEB 0x30 + #define REBASE_OPCODE_ADD_ADDR_IMM_SCALED 0x40 + #define REBASE_OPCODE_DO_REBASE_IMM_TIMES 0x50 + #define REBASE_OPCODE_DO_REBASE_ULEB_TIMES 0x60 + #define REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB 0x70 + #define REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB 0x80 + + #define BIND_TYPE_POINTER 1 + #define BIND_TYPE_TEXT_ABSOLUTE32 2 + #define BIND_TYPE_TEXT_PCREL32 3 + + #define BIND_SPECIAL_DYLIB_SELF 0 + #define BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE -1 + #define BIND_SPECIAL_DYLIB_FLAT_LOOKUP -2 + + #define BIND_SYMBOL_FLAGS_WEAK_IMPORT 0x1 + #define BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION 0x8 + + #define BIND_OPCODE_MASK 0xF0 + #define BIND_IMMEDIATE_MASK 0x0F + #define BIND_OPCODE_DONE 0x00 + #define BIND_OPCODE_SET_DYLIB_ORDINAL_IMM 0x10 + #define BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB 0x20 + #define BIND_OPCODE_SET_DYLIB_SPECIAL_IMM 0x30 + #define BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM 0x40 + #define BIND_OPCODE_SET_TYPE_IMM 0x50 + #define BIND_OPCODE_SET_ADDEND_SLEB 0x60 + #define BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB 0x70 + #define BIND_OPCODE_ADD_ADDR_ULEB 0x80 + #define BIND_OPCODE_DO_BIND 0x90 + #define BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB 0xA0 + #define BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED 0xB0 + #define BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB 0xC0 + + #define EXPORT_SYMBOL_FLAGS_KIND_MASK 0x03 + #define EXPORT_SYMBOL_FLAGS_KIND_REGULAR 0x00 + #define EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL 0x01 + #define EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION 0x04 + #define EXPORT_SYMBOL_FLAGS_INDIRECT_DEFINITION 0x08 + #define EXPORT_SYMBOL_FLAGS_HAS_SPECIALIZATIONS 0x10 + +#endif // @@ -919,6 +971,195 @@ private: }; +// +// start of __unwind_info section +// +template +class macho_unwind_info_section_header { +public: + uint32_t version() const INLINE { return E::get32(fields.version); } + void set_version(uint32_t value) INLINE { E::set32(fields.version, value); } + + uint32_t commonEncodingsArraySectionOffset() const INLINE { return E::get32(fields.commonEncodingsArraySectionOffset); } + void set_commonEncodingsArraySectionOffset(uint32_t value) INLINE { E::set32(fields.commonEncodingsArraySectionOffset, value); } + + uint32_t commonEncodingsArrayCount() const INLINE { return E::get32(fields.commonEncodingsArrayCount); } + void set_commonEncodingsArrayCount(uint32_t value) INLINE { E::set32(fields.commonEncodingsArrayCount, value); } + + uint32_t personalityArraySectionOffset() const INLINE { return E::get32(fields.personalityArraySectionOffset); } + void set_personalityArraySectionOffset(uint32_t value) INLINE { E::set32(fields.personalityArraySectionOffset, value); } + + uint32_t personalityArrayCount() const INLINE { return E::get32(fields.personalityArrayCount); } + void set_personalityArrayCount(uint32_t value) INLINE { E::set32(fields.personalityArrayCount, value); } + + uint32_t indexSectionOffset() const INLINE { return E::get32(fields.indexSectionOffset); } + void set_indexSectionOffset(uint32_t value) INLINE { E::set32(fields.indexSectionOffset, value); } + + uint32_t indexCount() const INLINE { return E::get32(fields.indexCount); } + void set_indexCount(uint32_t value) INLINE { E::set32(fields.indexCount, value); } + + typedef typename P::E E; +private: + unwind_info_section_header fields; +}; + + + +// +// uwind first level index entry +// +template +class macho_unwind_info_section_header_index_entry { +public: + uint32_t functionOffset() const INLINE { return E::get32(fields.functionOffset); } + void set_functionOffset(uint32_t value) INLINE { E::set32(fields.functionOffset, value); } + + uint32_t secondLevelPagesSectionOffset() const INLINE { return E::get32(fields.secondLevelPagesSectionOffset); } + void set_secondLevelPagesSectionOffset(uint32_t value) INLINE { E::set32(fields.secondLevelPagesSectionOffset, value); } + + uint32_t lsdaIndexArraySectionOffset() const INLINE { return E::get32(fields.lsdaIndexArraySectionOffset); } + void set_lsdaIndexArraySectionOffset(uint32_t value) INLINE { E::set32(fields.lsdaIndexArraySectionOffset, value); } + + typedef typename P::E E; +private: + unwind_info_section_header_index_entry fields; +}; + + +// +// LSDA table entry +// +template +class macho_unwind_info_section_header_lsda_index_entry { +public: + uint32_t functionOffset() const INLINE { return E::get32(fields.functionOffset); } + void set_functionOffset(uint32_t value) INLINE { E::set32(fields.functionOffset, value); } + + uint32_t lsdaOffset() const INLINE { return E::get32(fields.lsdaOffset); } + void set_lsdaOffset(uint32_t value) INLINE { E::set32(fields.lsdaOffset, value); } + + typedef typename P::E E; +private: + unwind_info_section_header_lsda_index_entry fields; +}; + + +// +// regular second level entry +// +template +class macho_unwind_info_regular_second_level_entry { +public: + uint32_t functionOffset() const INLINE { return E::get32(fields.functionOffset); } + void set_functionOffset(uint32_t value) INLINE { E::set32(fields.functionOffset, value); } + + uint32_t encoding() const INLINE { return E::get32(fields.encoding); } + void set_encoding(uint32_t value) INLINE { E::set32(fields.encoding, value); } + + typedef typename P::E E; +private: + unwind_info_regular_second_level_entry fields; +}; + + +// +// start of second level regular page +// +template +class macho_unwind_info_regular_second_level_page_header { +public: + uint32_t kind() const INLINE { return E::get32(fields.kind); } + void set_kind(uint32_t value) INLINE { E::set32(fields.kind, value); } + + uint16_t entryPageOffset() const INLINE { return E::get16(fields.entryPageOffset); } + void set_entryPageOffset(uint16_t value) INLINE { E::set16((uint16_t&)fields.entryPageOffset, value); } + + uint16_t entryCount() const INLINE { return E::get16(fields.entryCount); } + void set_entryCount(uint16_t value) INLINE { E::set16((uint16_t&)fields.entryCount, value); } + + typedef typename P::E E; +private: + unwind_info_regular_second_level_page_header fields; +}; + + +// +// start of second level compressed page +// +template +class macho_unwind_info_compressed_second_level_page_header { +public: + uint32_t kind() const INLINE { return E::get32(fields.kind); } + void set_kind(uint32_t value) INLINE { E::set32(fields.kind, value); } + + uint16_t entryPageOffset() const INLINE { return E::get16(fields.entryPageOffset); } + void set_entryPageOffset(uint16_t value) INLINE { E::set16((uint16_t&)fields.entryPageOffset, value); } + + uint16_t entryCount() const INLINE { return E::get16(fields.entryCount); } + void set_entryCount(uint16_t value) INLINE { E::set16((uint16_t&)fields.entryCount, value); } + + uint16_t encodingsPageOffset() const INLINE { return E::get16(fields.encodingsPageOffset); } + void set_encodingsPageOffset(uint16_t value) INLINE { E::set16((uint16_t&)fields.encodingsPageOffset, value); } + + uint16_t encodingsCount() const INLINE { return E::get16(fields.encodingsCount); } + void set_encodingsCount(uint16_t value) INLINE { E::set16((uint16_t&)fields.encodingsCount, value); } + + typedef typename P::E E; +private: + unwind_info_compressed_second_level_page_header fields; +}; + + +// +// compressed dyld info load command +// +template +class macho_dyld_info_command { +public: + uint32_t cmd() const INLINE { return E::get32(fields.cmd); } + void set_cmd(uint32_t value) INLINE { E::set32(fields.cmd, value); } + + uint32_t cmdsize() const INLINE { return E::get32(fields.cmdsize); } + void set_cmdsize(uint32_t value) INLINE { E::set32(fields.cmdsize, value); } + + uint32_t rebase_off() const INLINE { return E::get32(fields.rebase_off); } + void set_rebase_off(uint32_t value) INLINE { E::set32(fields.rebase_off, value); } + + uint32_t rebase_size() const INLINE { return E::get32(fields.rebase_size); } + void set_rebase_size(uint32_t value) INLINE { E::set32(fields.rebase_size, value); } + + uint32_t bind_off() const INLINE { return E::get32(fields.bind_off); } + void set_bind_off(uint32_t value) INLINE { E::set32(fields.bind_off, value); } + + uint32_t bind_size() const INLINE { return E::get32(fields.bind_size); } + void set_bind_size(uint32_t value) INLINE { E::set32(fields.bind_size, value); } + + uint32_t weak_bind_off() const INLINE { return E::get32(fields.weak_bind_off); } + void set_weak_bind_off(uint32_t value) INLINE { E::set32(fields.weak_bind_off, value); } + + uint32_t weak_bind_size() const INLINE { return E::get32(fields.weak_bind_size); } + void set_weak_bind_size(uint32_t value) INLINE { E::set32(fields.weak_bind_size, value); } + + uint32_t lazy_bind_off() const INLINE { return E::get32(fields.lazy_bind_off); } + void set_lazy_bind_off(uint32_t value) INLINE { E::set32(fields.lazy_bind_off, value); } + + uint32_t lazy_bind_size() const INLINE { return E::get32(fields.lazy_bind_size); } + void set_lazy_bind_size(uint32_t value) INLINE { E::set32(fields.lazy_bind_size, value); } + + uint32_t export_off() const INLINE { return E::get32(fields.export_off); } + void set_export_off(uint32_t value) INLINE { E::set32(fields.export_off, value); } + + uint32_t export_size() const INLINE { return E::get32(fields.export_size); } + void set_export_size(uint32_t value) INLINE { E::set32(fields.export_size, value); } + + + typedef typename P::E E; +private: + dyld_info_command fields; +}; + + + #endif // __MACH_O_FILE_ABSTRACTION__ diff --git a/src/abstraction/MachOTrie.hpp b/src/abstraction/MachOTrie.hpp new file mode 100644 index 0000000..43284c4 --- /dev/null +++ b/src/abstraction/MachOTrie.hpp @@ -0,0 +1,320 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ +*/ +#ifndef __MACH_O_TRIE__ +#define __MACH_O_TRIE__ + +#include + +#include "MachOFileAbstraction.hpp" + +namespace mach_o { +namespace trie { + +struct Edge +{ + Edge(const char* s, struct Node* n) : fSubString(s), fChild(n) { } + ~Edge() { } + const char* fSubString; + struct Node* fChild; + +}; + +struct Node +{ + Node(const char* s) : fCummulativeString(s), fAddress(0), fFlags(0), fOrdered(false), + fHaveExportInfo(false), fTrieOffset(0) {} + ~Node() { } + const char* fCummulativeString; + std::vector fChildren; + uint64_t fAddress; + uint32_t fFlags; + bool fOrdered; + bool fHaveExportInfo; + uint32_t fTrieOffset; + + void addSymbol(const char* fullStr, uint64_t address, uint32_t flags) { + const char* partialStr = &fullStr[strlen(fCummulativeString)]; + for (std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + Edge& e = *it; + int subStringLen = strlen(e.fSubString); + if ( strncmp(e.fSubString, partialStr, subStringLen) == 0 ) { + // already have matching edge, go down that path + e.fChild->addSymbol(fullStr, address, flags); + return; + } + else { + for (int i=subStringLen-1; i > 0; --i) { + if ( strncmp(e.fSubString, partialStr, i) == 0 ) { + // found a common substring, splice in new node + // was A -> C, now A -> B -> C + char* bNodeCummStr = strdup(e.fChild->fCummulativeString); + bNodeCummStr[strlen(bNodeCummStr)+i-subStringLen] = '\0'; + //node* aNode = this; + Node* bNode = new Node(bNodeCummStr); + Node* cNode = e.fChild; + char* abEdgeStr = strdup(e.fSubString); + abEdgeStr[i] = '\0'; + char* bcEdgeStr = strdup(&e.fSubString[i]); + Edge& abEdge = e; + abEdge.fSubString = abEdgeStr; + abEdge.fChild = bNode; + Edge bcEdge(bcEdgeStr, cNode); + bNode->fChildren.push_back(bcEdge); + bNode->addSymbol(fullStr, address, flags); + return; + } + } + } + } + // no commonality with any existing child, make a new edge that is this whole string + Node* newNode = new Node(strdup(fullStr)); + Edge newEdge(strdup(partialStr), newNode); + fChildren.push_back(newEdge); + newNode->fAddress = address; + newNode->fFlags = flags; + newNode->fHaveExportInfo = true; + } + + void addOrderedNodes(const char* name, std::vector& orderedNodes) { + if ( !fOrdered ) { + orderedNodes.push_back(this); + //fprintf(stderr, "ordered %p %s\n", this, fCummulativeString); + fOrdered = true; + } + const char* partialStr = &name[strlen(fCummulativeString)]; + for (std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + Edge& e = *it; + int subStringLen = strlen(e.fSubString); + if ( strncmp(e.fSubString, partialStr, subStringLen) == 0 ) { + // already have matching edge, go down that path + e.fChild->addOrderedNodes(name, orderedNodes); + return; + } + } + } + + // byte for terminal node size in bytes, or 0x00 if not terminal node + // teminal node (uleb128 flags, uleb128 addr) + // byte for child node count + // each child: zero terminated substring, uleb128 node offset + bool updateOffset(uint32_t& offset) { + uint32_t nodeSize = 1; // byte for length of export info + if ( fHaveExportInfo ) + nodeSize += uleb128_size(fFlags) + uleb128_size(fAddress); + + // add children + ++nodeSize; // byte for count of chidren + for (std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + Edge& e = *it; + nodeSize += strlen(e.fSubString) + 1 + uleb128_size(e.fChild->fTrieOffset); + } + bool result = (fTrieOffset != offset); + fTrieOffset = offset; + //fprintf(stderr, "updateOffset %p %05d %s\n", this, fTrieOffset, fCummulativeString); + offset += nodeSize; + // return true if fTrieOffset was changed + return result; + } + + void appendToStream(std::vector& out) { + if ( fHaveExportInfo ) { + // nodes with export info: size, flags, address + out.push_back(uleb128_size(fFlags) + uleb128_size(fAddress)); + append_uleb128(fFlags, out); + append_uleb128(fAddress, out); + } + else { + // no export info + out.push_back(0); + } + // write number of children + out.push_back(fChildren.size()); + // write each child + for (std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + Edge& e = *it; + append_string(e.fSubString, out); + append_uleb128(e.fChild->fTrieOffset, out); + } + } + +private: + static void append_uleb128(uint64_t value, std::vector& out) { + uint8_t byte; + do { + byte = value & 0x7F; + value &= ~0x7F; + if ( value != 0 ) + byte |= 0x80; + out.push_back(byte); + value = value >> 7; + } while( byte >= 0x80 ); + } + + static void append_string(const char* str, std::vector& out) { + for (const char* s = str; *s != '\0'; ++s) + out.push_back(*s); + out.push_back('\0'); + } + + static unsigned int uleb128_size(uint64_t value) { + uint32_t result = 0; + do { + value = value >> 7; + ++result; + } while ( value != 0 ); + return result; + } + + +}; + +inline uint64_t read_uleb128(const uint8_t*& p, const uint8_t* end) { + uint64_t result = 0; + int bit = 0; + do { + if (p == end) + throw "malformed uleb128 extends beyond trie"; + + uint64_t slice = *p & 0x7f; + + if (bit >= 64 || slice << bit >> bit != slice) + throw "uleb128 too big for 64-bits"; + else { + result |= (slice << bit); + bit += 7; + } + } + while (*p++ & 0x80); + return result; +} + + + +struct Entry +{ + const char* name; + uint64_t address; + uint64_t flags; +}; + + +inline void makeTrie(const std::vector& input, std::vector& output) +{ + Node start(strdup("")); + + // make nodes for all exported symbols + for (std::vector::const_iterator it = input.begin(); it != input.end(); ++it) { + start.addSymbol(it->name, it->address, it->flags); + } + + // create vector of nodes + std::vector orderedNodes; + orderedNodes.reserve(input.size()*2); + for (std::vector::const_iterator it = input.begin(); it != input.end(); ++it) { + start.addOrderedNodes(it->name, orderedNodes); + } + + // assign each node in the vector an offset in the trie stream, iterating until all uleb128 sizes have stabilized + bool more; + do { + uint32_t offset = 0; + more = false; + for (std::vector::iterator it = orderedNodes.begin(); it != orderedNodes.end(); ++it) { + if ( (*it)->updateOffset(offset) ) + more = true; + } + } while ( more ); + + // create trie stream + for (std::vector::iterator it = orderedNodes.begin(); it != orderedNodes.end(); ++it) { + (*it)->appendToStream(output); + } +} + +struct EntryWithOffset +{ + uintptr_t nodeOffset; + Entry entry; + + bool operator<(const EntryWithOffset& other) const { return ( nodeOffset < other.nodeOffset ); } +}; + + + +static inline void processExportNode(const uint8_t* const start, const uint8_t* p, const uint8_t* const end, + char* cummulativeString, int curStrOffset, std::vector& output) +{ + if ( p >= end ) + throw "malformed trie, node past end"; + const uint8_t terminalSize = *p++; + const uint8_t* children = p + terminalSize; + if ( terminalSize != 0 ) { + EntryWithOffset e; + e.nodeOffset = p-start; + e.entry.name = strdup(cummulativeString); + e.entry.flags = read_uleb128(p, end); + e.entry.address = read_uleb128(p, end); + output.push_back(e); + } + const uint8_t childrenCount = *children++; + const uint8_t* s = children; + for (uint8_t i=0; i < childrenCount; ++i) { + int edgeStrLen = 0; + while (*s != '\0') { + cummulativeString[curStrOffset+edgeStrLen] = *s++; + ++edgeStrLen; + } + cummulativeString[curStrOffset+edgeStrLen] = *s++; + uint32_t childNodeOffet = read_uleb128(s, end); + processExportNode(start, start+childNodeOffet, end, cummulativeString, curStrOffset+edgeStrLen, output); + } +} + + +inline void parseTrie(const uint8_t* start, const uint8_t* end, std::vector& output) +{ + // empty tree has no entries + if ( start == end ) + return; + char cummulativeString[4000]; + std::vector entries; + processExportNode(start, start, end, cummulativeString, 0, entries); + // to preserve tie layout order, sort by node offset + std::sort(entries.begin(), entries.end()); + // copy to output + output.reserve(entries.size()); + for (std::vector::iterator it=entries.begin(); it != entries.end(); ++it) + output.push_back(it->entry); +} + + + + +}; // namespace trie +}; // namespace mach_o + + +#endif // __MACH_O_TRIE__ + + diff --git a/src/Architectures.hpp b/src/ld/Architectures.hpp old mode 100755 new mode 100644 similarity index 80% rename from src/Architectures.hpp rename to src/ld/Architectures.hpp index 2546bfe..ceb448a --- a/src/Architectures.hpp +++ b/src/ld/Architectures.hpp @@ -35,7 +35,8 @@ struct ppc { typedef Pointer32 P; - enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff16, kPointerDiff32, kPointerDiff64, + enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, + kPointerDiff16, kPointerDiff32, kPointerDiff=kPointerDiff32, kPointerDiff64, kBranch24, kBranch24WeakImport, kBranch14, kPICBaseLow16, kPICBaseLow14, kPICBaseHigh16, kAbsLow16, kAbsLow14, kAbsHigh16, kAbsHigh16AddLow, @@ -46,7 +47,8 @@ struct ppc64 { typedef Pointer64 P; - enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff16, kPointerDiff32, kPointerDiff64, + enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, + kPointerDiff16, kPointerDiff32, kPointerDiff64, kPointerDiff=kPointerDiff64, kBranch24, kBranch24WeakImport, kBranch14, kPICBaseLow16, kPICBaseLow14, kPICBaseHigh16, kAbsLow16, kAbsLow14, kAbsHigh16, kAbsHigh16AddLow, @@ -57,8 +59,9 @@ struct x86 { typedef Pointer32 P; - enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff, kPointerDiff16, - kPCRel32, kPCRel32WeakImport, kAbsolute32, kPCRel16, kPCRel8, + enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff, kPointerDiff32=kPointerDiff, kPointerDiff16, + kPCRel32, kPCRel32WeakImport, kAbsolute32, kPCRel16, kPCRel8, + kImageOffset32, kPointerDiff24, kSectionOffset24, kDtraceProbe, kDtraceProbeSite, kDtraceIsEnabledSite, kDtraceTypeReference }; }; @@ -66,11 +69,12 @@ struct x86_64 { typedef Pointer64 P; - enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff, kPointerDiff32, + enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointer32, kPointerWeakImport, kPointerDiff, kPointerDiff32, kPCRel32, kPCRel32_1, kPCRel32_2, kPCRel32_4, kBranchPCRel32, kBranchPCRel32WeakImport, kPCRel32GOTLoad, kPCRel32GOTLoadWeakImport, - kPCRel32GOT, kPCRel32GOTWeakImport, kBranchPCRel8, + kPCRel32GOT, kPCRel32GOTWeakImport, kBranchPCRel8, kGOTNoFixUp, + kImageOffset32, kPointerDiff24, kSectionOffset24, kDtraceProbe, kDtraceProbeSite, kDtraceIsEnabledSite, kDtraceTypeReference }; }; @@ -78,7 +82,7 @@ struct arm { typedef Pointer32 P; - enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff, kReadOnlyPointer, + enum ReferenceKinds { kNoFixUp, kFollowOn, kGroupSubordinate, kPointer, kPointerWeakImport, kPointerDiff, kPointerDiff32=kPointerDiff, kReadOnlyPointer, kBranch24, kBranch24WeakImport, kThumbBranch22, kThumbBranch22WeakImport, kDtraceProbe, kDtraceProbeSite, kDtraceIsEnabledSite, kDtraceTypeReference }; }; diff --git a/src/ArchiveReader.hpp b/src/ld/ArchiveReader.hpp old mode 100755 new mode 100644 similarity index 88% rename from src/ArchiveReader.hpp rename to src/ld/ArchiveReader.hpp index c3aebf8..b8f1a5c --- a/src/ArchiveReader.hpp +++ b/src/ld/ArchiveReader.hpp @@ -55,6 +55,7 @@ public: static bool validFile(const uint8_t* fileContent, uint64_t fileLength); Reader(const uint8_t fileContent[], uint64_t fileLength, const char* path, time_t modTime, + const LibraryOptions& archiveOptions, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase); virtual ~Reader() {} @@ -64,8 +65,12 @@ public: virtual std::vector& getAtoms(); virtual std::vector* getJustInTimeAtomsFor(const char* name); virtual std::vector* getStabs() { return NULL; } - virtual void optimize(std::vector&, std::vector&, - std::vector&, uint32_t, ObjectFile::Reader* writer, + virtual bool optimize(const std::vector&, std::vector&, + std::vector&, const std::set&, + std::vector& newDeadAtoms, + uint32_t, ObjectFile::Reader* writer, + ObjectFile::Atom* entryPointAtom, + const std::vector& llvmOptions, bool allGlobalsAReDeadStripRoots, int okind, bool verbose, bool saveTemps, const char* outputFilePath, bool pie, bool allowTextRelocs); @@ -119,6 +124,7 @@ private: std::set fInstantiatedEntries; std::set fPossibleEntries; NameToEntryMap fHashTable; + bool fForceLoad; static std::vector fgEmptyList; }; @@ -256,9 +262,10 @@ bool Reader::validFile(const uint8_t* fileContent, uint64_t fileLength) template Reader::Reader(const uint8_t fileContent[], uint64_t fileLength, const char* path, time_t modTime, + const LibraryOptions& archiveOptions, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase) : fPath(NULL), fModTime(modTime), fOptions(options), fOrdinalBase(ordinalBase), fFileContent(NULL), - fTableOfContents(NULL), fTableOfContentCount(0), fStringPool(NULL) + fTableOfContents(NULL), fTableOfContentCount(0), fStringPool(NULL), fForceLoad(archiveOptions.fForceLoad) { fPath = strdup(path); fFileContent = fileContent; @@ -271,7 +278,7 @@ Reader::Reader(const uint8_t fileContent[], uint64_t fileLength, const char* if ( options.fLogAllFiles ) printf("%s\n", path); - if ( !options.fFullyLoadArchives ) { + if ( !options.fFullyLoadArchives && !fForceLoad ) { const Entry* const firstMember = (Entry*)&fFileContent[8]; if ( (strcmp(firstMember->getName(), SYMDEF_SORTED) == 0) || (strcmp(firstMember->getName(), SYMDEF) == 0) ) { const uint8_t* contents = firstMember->getContent(); @@ -311,7 +318,7 @@ ObjectFile::Reader* Reader::makeObjectReaderForMember(const Entry* member) return new typename lto::Reader(member->getContent(), member->getContentSize(), memberPath, member->getModTime(), fOptions, architecture()); } #endif - throw "not a valid archive member"; + throwf("archive member '%s' with length %d is not mach-o or bitcode", memberName, member->getContentSize()); } catch (const char* msg) { throwf("in %s, %s", memberPath, msg); @@ -322,7 +329,7 @@ ObjectFile::Reader* Reader::makeObjectReaderForMember(const Entry* member) template std::vector& Reader::getAtoms() { - if ( fOptions.fFullyLoadArchives ) { + if ( fOptions.fFullyLoadArchives || fForceLoad ) { // build vector of all atoms from all .o files in this archive const Entry* const start = (Entry*)&fFileContent[8]; const Entry* const end = (Entry*)&fFileContent[fFileLength]; @@ -330,8 +337,12 @@ std::vector& Reader::getAtoms() const char* memberName = p->getName(); if ( (p==start) && ((strcmp(memberName, SYMDEF_SORTED) == 0) || (strcmp(memberName, SYMDEF) == 0)) ) continue; - if ( fOptions.fWhyLoad ) - printf("-all_load forced load of %s(%s)\n", this->getPath(), memberName); + if ( fOptions.fWhyLoad ) { + if ( fForceLoad ) + printf("-force_load forced load of %s(%s)\n", this->getPath(), memberName); + else + printf("-all_load forced load of %s(%s)\n", this->getPath(), memberName); + } ObjectFile::Reader* r = this->makeObjectReaderForMember(p); std::vector& atoms = r->getAtoms(); fAllAtoms.insert(fAllAtoms.end(), atoms.begin(), atoms.end()); @@ -365,16 +376,22 @@ std::vector& Reader::getAtoms() } template -void Reader::optimize(std::vector& allAtoms, std::vector& newAtoms, - std::vector& additionalUndefines, uint32_t nextOrdinal, ObjectFile::Reader* writer, +bool Reader::optimize(const std::vector& allAtoms, std::vector& newAtoms, + std::vector& additionalUndefines, const std::set& deadAtoms, + std::vector& newDeadAtoms, + uint32_t nextOrdinal, ObjectFile::Reader* writer, ObjectFile::Atom* entryPointAtom, + const std::vector& llvmOptions, bool allGlobalsAReDeadStripRoots, int okind, bool verbose, bool saveTemps, const char* outputFilePath, bool pie, bool allowTextRelocs) { + bool result = false; for(std::vector::iterator it=fInstantiatedReaders.begin(); it != fInstantiatedReaders.end(); ++it) { - (*it)->optimize(allAtoms, newAtoms, additionalUndefines, nextOrdinal, writer, allGlobalsAReDeadStripRoots, - okind, verbose, saveTemps, outputFilePath, pie, allowTextRelocs); + result |= (*it)->optimize(allAtoms, newAtoms, additionalUndefines, deadAtoms, newDeadAtoms, nextOrdinal, + writer, entryPointAtom, llvmOptions, allGlobalsAReDeadStripRoots, okind, + verbose, saveTemps, outputFilePath, pie, allowTextRelocs); } + return result; } @@ -416,7 +433,7 @@ void Reader::dumpTableOfContents() template std::vector* Reader::getJustInTimeAtomsFor(const char* name) { - if ( fOptions.fFullyLoadArchives ) { + if ( fOptions.fFullyLoadArchives || fForceLoad ) { return NULL; } else { @@ -426,7 +443,7 @@ std::vector* Reader::getJustInTimeAtomsFor(const cha if ( result != NULL ) { const Entry* member = (Entry*)&fFileContent[E::get32(result->ran_off)]; if ( fInstantiatedEntries.count(member) == 0 ) { - if ( fOptions.fWhyLoad ) + if ( fOptions.fWhyLoad ) printf("%s forced load of %s(%s)\n", name, this->getPath(), member->getName()); // only return these atoms once fInstantiatedEntries.insert(member); diff --git a/src/ExecutableFile.h b/src/ld/ExecutableFile.h old mode 100755 new mode 100644 similarity index 88% rename from src/ExecutableFile.h rename to src/ld/ExecutableFile.h index b0b760d..675d3da --- a/src/ExecutableFile.h +++ b/src/ld/ExecutableFile.h @@ -37,7 +37,7 @@ namespace ExecutableFile { struct DyLibUsed { ObjectFile::Reader* reader; - DynamicLibraryOptions options; + LibraryOptions options; }; class Writer : public ObjectFile::Reader @@ -54,12 +54,14 @@ namespace ExecutableFile { virtual uint64_t write(std::vector& atoms, std::vector& stabs, class ObjectFile::Atom* entryPointAtom, - class ObjectFile::Atom* dyldHelperAtom, + class ObjectFile::Atom* dyldClassicHelperAtom, + class ObjectFile::Atom* dyldCompressedHelperAtom, class ObjectFile::Atom* dyldLazyDylibHelperAtom, bool createUUID, bool canScatter, ObjectFile::Reader::CpuConstraint cpuConstraint, bool biggerThanTwoGigs, - bool overridesDylibWeakDefines) = 0; + std::set& atomsThatOverrideWeak, + bool hasExternalWeakDefinitions) = 0; protected: Writer(std::vector&) {}; diff --git a/src/LTOReader.hpp b/src/ld/LTOReader.hpp old mode 100755 new mode 100644 similarity index 84% rename from src/LTOReader.hpp rename to src/ld/LTOReader.hpp index 4cd5644..1b8f2c3 --- a/src/LTOReader.hpp +++ b/src/ld/LTOReader.hpp @@ -142,7 +142,7 @@ public: { return fRealAtom->getTranslationUnitSource(dir, name); } const char * getName () const { return fName; } const char * getDisplayName() const { return this->getName(); } - Scope getScope() const { return fScope; } + Scope getScope() const { return (fRealAtom ? fRealAtom->getScope() : fScope); } DefinitionKind getDefinitionKind() const { return (fRealAtom ? fRealAtom->getDefinitionKind() : fKind); } SymbolTableInclusion getSymbolTableInclusion() const { return fRealAtom->getSymbolTableInclusion(); } @@ -209,7 +209,7 @@ public: bool getTranslationUnitSource (const char **dir, const char **name) const { return false; } const char * getName () const { return "__llvm-internal-atom"; } - const char * getDisplayName() const { return this->getName(); } + const char * getDisplayName() const { return "llvm bitcode"; } Scope getScope() const { return scopeTranslationUnit; } DefinitionKind getDefinitionKind() const { return kRegularDefinition; } SymbolTableInclusion getSymbolTableInclusion() const { return kSymbolTableNotIn; } @@ -232,7 +232,7 @@ public: void addReference(const char* targetName); private: - class Reader& fOwner; + class Reader& fOwner; std::vector fReferences; }; @@ -279,9 +279,13 @@ public: virtual time_t getModificationTime() { return fModTime; } virtual ObjectFile::Reader::DebugInfoKind getDebugInfoKind() { return kDebugInfoNone; } virtual std::vector* getStabs() { return NULL; } - virtual void optimize(std::vector &allAtoms, std::vector &newAtoms, - std::vector &additionalUndefines, uint32_t nextInputOrdinal, - ObjectFile::Reader* writer, bool allGlobalsAReDeadStripRoots, + virtual bool optimize(const std::vector& allAtoms, std::vector& newAtoms, + std::vector& additionalUndefines, const std::set&, + std::vector& newDeadAtoms, + uint32_t nextInputOrdinal, + ObjectFile::Reader* writer, ObjectFile::Atom* entryPointAtom, + const std::vector& llvmOptions, + bool allGlobalsAReDeadStripRoots, int outputKind, bool verbose, bool saveTemps, const char* outputFilePath, bool pie, bool allowTextRelocs); @@ -321,7 +325,7 @@ Reader::~Reader() Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path, time_t modTime, const ObjectFile::ReaderOptions& options, cpu_type_t arch) - : fArchitecture(arch), fPath(path), fModTime(modTime), fInternalAtom(*this), fReaderOptions(options) + : fArchitecture(arch), fPath(strdup(path)), fModTime(modTime), fInternalAtom(*this), fReaderOptions(options) { fgReaders.insert(this); @@ -329,12 +333,19 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path if ( fModule == NULL ) throwf("could not parse object file %s: %s", path, lto_get_error_message()); + fAtoms.push_back(&fInternalAtom); uint32_t count = ::lto_module_get_num_symbols(fModule); for (uint32_t i=0; i < count; ++i) { const char* name = ::lto_module_get_symbol_name(fModule, i); lto_symbol_attributes attr = lto_module_get_symbol_attribute(fModule, i); - + + // LTO doesn't like dtrace symbols + // ignore dtrace static probes for now + // later when codegen is done and a mach-o file is produces the probes will be processed + if ( (strncmp(name, "___dtrace_probe$", 16) == 0) || (strncmp(name, "___dtrace_isenabled$", 20) == 0) ) + continue; + ObjectFile::Atom::DefinitionKind kind; switch ( attr & LTO_SYMBOL_DEFINITION_MASK ) { case LTO_SYMBOL_DEFINITION_REGULAR: @@ -347,6 +358,7 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path kind = ObjectFile::Atom::kWeakDefinition; break; case LTO_SYMBOL_DEFINITION_UNDEFINED: + case LTO_SYMBOL_DEFINITION_WEAKUNDEF: kind = ObjectFile::Atom::kExternalDefinition; break; default: @@ -395,7 +407,7 @@ const char* Reader::tripletPrefixForArch(cpu_type_t arch) case CPU_TYPE_X86_64: return "x86_64-"; case CPU_TYPE_ARM: - return "arm-"; + return "arm"; } return ""; } @@ -405,16 +417,19 @@ bool Reader::validFile(const uint8_t* fileContent, uint64_t fileLength, cpu_type return ::lto_module_is_object_file_in_memory_for_target(fileContent, fileLength, tripletPrefixForArch(architecture)); } -void Reader::optimize(std::vector& allAtoms, std::vector& newAtoms, - std::vector& additionalUndefines, uint32_t nextInputOrdinal, - ObjectFile::Reader* writer, bool allGlobalsAReDeadStripRoots, +bool Reader::optimize(const std::vector& allAtoms, std::vector& newAtoms, + std::vector& additionalUndefines, const std::set& deadAtoms, + std::vector& newlyDeadAtoms, + uint32_t nextInputOrdinal, ObjectFile::Reader* writer, ObjectFile::Atom* entryPointAtom, + const std::vector& llvmOptions, + bool allGlobalsAReDeadStripRoots, int okind, bool verbose, bool saveTemps, const char* outputFilePath, bool pie, bool allowTextRelocs) { // this method is call on all Readers. We want the first call to trigger optimization // across all Readers and the subsequent calls to do nothing. if ( fgOptimized ) - return; + return false; fgOptimized = true; Options::OutputKind outputKind = (Options::OutputKind)okind; // HACK to work around upward dependency @@ -427,12 +442,14 @@ void Reader::optimize(std::vector& allAtoms, std::vector::iterator it=fgReaders.begin(); it != fgReaders.end(); ++it) { if ( ::lto_codegen_add_module(generator, (*it)->fModule) ) - throwf("lto: could not merge in %s", (*it)->fPath); + throwf("lto: could not merge in %s because %s", (*it)->fPath, ::lto_get_error_message()); + } + + // add any -mllvm command line options + for (std::vector::const_iterator it=llvmOptions.begin(); it != llvmOptions.end(); ++it) { + ::lto_codegen_debug_options(generator, *it); } - // the linker must preserve all globals in dylibs and flat images - const bool globalsNeedPreserving = allGlobalsAReDeadStripRoots || fReaderOptions.fFlatNamespace; - // The atom graph uses directed edges (references). Collect all references where // originating atom is not part of any LTO Reader. This allows optimizer to optimize an // external (i.e. not originated from same .o file) reference if all originating atoms are also @@ -440,11 +457,11 @@ void Reader::optimize(std::vector& allAtoms, std::vector::iterator it = allAtoms.begin(); it != allAtoms.end(); ++it) { + for (std::vector::const_iterator it = allAtoms.begin(); it != allAtoms.end(); ++it) { ObjectFile::Atom* atom = *it; // only look at references come from an atom that is not an llvm atom if ( fgReaders.count((Reader*)(atom->getFile())) == 0 ) { - // remember if we've seen an atoms not from an llvm reader and not from the writer + // remember if we've seen any atoms not from an llvm reader and not from the writer if ( atom->getFile() != writer ) hasNonllvmAtoms = true; std::vector& refs = atom->getReferences(); @@ -462,17 +479,38 @@ void Reader::optimize(std::vector& allAtoms, std::vectorgetFile())) != 0 ) + nonLLVMRefs.insert(entryPointAtom->getName()); + } + + // deadAtoms are the atoms that the linker coalesced. For instance weak or tentative definitions + // overriden by another atom. If any of these deadAtoms are llvm atoms and they were replaced + // with a mach-o atom, we need to tell the lto engine to preserve (not optimize away) its dead + // atom so that the linker can replace it with the mach-o one later. + CStringToAtom deadllvmAtoms; + for (std::set::iterator it = deadAtoms.begin(); it != deadAtoms.end(); ++it) { + ObjectFile::Atom* atom = *it; + if ( fgReaders.count((Reader*)(atom->getFile())) != 0 ) { + const char* name = atom->getName(); + ::lto_codegen_add_must_preserve_symbol(generator, name); + deadllvmAtoms[name] = (Atom*)atom; + } + } + + // tell code generator about symbols that must be preserved for (CStringToAtom::iterator it = llvmAtoms.begin(); it != llvmAtoms.end(); ++it) { const char* name = it->first; Atom* atom = it->second; // Include llvm Symbol in export list if it meets one of following two conditions - // 1 - globals need preserving and atom scope is global (and not linkage unit). + // 1 - atom scope is global (and not linkage unit). // 2 - included in nonLLVMRefs set. // If a symbol is not listed in exportList then LTO is free to optimize it away. - if ( globalsNeedPreserving && (atom->getScope() == ObjectFile::Atom::scopeGlobal) ) + if ( (atom->getScope() == ObjectFile::Atom::scopeGlobal) ) ::lto_codegen_add_must_preserve_symbol(generator, name); - else if ( nonLLVMRefs.find(name) != nonLLVMRefs.end() ) + else if ( nonLLVMRefs.find(name) != nonLLVMRefs.end() ) ::lto_codegen_add_must_preserve_symbol(generator, name); } @@ -497,6 +535,7 @@ void Reader::optimize(std::vector& allAtoms, std::vector& allAtoms, std::vector& allAtoms, std::vectormakeMachOReader(machOFile, machOFileLen, nextInputOrdinal); - // sync generated mach-o atoms with existing atoms ld know about + // sync generated mach-o atoms with existing atoms ld knows about std::vector machoAtoms = machoReader->getAtoms(); for (std::vector::iterator it = machoAtoms.begin(); it != machoAtoms.end(); ++it) { ObjectFile::Atom* atom = *it; @@ -551,8 +591,24 @@ void Reader::optimize(std::vector& allAtoms, std::vectorsecond->setRealAtom(atom); } else { - // this atom is did not exist orginally, tell ld about it - newAtoms.push_back(atom); + // an atom of this name was not in the allAtoms list the linker gave us + if ( deadllvmAtoms.find(name) != deadllvmAtoms.end() ) { + // this corresponding to an atom that the linker coalesced away. Ignore it + // Make sure there any dependent atoms are also marked dead + std::vector& refs = atom->getReferences(); + for (std::vector::iterator ri=refs.begin(), re=refs.end(); ri != re; ++ri) { + ObjectFile::Reference* ref = *ri; + if ( ref->getKind() == 2 /*kGroupSubordinate*/ ) { // FIX FIX + ObjectFile::Atom* targ = &ref->getTarget(); + deadllvmAtoms[targ->getName()] = (Atom*)atom; + } + } + } + else + { + // this is something new that lto conjured up, tell ld its new + newAtoms.push_back(atom); + } } } else { @@ -587,17 +643,17 @@ void Reader::optimize(std::vector& allAtoms, std::vector deletedAtoms; for (std::set::iterator it=fgReaders.begin(); it != fgReaders.end(); ++it) { - deletedAtoms.insert(&((*it)->fInternalAtom)); + newlyDeadAtoms.push_back(&((*it)->fInternalAtom)); } // Remove Atoms from ld if code generator optimized them away for (CStringToAtom::iterator li = llvmAtoms.begin(), le = llvmAtoms.end(); li != le; ++li) { // check if setRealAtom() called on this Atom if ( li->second->getRealAtom() == NULL ) - deletedAtoms.insert(li->second); + newlyDeadAtoms.push_back(li->second); } - allAtoms.erase(std::remove_if(allAtoms.begin(), allAtoms.end(), RemovableAtoms(deletedAtoms)), allAtoms.end()); + + return true; } @@ -630,6 +686,7 @@ ObjectFile::Reader* Reader::makeMachOReader(const uint8_t* p, size_t len, uint32 }; // namespace lto +extern void printLTOVersion(Options &opts); void printLTOVersion(Options &opts) { const char* vers = lto_get_version(); diff --git a/src/MachOReaderDylib.hpp b/src/ld/MachOReaderDylib.hpp old mode 100755 new mode 100644 similarity index 86% rename from src/MachOReaderDylib.hpp rename to src/ld/MachOReaderDylib.hpp index eb8e844..8aea6ef --- a/src/MachOReaderDylib.hpp +++ b/src/ld/MachOReaderDylib.hpp @@ -37,6 +37,7 @@ #include #include "MachOFileAbstraction.hpp" +#include "MachOTrie.hpp" #include "ObjectFile.h" // @@ -223,7 +224,7 @@ class Reader : public ObjectFile::Reader public: static bool validFile(const uint8_t* fileContent, bool executableOrDylib); Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path, - const DynamicLibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options, + const LibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase); virtual ~Reader() {} @@ -246,6 +247,7 @@ public: virtual const char* parentUmbrella() { return fParentUmbrella; } virtual std::vector* getAllowableClients(); virtual bool hasWeakExternals() { return fHasWeakExports; } + virtual bool deadStrippable() { return fDeadStrippable; } virtual bool isLazyLoadedDylib() { return fLazyLoaded; } virtual void setImplicitlyLinked() { fImplicitlyLinked = true; } @@ -273,7 +275,13 @@ private: struct PathAndFlag { const char* path; bool reExport; }; bool isPublicLocation(const char* path); - void addSymbol(const char* name, bool weak, uint32_t ordinal); + void addSymbol(const char* name, bool weak); + void addDyldFastStub(); + void buildExportHashTableFromExportInfo(const macho_dyld_info_command

* dyldInfo, + const uint8_t* fileContent); + void buildExportHashTableFromSymbolTable(const macho_dysymtab_command

* dynamicInfo, + const macho_nlist

* symbolTable, const char* strings, + const uint8_t* fileContent); const char* fPath; const char* fParentUmbrella; @@ -288,6 +296,7 @@ private: NameSet fIgnoreExports; bool fNoRexports; bool fHasWeakExports; + bool fDeadStrippable; const bool fLinkingFlat; const bool fLinkingMainExecutable; bool fExplictReExportFound; @@ -298,7 +307,7 @@ private: bool fLazyLoaded; ObjectFile::Reader::ObjcConstraint fObjcContraint; std::vector fReExportedChildren; - const ObjectFile::ReaderOptions::VersionMin fDeploymentVersionMin; + const ObjectFile::ReaderOptions::MacVersionMin fDeploymentVersionMin; std::vector fFlatImports; static bool fgLogHashtable; @@ -313,15 +322,15 @@ bool Reader::fgLogHashtable = false; template Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* path, - const DynamicLibraryOptions& dylibOptions, + const LibraryOptions& dylibOptions, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase) : fParentUmbrella(NULL), fDylibInstallPath(NULL), fDylibTimeStamp(0), fDylibtCurrentVersion(0), - fDylibCompatibilityVersion(0), fLinkingFlat(options.fFlatNamespace), + fDylibCompatibilityVersion(0), fReExportedOrdinal(ordinalBase), fLinkingFlat(options.fFlatNamespace), fLinkingMainExecutable(options.fLinkingMainExecutable), fExplictReExportFound(false), fExplicitlyLinked(false), fImplicitlyLinked(false), fProvidedAtom(false), fImplicitlyLinkPublicDylibs(options.fImplicitlyLinkPublicDylibs), fLazyLoaded(dylibOptions.fLazyLoad), fObjcContraint(ObjectFile::Reader::kObjcNone), - fDeploymentVersionMin(options.fVersionMin) + fDeploymentVersionMin(options.fMacVersionMin) { // sanity check if ( ! validFile(fileContent, dylibOptions.fBundleLoader) ) @@ -355,6 +364,7 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* p // optimize the case where we know there is no reason to look at indirect dylibs fNoRexports = (header->flags() & MH_NO_REEXPORTED_DYLIBS); fHasWeakExports = (header->flags() & MH_WEAK_DEFINES); + fDeadStrippable = (header->flags() & MH_DEAD_STRIPPABLE_DYLIB); bool trackDependentLibraries = !fNoRexports || options.fFlatNamespace; // pass 1 builds list of all dependent libraries @@ -381,6 +391,7 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* p // pass 2 determines re-export info const macho_dysymtab_command

* dynamicInfo = NULL; + const macho_dyld_info_command

* dyldInfo = NULL; const macho_nlist

* symbolTable = NULL; const char* strings = NULL; cmd = cmds; @@ -396,6 +407,10 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* p case LC_DYSYMTAB: dynamicInfo = (macho_dysymtab_command

*)cmd; break; + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: + dyldInfo = (macho_dyld_info_command

*)cmd; + break; case LC_ID_DYLIB: { macho_dylib_command

* dylibID = (macho_dylib_command

*)cmd; @@ -504,44 +519,90 @@ Reader::Reader(const uint8_t* fileContent, uint64_t fileLength, const char* p for (const macho_nlist

* sym=start; sym < end; ++sym) { importNames.push_back(&strings[sym->n_strx()]); } - fFlatImports.push_back(new ImportAtom(*this, ordinalBase++, importNames)); + fFlatImports.push_back(new ImportAtom(*this, fReExportedOrdinal++, importNames)); } - + // build hash table + if ( dyldInfo != NULL ) + buildExportHashTableFromExportInfo(dyldInfo, fileContent); + else + buildExportHashTableFromSymbolTable(dynamicInfo, symbolTable, strings, fileContent); + + // special case libSystem + if ( (fDylibInstallPath != NULL) && (strcmp(fDylibInstallPath, "/usr/lib/libSystem.B.dylib") == 0) ) + addDyldFastStub(); + + // unmap file + munmap((caddr_t)fileContent, fileLength); +} + + +template +void Reader::buildExportHashTableFromSymbolTable(const macho_dysymtab_command

* dynamicInfo, + const macho_nlist

* symbolTable, const char* strings, + const uint8_t* fileContent) +{ if ( dynamicInfo->tocoff() == 0 ) { - if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), path); + if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u toc entries for %s\n", dynamicInfo->nextdefsym(), this->getPath()); const macho_nlist

* start = &symbolTable[dynamicInfo->iextdefsym()]; const macho_nlist

* end = &start[dynamicInfo->nextdefsym()]; fAtoms.resize(dynamicInfo->nextdefsym()); // set initial bucket count - uint32_t index = ordinalBase; - for (const macho_nlist

* sym=start; sym < end; ++sym, ++index) { - this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, index); + for (const macho_nlist

* sym=start; sym < end; ++sym) { + this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0); } - fReExportedOrdinal = index; } else { int32_t count = dynamicInfo->ntoc(); fAtoms.resize(count); // set initial bucket count - if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, path); - const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)((char*)header + dynamicInfo->tocoff()); + if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable of %u entries for %s\n", count, this->getPath()); + const struct dylib_table_of_contents* toc = (dylib_table_of_contents*)(fileContent + dynamicInfo->tocoff()); for (int32_t i = 0; i < count; ++i) { const uint32_t index = E::get32(toc[i].symbol_index); const macho_nlist

* sym = &symbolTable[index]; - this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0, ordinalBase+i); + this->addSymbol(&strings[sym->n_strx()], (sym->n_desc() & N_WEAK_DEF) != 0); } - fReExportedOrdinal = ordinalBase + count; } +} - - // unmap file - munmap((caddr_t)fileContent, fileLength); + +template +void Reader::buildExportHashTableFromExportInfo(const macho_dyld_info_command

* dyldInfo, + const uint8_t* fileContent) +{ + if ( fgLogHashtable ) fprintf(stderr, "ld: building hashtable from export info in %s\n", this->getPath()); + if ( dyldInfo->export_size() > 0 ) { + const uint8_t* start = fileContent + dyldInfo->export_off(); + const uint8_t* end = &start[dyldInfo->export_size()]; + std::vector list; + parseTrie(start, end, list); + for (std::vector::iterator it=list.begin(); it != list.end(); ++it) + this->addSymbol(it->name, it->flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); + } } +template <> +void Reader::addDyldFastStub() +{ + addSymbol("dyld_stub_binder", false); +} + +template <> +void Reader::addDyldFastStub() +{ + addSymbol("dyld_stub_binder", false); +} + +template +void Reader::addDyldFastStub() +{ + // do nothing +} template -void Reader::addSymbol(const char* name, bool weak, uint32_t ordinal) +void Reader::addSymbol(const char* name, bool weakDef) { + //fprintf(stderr, "addSymbol() %s\n", name); // symbols that start with $ld$ are meta-data to the static linker // need way for ld and dyld to see different exported symbols in a dylib if ( strncmp(name, "$ld$", 4) == 0 ) { @@ -549,7 +610,7 @@ void Reader::addSymbol(const char* name, bool weak, uint32_t ordinal) const char* symAction = &name[4]; const char* symCond = strchr(symAction, '$'); if ( symCond != NULL ) { - ObjectFile::ReaderOptions::VersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinUnset; + ObjectFile::ReaderOptions::MacVersionMin symVersionCondition = ObjectFile::ReaderOptions::kMinMacVersionUnset; if ( (strncmp(symCond, "$os10.", 6) == 0) && isdigit(symCond[6]) && (symCond[7] == '$') ) { switch ( symCond[6] - '0' ) { case 0: @@ -582,7 +643,7 @@ void Reader::addSymbol(const char* name, bool weak, uint32_t ordinal) return; } else if ( strncmp(symAction, "add$", 4) == 0 ) { - this->addSymbol(symName, weak, ordinal); + this->addSymbol(symName, weakDef); return; } else { @@ -607,8 +668,8 @@ void Reader::addSymbol(const char* name, bool weak, uint32_t ordinal) if ( fIgnoreExports.count(name) == 0 ) { AtomAndWeak bucket; bucket.atom = NULL; - bucket.weak = weak; - bucket.ordinal = ordinal; + bucket.weak = weakDef; + bucket.ordinal = fReExportedOrdinal++; if ( fgLogHashtable ) fprintf(stderr, " adding %s to hash table for %s\n", name, this->getPath()); fAtoms[strdup(name)] = bucket; } @@ -625,8 +686,11 @@ std::vector& Reader::getAtoms() template std::vector* Reader::getJustInTimeAtomsFor(const char* name) { + // if supposed to ignore this export, then pretend I don't have it + if ( fIgnoreExports.count(name) != 0 ) + return NULL; + std::vector* atoms = NULL; - NameToAtomMapIterator pos = fAtoms.find(name); if ( pos != fAtoms.end() ) { if ( pos->second.atom == NULL ) { @@ -641,23 +705,20 @@ std::vector* Reader::getJustInTimeAtomsFor(const cha } else { if ( fgLogHashtable ) fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s\n", name, this->getPath()); - // if not supposed to ignore this export, see if I have it - if ( fIgnoreExports.count(name) == 0 ) { - // look in children that I re-export - for (std::vector::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) { - //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->getPath(), (*it)->getInstallPath()); - std::vector* childAtoms = (*it)->getJustInTimeAtomsFor(name); - if ( childAtoms != NULL ) { - // make a new atom that says this reader is the owner - bool isWeakDef = (childAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition); - // return a vector of one atom - ExportAtom* newAtom = new ExportAtom(*this, name, isWeakDef, fReExportedOrdinal++); - fProvidedAtom = true; - atoms = new std::vector; - atoms->push_back(newAtom); - delete childAtoms; - return atoms; - } + // look in children that I re-export + for (std::vector::iterator it = fReExportedChildren.begin(); it != fReExportedChildren.end(); it++) { + //fprintf(stderr, "getJustInTimeAtomsFor: %s NOT found in %s, looking in child %s\n", name, this->getPath(), (*it)->getInstallPath()); + std::vector* childAtoms = (*it)->getJustInTimeAtomsFor(name); + if ( childAtoms != NULL ) { + // make a new atom that says this reader is the owner + bool isWeakDef = (childAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition); + // return a vector of one atom + ExportAtom* newAtom = new ExportAtom(*this, name, isWeakDef, fReExportedOrdinal++); + fProvidedAtom = true; + atoms = new std::vector; + atoms->push_back(newAtom); + delete childAtoms; + return atoms; } } } @@ -719,13 +780,18 @@ void Reader::processIndirectLibraries(DylibHander* handler) //fprintf(stderr, "processIndirectLibraries() implicitly linking %s\n", child->getInstallPath()); ((Reader*)child)->setImplicitlyLinked(); } - else + else if ( child->explicitlyLinked() || child->implicitlyLinked() ) { + //fprintf(stderr, "processIndirectLibraries() parent is not directly linked, but child is, so no need to re-export child\n"); + } + else { fReExportedChildren.push_back(child); + //fprintf(stderr, "processIndirectLibraries() parent is not directly linked, so parent=%s will re-export child=%s\n", this->getInstallPath(), it->path); + } } else { // add all child's symbols to me fReExportedChildren.push_back(child); - //fprintf(stderr, "processIndirectLibraries() parent=%s will re-export child=%s\n", this->getInstallPath(), it->path); + //fprintf(stderr, "processIndirectLibraries() child is not public, so parent=%s will re-export child=%s\n", this->getInstallPath(), it->path); } } else if ( !fExplictReExportFound ) { diff --git a/src/MachOReaderRelocatable.hpp b/src/ld/MachOReaderRelocatable.hpp old mode 100755 new mode 100644 similarity index 74% rename from src/MachOReaderRelocatable.hpp rename to src/ld/MachOReaderRelocatable.hpp index 73c58e2..e576313 --- a/src/MachOReaderRelocatable.hpp +++ b/src/ld/MachOReaderRelocatable.hpp @@ -1,6 +1,6 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * - * Copyright (c) 2005-2008 Apple Inc. All rights reserved. + * Copyright (c) 2005-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -40,6 +40,9 @@ #include "dwarf2.h" #include "debugline.h" +#include +#include +#include // // @@ -102,18 +105,21 @@ public: virtual ObjectFile::Reference::TargetBinding getFromTargetBinding() const; virtual uint8_t getKind() const { return (uint8_t)fKind; } virtual uint64_t getFixUpOffset() const { return fFixUpOffsetInSrc; } - virtual const char* getTargetName() const { return (fToTargetName != NULL) ? fToTargetName : fToTarget.atom->getName(); } + virtual const char* getTargetName() const { return (fToTarget.atom != NULL) ? fToTarget.atom->getName() : fToTargetName; } virtual ObjectFile::Atom& getTarget() const { return *fToTarget.atom; } virtual uint64_t getTargetOffset() const { return (int64_t)((int32_t)fToTarget.offset); } virtual ObjectFile::Atom& getFromTarget() const { return *fFromTarget.atom; } - virtual const char* getFromTargetName() const { return (fFromTargetName != NULL) ? fFromTargetName : fFromTarget.atom->getName(); } - virtual void setTarget(ObjectFile::Atom& target, uint64_t offset) { fToTarget.atom = ⌖ fToTarget.offset = offset; } + virtual const char* getFromTargetName() const { return (fFromTarget.atom != NULL) ? fFromTarget.atom->getName() : fFromTargetName; } + virtual void setTarget(ObjectFile::Atom& target, uint64_t offset) { fToTarget.atom = ⌖ fToTarget.offset = offset; } virtual void setToTargetOffset(uint64_t offset) { fToTarget.offset = offset; } virtual void setFromTarget(ObjectFile::Atom& target) { fFromTarget.atom = ⌖ } virtual void setFromTargetName(const char* name) { fFromTargetName = name; } virtual void setFromTargetOffset(uint64_t offset) { fFromTarget.offset = offset; } virtual const char* getDescription() const; virtual uint64_t getFromTargetOffset() const { return fFromTarget.offset; } + virtual bool isBranch() const; + virtual const char* getTargetDisplayName() const { return (fToTarget.atom != NULL) ? fToTarget.atom->getDisplayName() : fToTargetName; } + virtual const char* getFromTargetDisplayName() const { return (fFromTarget.atom != NULL) ? fFromTarget.atom->getDisplayName() : fFromTargetName; } static bool fgForFinalLinkedImage; @@ -127,6 +133,7 @@ private: }; + template bool Reference::fgForFinalLinkedImage = true; template @@ -270,23 +277,86 @@ LinkEditSegment LinkEditSegment::fgSingleton; class BaseAtom : public ObjectFile::Atom { public: - BaseAtom() : fStabsStartIndex(0), fStabsCount(0) {} + BaseAtom() : fStabsStartIndex(0), fStabsCount(0), fHasCompactUnwindInfo(false) {} - virtual void setSize(uint64_t size) = 0; + virtual void setSize(uint64_t size) = 0; virtual void addReference(ObjectFile::Reference* ref) = 0; virtual void sortReferences() = 0; virtual void addLineInfo(const ObjectFile::LineInfo& info) = 0; + virtual const ObjectFile::ReaderOptions& getOptions() const = 0; virtual uint64_t getObjectAddress() const = 0; virtual uint32_t getOrdinal() const { return fOrdinal; } virtual void setOrdinal(uint32_t value) { fOrdinal = value; } virtual const void* getSectionRecord() const = 0; virtual bool isAlias() const { return false; } + virtual uint8_t getLSDAReferenceKind() const { return 0; } + virtual uint8_t getPersonalityReferenceKind() const { return 0; } + virtual uint32_t getCompactUnwindEncoding(uint64_t ehAtomAddress) { return 0; } + virtual ObjectFile::UnwindInfo::iterator beginUnwind() { return fHasCompactUnwindInfo ? &fSingleUnwindInfo[0] : NULL; } + virtual ObjectFile::UnwindInfo::iterator endUnwind() { return fHasCompactUnwindInfo ? &fSingleUnwindInfo[1] : NULL; } + virtual ObjectFile::Reference* getLSDA(); + virtual ObjectFile::Reference* getFDE(); + virtual Atom* getPersonalityPointer(); + virtual void setCompactUnwindEncoding(uint64_t ehAtomAddress); uint32_t fStabsStartIndex; uint32_t fStabsCount; uint32_t fOrdinal; + ObjectFile::UnwindInfo fSingleUnwindInfo[1]; + bool fHasCompactUnwindInfo; }; + +ObjectFile::Reference* BaseAtom::getLSDA() +{ + const uint8_t groupKind = this->getLSDAReferenceKind(); + const std::vector& refs = this->getReferences(); + for (std::vector::const_iterator it=refs.begin(); it != refs.end(); it++) { + ObjectFile::Reference* ref = *it; + if ( (ref->getKind() == groupKind) && (ref->getTarget().getContentType() == ObjectFile::Atom::kLSDAType) ) { + return ref; + } + } + return NULL; +} + +ObjectFile::Reference* BaseAtom::getFDE() +{ + const uint8_t groupKind = this->getLSDAReferenceKind(); + const std::vector& refs = this->getReferences(); + for (std::vector::const_iterator it=refs.begin(); it != refs.end(); it++) { + ObjectFile::Reference* ref = *it; + if ( (ref->getKind() == groupKind) && (ref->getTarget().getContentType() == ObjectFile::Atom::kCFIType) ) { + return ref; + } + } + return NULL; +} + +ObjectFile::Atom* BaseAtom::getPersonalityPointer() +{ + const uint8_t personalityKind = this->getPersonalityReferenceKind(); + const std::vector& refs = this->getReferences(); + for (std::vector::const_iterator it=refs.begin(); it != refs.end(); it++) { + ObjectFile::Reference* ref = *it; + if ( ref->getKind() == personalityKind ) { + if ( strcmp(ref->getTarget().getSectionName(), "__nl_symbol_ptr") == 0 ) + return &ref->getTarget(); + if ( strcmp(ref->getTarget().getSectionName(), "__pointers") == 0 ) + return &ref->getTarget(); + } + } + return NULL; +} + + +void BaseAtom::setCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + fSingleUnwindInfo[0].unwindInfo = this->getCompactUnwindEncoding(ehAtomAddress); + fHasCompactUnwindInfo = true; +} + + class BaseAtomSorter { public: @@ -366,6 +436,7 @@ public: virtual ObjectFile::Atom::Scope getScope() const { return fScope; } virtual ObjectFile::Atom::DefinitionKind getDefinitionKind() const { return ((fSymbol->n_desc() & N_WEAK_DEF) != 0) ? ObjectFile::Atom::kWeakDefinition : ObjectFile::Atom::kRegularDefinition; } + virtual ObjectFile::Atom::ContentType getContentType() const { return fType; } virtual SymbolTableInclusion getSymbolTableInclusion() const { return fSymbolTableInclusion; } virtual bool dontDeadStrip() const; virtual bool isZeroFill() const { return ((fSection->flags() & SECTION_TYPE) == S_ZEROFILL); } @@ -384,8 +455,12 @@ public: virtual void addReference(ObjectFile::Reference* ref) { fReferences.push_back((Reference*)ref); } virtual void sortReferences() { std::sort(fReferences.begin(), fReferences.end(), ReferenceSorter()); } virtual void addLineInfo(const ObjectFile::LineInfo& info) { fLineInfo.push_back(info); } + virtual const ObjectFile::ReaderOptions& getOptions() const { return fOwner.fOptions; } virtual uint64_t getObjectAddress() const { return fAddress; } virtual const void* getSectionRecord() const { return (const void*)fSection; } + virtual uint8_t getLSDAReferenceKind() const; + virtual uint8_t getPersonalityReferenceKind() const; + virtual uint32_t getCompactUnwindEncoding(uint64_t ehAtomAddress); protected: typedef typename A::P P; @@ -410,14 +485,17 @@ protected: std::vector fLineInfo; ObjectFile::Atom::Scope fScope; SymbolTableInclusion fSymbolTableInclusion; + ObjectFile::Atom::ContentType fType; ObjectFile::Alignment fAlignment; }; template SymbolAtom::SymbolAtom(Reader& owner, const macho_nlist

* symbol, const macho_section

* section) - : fOwner(owner), fSymbol(symbol), fAddress(0), fSize(0), fSection(section), fSegment(NULL), fAlignment(0) + : fOwner(owner), fSymbol(symbol), fAddress(0), fSize(0), fSection(section), fSegment(NULL), fType(ObjectFile::Atom::kUnclassifiedType), fAlignment(0) { + fSingleUnwindInfo[0].startOffset = 0; + fSingleUnwindInfo[0].unwindInfo = 0; uint8_t type = symbol->n_type(); if ( (type & N_EXT) == 0 ) fScope = ObjectFile::Atom::scopeTranslationUnit; @@ -481,6 +559,7 @@ SymbolAtom::SymbolAtom(Reader& owner, const macho_nlist

* symbol, const break; case S_CSTRING_LITERALS: setSize(strlen((char*)(fOwner.fHeader) + section->offset() + fAddress - section->addr()) + 1); + fType = ObjectFile::Atom::kCStringType; break; case S_REGULAR: case S_ZEROFILL: @@ -496,24 +575,6 @@ SymbolAtom::SymbolAtom(Reader& owner, const macho_nlist

* symbol, const if ( (fSymbol->n_desc() & REFERENCED_DYNAMICALLY) != 0) { fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableInAndNeverStrip; } - else if ( fOwner.fOptions.fForFinalLinkedImage - && ((section->flags() & SECTION_TYPE) == S_COALESCED) - && ((section->flags() & S_ATTR_NO_TOC) == S_ATTR_NO_TOC) - && ((section->flags() & S_ATTR_STRIP_STATIC_SYMS) == S_ATTR_STRIP_STATIC_SYMS) - && (strcmp(section->sectname(), "__eh_frame") == 0) ) { - // .eh symbols exist so the linker can associate them with functions - // removing them from final linked images is a big space savings rdar://problem/4180168 - fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableNotIn; - // FDEs and CIEs are always packed together in a final linked image, so ignore section alignment - fAlignment = ObjectFile::Alignment(0); - } - else if ( fOwner.fOptions.fForFinalLinkedImage - && ((section->flags() & SECTION_TYPE) == S_REGULAR) - && (strncmp(section->sectname(), "__gcc_except_tab", 16) == 0) - && (strncmp(this->getName(), "GCC_except_table", 16) == 0) ) { - // GCC_except_table* symbols don't need to exist in final linked image - fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableNotIn; - } else if ( fOwner.fOptions.fForFinalLinkedImage && !fOwner.fOptions.fForStatic && (fOwner.fStrings[fSymbol->n_strx()] == 'l') ) { // labels beginning with a lowercase ell are automatically removed in final linked images // xnu code base uses a lot of asesembly labels that start with 'l', don't strip those (static executable) @@ -543,8 +604,24 @@ bool SymbolAtom::dontDeadStrip() const template const char* SymbolAtom::getSectionName() const { - if ( fOwner.fOptions.fForFinalLinkedImage && (strcmp(fSection->sectname(), "__textcoal_nt") == 0) ) - return "__text"; + if ( fOwner.fOptions.fForFinalLinkedImage ) { + if ( strcmp(fSection->sectname(), "__textcoal_nt") == 0 ) + return "__text"; + else if ( strcmp(fSection->sectname(), "__const_coal") == 0 ) + return "__const"; + else if ( strcmp(fSection->sectname(), "__datacoal_nt") == 0 ) + return "__data"; + else if ( fOwner.fOptions.fAutoOrderInitializers && (strcmp(fSection->sectname(), "__StaticInit") == 0) ) + return "__text"; + else { + switch ( fSection->flags() & SECTION_TYPE ) { + case S_4BYTE_LITERALS: + case S_8BYTE_LITERALS: + case S_16BYTE_LITERALS: + return "__const"; + } + } + } if ( strlen(fSection->sectname()) > 15 ) { static char temp[18]; @@ -601,6 +678,9 @@ void SymbolAtom::copyRawContent(uint8_t buffer[]) const } } + + + // // A SymbolAliasAtom represents an alternate name for a SymbolAtom // @@ -634,6 +714,7 @@ public: virtual void addReference(ObjectFile::Reference* ref) { fReferences.push_back((Reference*)ref); } virtual void sortReferences() { std::sort(fReferences.begin(), fReferences.end(), ReferenceSorter()); } virtual void addLineInfo(const ObjectFile::LineInfo& info) { } + virtual const ObjectFile::ReaderOptions& getOptions() const { return fAliasOf.getOptions(); } virtual uint64_t getObjectAddress() const { return fAliasOf.getObjectAddress(); } virtual const void* getSectionRecord() const { return fAliasOf.getSectionRecord(); } virtual bool isAlias() const { return true; } @@ -716,6 +797,7 @@ public: virtual void addReference(ObjectFile::Reference* ref) { throw "ld: can't add references"; } virtual void sortReferences() { } virtual void addLineInfo(const ObjectFile::LineInfo& info) { throw "ld: can't add line info to tentative definition"; } + virtual const ObjectFile::ReaderOptions& getOptions() const { return fOwner.fOptions; } virtual uint64_t getObjectAddress() const { return ULLONG_MAX; } virtual const void* getSectionRecord() const { return NULL; } @@ -812,6 +894,7 @@ public: virtual const char* getDisplayName() const; virtual ObjectFile::Atom::Scope getScope() const; virtual ObjectFile::Atom::DefinitionKind getDefinitionKind() const { return fKind; } + virtual ObjectFile::Atom::ContentType getContentType() const { return fType; } virtual ObjectFile::Atom::SymbolTableInclusion getSymbolTableInclusion() const { return fSymbolTableInclusion; } virtual bool dontDeadStrip() const { return fDontDeadStrip; } virtual bool isZeroFill() const; @@ -829,12 +912,16 @@ public: virtual void setSize(uint64_t size) { fSize = size; } virtual void addReference(ObjectFile::Reference* ref) { fReferences.push_back((Reference*)ref); } virtual void sortReferences() { std::sort(fReferences.begin(), fReferences.end(), ReferenceSorter()); } - virtual void addLineInfo(const ObjectFile::LineInfo& info) { warning("can't add line info to anonymous symbol %s from %s", this->getDisplayName(), this->getFile()->getPath()); } + virtual void addLineInfo(const ObjectFile::LineInfo& info); + virtual const ObjectFile::ReaderOptions& getOptions() const { return fOwner.fOptions; } virtual uint64_t getObjectAddress() const { return fAddress; } virtual const void* getSectionRecord() const { return (const void*)fSection; } BaseAtom* redirectTo() { return fRedirect; } bool isWeakImportStub() { return fWeakImportStub; } void resolveName(); + virtual uint8_t getLSDAReferenceKind() const; + virtual uint8_t getPersonalityReferenceKind() const; + virtual uint32_t getCompactUnwindEncoding(uint64_t ehAtomAddress); protected: typedef typename A::P P; @@ -864,13 +951,15 @@ protected: ObjectFile::Atom::SymbolTableInclusion fSymbolTableInclusion; ObjectFile::Atom::Scope fScope; ObjectFile::Atom::DefinitionKind fKind; + ObjectFile::Atom::ContentType fType; }; template AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* section, pint_t addr, pint_t size) : fOwner(owner), fSynthesizedName(NULL), fDisplayName(NULL), fSection(section), fAddress(addr), fSize(size), fSegment(NULL), fDontDeadStrip(true), fWeakImportStub(false), fSymbolTableInclusion(ObjectFile::Atom::kSymbolTableNotIn), - fScope(ObjectFile::Atom::scopeTranslationUnit), fKind(ObjectFile::Atom::kRegularDefinition) + fScope(ObjectFile::Atom::scopeTranslationUnit), fKind(ObjectFile::Atom::kRegularDefinition), + fType(ObjectFile::Atom::kUnclassifiedType) { fSegment = new Segment(fSection); fRedirect = this; @@ -884,7 +973,28 @@ AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* sectio break; case S_COALESCED: case S_REGULAR: - if ( (strcmp(section->sectname(), "__class") == 0) && (strcmp(section->segname(), "__OBJC") == 0) && owner.fAppleObjc ) { + if ( section == owner.fehFrameSection ) { + if ( fSize == 1 ) { + // is CIE + fSize = 0; + fDontDeadStrip = false; + if ( fOwner.fOptions.fForFinalLinkedImage ) + fSynthesizedName = "CIE"; + else + fSynthesizedName = "EH_frame1"; + } + else { + // is FDE + fSynthesizedName = ".eh_PENDING"; + fDontDeadStrip = false; + owner.fAtomsPendingAName.push_back(this); + } + fType = ObjectFile::Atom::kCFIType; + // FDEs and CIEs don't need to be in symbol table of final linked images + if ( !fOwner.fOptions.fNoEHLabels ) + fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableIn; + } + else if ( (strcmp(section->sectname(), "__class") == 0) && (strcmp(section->segname(), "__OBJC") == 0) && owner.fAppleObjc ) { // special case ObjC classes to synthesize .objc_class_name_* symbols, for Apple runtime only fSynthesizedName = ".objc_class_name_PENDING"; owner.fAtomsPendingAName.push_back(this); @@ -908,13 +1018,29 @@ AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* sectio fDontDeadStrip = false; fKind = ObjectFile::Atom::kWeakDefinition; } + else if ( (fSection->flags() & S_ATTR_SOME_INSTRUCTIONS) != 0 ) { + fDontDeadStrip = false; + asprintf((char**)&fSynthesizedName, "anon-func-0x%X", addr); + } + else if ( strncmp(fSection->sectname(), "__gcc_except_tab",16) == 0 ) { + fType = ObjectFile::Atom::kLSDAType; + fDontDeadStrip = false; + fSynthesizedName = ".lsda_PENDING"; + owner.fAtomsPendingAName.push_back(this); + if ( !fOwner.fOptions.fNoEHLabels ) + fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableIn; + } break; case S_CSTRING_LITERALS: { const char* str = (char*)(owner.fHeader) + section->offset() + addr - section->addr(); - asprintf((char**)&fSynthesizedName, "cstring=%s", str); + if ( (strcmp(fSection->sectname(), "__cstring") == 0) && (strcmp(section->segname(), "__TEXT") == 0) ) + asprintf((char**)&fSynthesizedName, "cstring=%s", str); + else + asprintf((char**)&fSynthesizedName, "cstring%s%s=%s", fSection->segname(), fSection->sectname(), str); fScope = ObjectFile::Atom::scopeLinkageUnit; fKind = ObjectFile::Atom::kWeakDefinition; + fType = ObjectFile::Atom::kCStringType; fDontDeadStrip = false; if ( !fOwner.fOptions.fForFinalLinkedImage && cstringsHaveLabels() ) fSymbolTableInclusion = ObjectFile::Atom::kSymbolTableIn; @@ -996,6 +1122,16 @@ AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* sectio case S_LAZY_SYMBOL_POINTERS: case S_NON_LAZY_SYMBOL_POINTERS: { + // transform i386 __IMPORT/__pointers to __DATA/__nl_symbol_ptr when + // generating the new compressed LINKEDIT format + if ( (type == S_NON_LAZY_SYMBOL_POINTERS) && fOwner.fOptions.fMakeCompressedDyldInfo && (strcmp(fSection->segname(),"__IMPORT") == 0) ) { + macho_section

* dummySection = new macho_section

(*fSection); + dummySection->set_segname("__DATA"); + dummySection->set_sectname("__nl_symbol_ptr"); + fSection = dummySection; + fSegment = new Segment(fSection); + } + fDontDeadStrip = false; fScope = ObjectFile::Atom::scopeLinkageUnit; uint32_t index = (fAddress - fSection->addr()) / sizeof(pint_t); @@ -1051,15 +1187,6 @@ AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* sectio strcat(str, "$non_lazy_ptr"); fSynthesizedName = str; - // optimize __IMPORT segment out of i386 dyld or if -slow_stubs is used - if ( (fOwner.fOptions.fForDyld || fOwner.fOptions.fSlowx86Stubs) && (strcmp(fSection->segname(),"__IMPORT") == 0) ) { - macho_section

* dummySection = new macho_section

(*fSection); - dummySection->set_segname("__DATA"); - dummySection->set_sectname("__nl_symbol_ptr"); - fSection = dummySection; - fSegment = new Segment(fSection); - } - if ( type == S_NON_LAZY_SYMBOL_POINTERS ) fKind = ObjectFile::Atom::kWeakDefinition; @@ -1086,6 +1213,13 @@ AnonymousAtom::AnonymousAtom(Reader& owner, const macho_section

* sectio template <> bool AnonymousAtom::cstringsHaveLabels() { return true; } template bool AnonymousAtom::cstringsHaveLabels() { return false; } +template +void AnonymousAtom::addLineInfo(const ObjectFile::LineInfo& info) +{ + // don't warn if line table has entries for stubs + if ( (fSection->flags() & SECTION_TYPE) != S_SYMBOL_STUBS ) + warning("can't add line info to anonymous symbol %s from %s", this->getDisplayName(), this->getFile()->getPath()); +} template void AnonymousAtom::resolveName() @@ -1096,7 +1230,7 @@ void AnonymousAtom::resolveName() for (std::vector::iterator rit=references.begin(); rit != references.end(); rit++) { if ( ((*rit)->getFixUpOffset() == sizeof(pint_t)) && ((*rit)->getKind() == A::kPointer) ) { const char* superStr = (*rit)->getTargetName(); - if ( strncmp(superStr, "cstring=", 8) == 0 ) { + if ( strncmp(superStr, "cstring", 7) == 0 ) { const char* superClassName; asprintf((char**)&superClassName, ".objc_class_name_%s", &superStr[8]); new Reference(A::kNoFixUp, AtomAndOffset(this), superClassName, 0); @@ -1107,7 +1241,7 @@ void AnonymousAtom::resolveName() for (std::vector::iterator rit=references.begin(); rit != references.end(); rit++) { if ( ((*rit)->getFixUpOffset() == 2*sizeof(pint_t)) && ((*rit)->getKind() == A::kPointer) ) { const char* classStr = (*rit)->getTargetName(); - if ( strncmp(classStr, "cstring=", 8) == 0 ) { + if ( strncmp(classStr, "cstring", 7) == 0 ) { asprintf((char**)&fSynthesizedName, ".objc_class_name_%s", &classStr[8]); } break; @@ -1120,7 +1254,7 @@ void AnonymousAtom::resolveName() throwf("S_LITERAL_POINTERS section %s,%s missing relocs", fSection->segname(), fSection->sectname()); ObjectFile::Reference* ref = references[0]; const char* str = ref->getTargetName(); - if ( strncmp(str, "cstring=", 8) == 0 ) { + if ( strncmp(str, "cstring", 7) == 0 ) { asprintf((char**)&fSynthesizedName, "literal-pointer@%s@%s@%s", fSection->segname(), fSection->sectname(), &str[8]); } } @@ -1135,17 +1269,28 @@ void AnonymousAtom::resolveName() } else { // compiled with -fwritable-strings or a non-ASCII string - ObjectFile::Atom& stringDataAtom = (*rit)->getTarget(); - uint8_t buffer[stringDataAtom.getSize()]; - stringDataAtom.copyRawContent(buffer); fKind = ObjectFile::Atom::kRegularDefinition; // these are not coalescable fScope = ObjectFile::Atom::scopeTranslationUnit; fSynthesizedName = "cfstring-not-coalesable"; + if ( (*rit)->getTargetOffset() != 0 ) + warning("-fwritable-strings not compatible with literal CF/NSString in %s", fOwner.getPath()); } break; } } } + else if ( fSection == fOwner.fehFrameSection ) { + // give name to FDE + ObjectFile::Atom* funcAtom = fOwner.getFunctionAtomFromFDEAddress(fAddress); + if ( funcAtom != NULL ) + asprintf((char**)&fSynthesizedName, "%s.eh", funcAtom->getDisplayName()); + } + else if ( fOwner.fLSDAAtoms.count(this) != 0) { + // give name to LSDA + ObjectFile::Atom* funcAtom = fOwner.getFunctionAtomFromLSDAAddress(fAddress); + if ( funcAtom != NULL ) + asprintf((char**)&fSynthesizedName, "%s.lsda", funcAtom->getDisplayName()); + } } @@ -1186,6 +1331,15 @@ bool AnonymousAtom::isZeroFill() const template const char* AnonymousAtom::getSectionName() const { + if ( fOwner.fOptions.fForFinalLinkedImage ) { + switch ( fSection->flags() & SECTION_TYPE ) { + case S_4BYTE_LITERALS: + case S_8BYTE_LITERALS: + case S_16BYTE_LITERALS: + return "__const"; + } + } + if ( strlen(fSection->sectname()) > 15 ) { static char temp[18]; strncpy(temp, fSection->sectname(), 16); @@ -1198,6 +1352,10 @@ const char* AnonymousAtom::getSectionName() const template ObjectFile::Alignment AnonymousAtom::getAlignment() const { + // FDEs and CIEs are always packed together in a final linked image, so ignore section alignment + if ( fType == ObjectFile::Atom::kCFIType ) + return ObjectFile::Alignment(0); + switch ( fSection->flags() & SECTION_TYPE ) { case S_4BYTE_LITERALS: return ObjectFile::Alignment(2); @@ -1239,7 +1397,6 @@ void AnonymousAtom::copyRawContent(uint8_t buffer[]) const } } - // // An AbsoluteAtom represents an N_ABS symbol which can only be created in // assembly language and usable by static executables such as the kernel/ @@ -1273,6 +1430,7 @@ public: virtual void addReference(ObjectFile::Reference* ref) { throw "ld: can't add references"; } virtual void sortReferences() { } virtual void addLineInfo(const ObjectFile::LineInfo& info) { throw "ld: can't add line info to tentative definition"; } + virtual const ObjectFile::ReaderOptions& getOptions() const { return fOwner.fOptions; } virtual uint64_t getObjectAddress() const { return fSymbol->n_value(); } virtual void setSectionOffset(uint64_t offset) { /* don't let fSectionOffset be altered*/ } virtual const void* getSectionRecord() const { return NULL; } @@ -1315,11 +1473,165 @@ AbsoluteAtom::AbsoluteAtom(Reader& owner, const macho_nlist

* symbol) + +/// +/// ObjectFileAddressSpace is used as a template parameter to UnwindCursor for parsing +/// dwarf CFI information in an object file. +/// +template +class ObjectFileAddressSpace +{ +public: + ObjectFileAddressSpace(Reader& reader); + + typedef typename A::P::uint_t pint_t; + typedef typename A::P P; + typedef typename A::P::uint_t sint_t; + + uint8_t get8(pint_t addr); + uint16_t get16(pint_t addr); + uint32_t get32(pint_t addr); + uint64_t get64(pint_t addr); + pint_t getP(pint_t addr); + uint64_t getULEB128(pint_t& addr, pint_t end); + int64_t getSLEB128(pint_t& addr, pint_t end); + pint_t getEncodedP(pint_t& addr, pint_t end, uint8_t encoding); +private: + const void* mappedAddress(pint_t addr, pint_t* relocTarget=NULL); + pint_t relocated(uint32_t sectOffset, uint32_t relocsOffset, uint32_t relocsCount); + void buildRelocatedMap(const macho_section

* sect, std::map& map); + + Reader& fReader; + const uint8_t* fMappingStart; + const macho_section

* fSectionsStart; + const macho_section

* fSectionsEnd; + std::map fEHFrameOffsetToTargetMap; +}; + + +template +ObjectFileAddressSpace::ObjectFileAddressSpace(Reader& reader) + : fReader(reader), fMappingStart(NULL), fSectionsStart(NULL), fSectionsEnd(NULL) +{ +} + + + +template +const void* ObjectFileAddressSpace::mappedAddress(pint_t addr, pint_t* relocTarget) +{ + if ( fMappingStart == NULL ) { + // delay initialization until now when fReader.fSegment is set up + fMappingStart = (uint8_t*)fReader.fHeader; + fSectionsStart = (macho_section

*)((char*)fReader.fSegment + sizeof(macho_segment_command

)); + fSectionsEnd = &fSectionsStart[fReader.fSegment->nsects()]; + // find __eh_frame section and build map of relocations for performance + buildRelocatedMap(fReader.fehFrameSection, fEHFrameOffsetToTargetMap); + } + // special case lookups in __eh_frame section to be fast + const macho_section

* ehSect = fReader.fehFrameSection; + if ( (ehSect->addr() <= addr) && (addr < (ehSect->addr()+ehSect->size())) ) { + pint_t offsetOfAddrInSection = addr - ehSect->addr(); + if ( relocTarget != NULL ) { + std::map::iterator pos = fEHFrameOffsetToTargetMap.find(offsetOfAddrInSection); + if ( pos != fEHFrameOffsetToTargetMap.end() ) + *relocTarget = pos->second; + else + *relocTarget = 0; + } + return fMappingStart + ehSect->offset() + offsetOfAddrInSection; + } + else { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { + if ( (sect->addr() <= addr) && (addr < (sect->addr()+sect->size())) ) { + pint_t offsetOfAddrInSection = addr - sect->addr(); + if ( (sect->flags() & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS ) { + const uint32_t indirectTableOffset = sect->reserved1(); + const uint32_t sectionIndex = offsetOfAddrInSection/sizeof(pint_t); + const uint32_t symbolIndex = A::P::E::get32(fReader.fIndirectTable[indirectTableOffset+sectionIndex]); + // return pointer to symbol name which this non-lazy-pointer will point to + if ( relocTarget != NULL ) + *relocTarget = (uintptr_t)&fReader.fStrings[fReader.fSymbols[symbolIndex].n_strx()]; + } + else { + if ( relocTarget != NULL ) + *relocTarget = relocated(offsetOfAddrInSection, sect->reloff(), sect->nreloc()); + } + return fMappingStart + sect->offset() + offsetOfAddrInSection; + } + } + throwf("ObjectFileAddressSpace::mappedAddress(0x%0lX) not in any section", (long)addr); + } +} + + + + +template +uint8_t ObjectFileAddressSpace::get8(pint_t logicalAddr) +{ + return *((uint8_t*)mappedAddress(logicalAddr)); +} + +template +uint16_t ObjectFileAddressSpace::get16(pint_t logicalAddr) +{ + return P::E::get16(*((uint16_t*)mappedAddress(logicalAddr))); +} + +template +uint32_t ObjectFileAddressSpace::get32(pint_t logicalAddr) +{ + pint_t relocTarget; + return P::E::get32(*((uint32_t*)mappedAddress(logicalAddr, &relocTarget))) + relocTarget; +} + +template +uint64_t ObjectFileAddressSpace::get64(pint_t logicalAddr) +{ + pint_t relocTarget; + return P::E::get64(*((uint64_t*)mappedAddress(logicalAddr, &relocTarget))) + relocTarget; +} + +template +typename A::P::uint_t ObjectFileAddressSpace::getP(pint_t logicalAddr) +{ + pint_t relocTarget; + return P::getP(*((pint_t*)mappedAddress(logicalAddr, &relocTarget))) + relocTarget; +} + +template +uint64_t ObjectFileAddressSpace::getULEB128(pint_t& logicalAddr, pint_t end) +{ + uintptr_t size = (end - logicalAddr); + libunwind::LocalAddressSpace::pint_t laddr = (libunwind::LocalAddressSpace::pint_t)mappedAddress(logicalAddr); + libunwind::LocalAddressSpace::pint_t sladdr = laddr; + uint64_t result = libunwind::LocalAddressSpace::getULEB128(laddr, laddr+size); + logicalAddr += (laddr-sladdr); + return result; +} + +template +int64_t ObjectFileAddressSpace::getSLEB128(pint_t& logicalAddr, pint_t end) +{ + uintptr_t size = (end - logicalAddr); + libunwind::LocalAddressSpace::pint_t laddr = (libunwind::LocalAddressSpace::pint_t)mappedAddress(logicalAddr); + libunwind::LocalAddressSpace::pint_t sladdr = laddr; + int64_t result = libunwind::LocalAddressSpace::getSLEB128(laddr, laddr+size); + logicalAddr += (laddr-sladdr); + return result; +} + + + + + + template class Reader : public ObjectFile::Reader { public: - static bool validFile(const uint8_t* fileContent); + static bool validFile(const uint8_t* fileContent, bool subtypeMustMatch=false, cpu_subtype_t subtype=0); Reader(const uint8_t* fileContent, const char* path, time_t modTime, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase); virtual ~Reader() {} @@ -1345,6 +1657,10 @@ private: //typedef typename std::vector*> AtomVector; //typedef typename AtomVector::iterator AtomVectorIterator; // seems to help C++ parser typedef typename A::ReferenceKinds Kinds; + typedef typename libunwind::CFI_Parser >::FDE_Atom_Info FDE_Atom_Info; + typedef typename libunwind::CFI_Parser >::CIE_Atom_Info CIE_Atom_Info; + typedef class ObjectFileAddressSpace OAS; + friend class ObjectFileAddressSpace; friend class AnonymousAtom; friend class TentativeAtom; friend class AbsoluteAtom; @@ -1354,6 +1670,7 @@ private: void addReferencesForSection(const macho_section

* sect); bool addRelocReference(const macho_section

* sect, const macho_relocation_info

* reloc); bool addRelocReference_powerpc(const macho_section

* sect, const macho_relocation_info

* reloc); + const char* getDwarfString(uint64_t form, const uint8_t* p); bool read_comp_unit(const char ** name, const char ** comp_dir, uint64_t *stmt_list); static bool isWeakImportSymbol(const macho_nlist

* sym); static bool skip_form(const uint8_t ** offset, const uint8_t * end, uint64_t form, uint8_t addr_size, bool dwarf64); @@ -1365,11 +1682,18 @@ private: Reference* makeReferenceWithToBase(Kinds kind, pint_t atAddr, pint_t toAddr, pint_t toBaseAddr); Reference* makeReferenceWithToBase(Kinds kind, pint_t atAddr, pint_t fromAddr, pint_t toAddr, pint_t toBaseAddr); Reference* makeByNameReference(Kinds kind, pint_t atAddr, const char* toName, uint32_t toOffset); - Reference* makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect); + BaseAtom* makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect); Reference* makeReferenceToSymbol(Kinds kind, pint_t atAddr, const macho_nlist

* toSymbol, pint_t toOffset); void validSectionType(uint8_t type); void addDtraceExtraInfos(uint32_t probeAddr, const char* providerName); void setCpuConstraint(uint32_t cpusubtype); + const macho_section

* getSectionForAddress(pint_t); + ObjectFile::Atom* getFunctionAtomFromFDEAddress(pint_t); + ObjectFile::Atom* getFunctionAtomFromLSDAAddress(pint_t); + void addFdeReference(uint8_t encoding, AtomAndOffset inFDE, AtomAndOffset target); + void addCiePersonalityReference(BaseAtom* cieAtom, uint32_t offsetInCIE, uint8_t encoding); + bool isSectDiffReloc(uint8_t r_type); + BaseAtom* findAtomByName(const char*); @@ -1392,13 +1716,18 @@ private: std::vector fDtraceProviderInfo; ObjectFile::Reader::DebugInfoKind fDebugInfo; bool fHasUUID; + const macho_section

* fehFrameSection; + std::set fLSDAAtoms; const macho_section

* fDwarfDebugInfoSect; const macho_section

* fDwarfDebugAbbrevSect; const macho_section

* fDwarfDebugLineSect; + const macho_section

* fDwarfDebugStringSect; const char* fDwarfTranslationUnitDir; const char* fDwarfTranslationUnitFile; std::map fDwarfIndexToFile; std::vector fStabs; + std::vector fFDEInfos; + std::vector fCIEInfos; bool fAppleObjc; bool fHasDTraceProbes; bool fHaveIndirectSymbols; @@ -1406,19 +1735,24 @@ private: bool fHasLongBranchStubs; ObjectFile::Reader::ObjcConstraint fObjConstraint; uint32_t fCpuConstraint; + const macho_section

* fSectionsStart; + const macho_section

* fSectionsEnd; + OAS fObjectAddressSpace; }; template Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, const ObjectFile::ReaderOptions& options, uint32_t ordinalBase) : fPath(strdup(path)), fModTime(modTime), fOrdinalBase(ordinalBase), fOptions(options), fHeader((const macho_header

*)fileContent), fStrings(NULL), fSymbols(NULL), fSymbolCount(0), fSegment(NULL), fIndirectTable(NULL), - fDebugInfo(kDebugInfoNone), fHasUUID(false), fDwarfDebugInfoSect(NULL), fDwarfDebugAbbrevSect(NULL), fDwarfDebugLineSect(NULL), + fDebugInfo(kDebugInfoNone), fHasUUID(false), fehFrameSection(NULL), + fDwarfDebugInfoSect(NULL), fDwarfDebugAbbrevSect(NULL), fDwarfDebugLineSect(NULL), fDwarfTranslationUnitDir(NULL), fDwarfTranslationUnitFile(NULL), fAppleObjc(false), fHasDTraceProbes(false), fHaveIndirectSymbols(false), fReplacementClasses(false), fHasLongBranchStubs(false), - fObjConstraint(ObjectFile::Reader::kObjcNone), fCpuConstraint(ObjectFile::Reader::kCpuAny) + fObjConstraint(ObjectFile::Reader::kObjcNone), fCpuConstraint(ObjectFile::Reader::kCpuAny), + fSectionsStart(NULL), fSectionsEnd(NULL), fObjectAddressSpace(*this) { // sanity check - if ( ! validFile(fileContent) ) + if ( ! validFile(fileContent, false, 0) ) throw "not a valid mach-o object file"; Reference::fgForFinalLinkedImage = options.fForFinalLinkedImage; @@ -1477,24 +1811,63 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, if ( header->ncmds() < 1 ) return; - const macho_section

* const sectionsStart = (macho_section

*)((char*)fSegment + sizeof(macho_segment_command

)); - const macho_section

* const sectionsEnd = §ionsStart[fSegment->nsects()]; + fSectionsStart = (macho_section

*)((char*)fSegment + sizeof(macho_segment_command

)); + fSectionsEnd = &fSectionsStart[fSegment->nsects()]; // inital guess for number of atoms fAtoms.reserve(fSymbolCount); + // if there is an __eh_frame section, decode it into chunks to get atoms in that + // section as well as division points for functions in __text + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { + if ( (strcmp(sect->sectname(), "__eh_frame") == 0) && (strcmp(sect->segname(), "__TEXT") == 0) ) { + fehFrameSection = sect; + const char* msg = libunwind::CFI_Parser >::getCFIs(fObjectAddressSpace, sect->addr(), + sect->size(), fFDEInfos, fCIEInfos); + if ( msg != NULL ) { + throwf("malformed __eh_frame section: %s", msg); + } + else { + //fprintf(stderr, "%lu CIEs, %lu FDEs\n", fCIEInfos.size(), fFDEInfos.size()); + // add anonymous atoms for each CIE + for (typename std::vector::const_iterator it = fCIEInfos.begin(); it != fCIEInfos.end(); ++it) { + AnonymousAtom* cieAtom = new AnonymousAtom(*this, sect, it->cieAddress, 1); + fAtoms.push_back(cieAtom); + fAddrToAtom[it->cieAddress] = cieAtom; + } + // add anonymous atoms for each FDE and LSDA + for (typename std::vector::const_iterator it = fFDEInfos.begin(); it != fFDEInfos.end(); ++it) { + //fprintf(stderr, "fdeAddress=0x%08llX, lsdaAddr=0x%08llX, funcAddr=0x%08llX\n", (uint64_t)it->fdeAddress, (uint64_t)it->lsda.address, (uint64_t)it->function.address); + AnonymousAtom* fdeAtom = new AnonymousAtom(*this, sect, it->fdeAddress, 0); + fAtoms.push_back(fdeAtom); + fAddrToAtom[it->fdeAddress] = fdeAtom; + if ( it->lsda.address != 0 ) { + AnonymousAtom* lsdaAtom = new AnonymousAtom(*this, getSectionForAddress(it->lsda.address), it->lsda.address, 0); + fAtoms.push_back(lsdaAtom); + fAddrToAtom[it->lsda.address] = lsdaAtom; + fLSDAAtoms.insert(lsdaAtom); + } + } + } + } + } + + // add all atoms that have entries in symbol table - const macho_section

* sections = (macho_section

*)((char*)fSegment + sizeof(macho_segment_command

)); + BaseAtom* sectionEndAtoms[fSegment->nsects()]; + for (unsigned int i=0; i < fSegment->nsects(); ++i) + sectionEndAtoms[i] = NULL; for (int i=fSymbolCount-1; i >= 0 ; --i) { - // walk backwards through symbol table so globals are see before locals, otherwise a local alias would beome the reaal name + // walk backwards through symbol table so globals are see before locals, otherwise a local alias would beome the real name const macho_nlist

& sym = fSymbols[i]; if ( (sym.n_type() & N_STAB) == 0 ) { uint8_t type = (sym.n_type() & N_TYPE); if ( type == N_SECT ) { - const macho_section

* section = §ions[sym.n_sect()-1]; - pint_t sectionEndAddr = section->addr() + section->size(); + const macho_section

* section = &fSectionsStart[sym.n_sect()-1]; + const pint_t sectionStartAddr = section->addr(); + const pint_t sectionEndAddr = sectionStartAddr + section->size(); bool suppress = false; - // ignore atoms in debugger sections + // ignore atoms in debugger sections if ( (section->flags() & S_ATTR_DEBUG) == 0 ) { if ( strncmp(&fStrings[sym.n_strx()], "__dtrace_probe$", 15) == 0 ) { // ignore dtrace probe labels @@ -1503,6 +1876,9 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, else if ( fStrings[sym.n_strx()] == 'L' ) { // ignore L labels, } + else if ( section == fehFrameSection ) { + // ignore labels in __eh_frame section + } else { // ignore labels for atoms in other sections switch ( section->flags() & SECTION_TYPE ) { @@ -1518,16 +1894,39 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, { BaseAtom* newAtom; typename AddrToAtomMap::iterator pos = fAddrToAtom.find(sym.n_value()); - if ( (pos != fAddrToAtom.end()) && (strcmp(pos->second->getSectionName(), section->sectname())==0) ) { - // another label to an existing address in the same section, make this an alias - newAtom = new SymbolAliasAtom(&fStrings[sym.n_strx()], &sym, *pos->second); + if ( (pos != fAddrToAtom.end()) && (pos->second->getSectionRecord() == section) ) { + if ( fLSDAAtoms.count(pos->second) != 0 ) { + // already have LSDA atom from for this address, ignore compiler's label + suppress = true; + break; + } + else { + // another label to an existing address in the same section, make this an alias + newAtom = new SymbolAliasAtom(&fStrings[sym.n_strx()], &sym, *pos->second); + } } else { - // make SymbolAtom atom for this address - newAtom = new SymbolAtom(*this, &sym, section); - // don't add symbols at end of section to addr->atom map - if ( sym.n_value() != sectionEndAddr ) + if ( sym.n_value() == sectionEndAddr ) { + // Symbol address is at end of section. This can interfere + // with a symbol at the start of the next section, so don't + // add to fAddrToAtom. But do track in sectionEndAtoms so we + // still make aliases if there are duplicates. + if ( sectionEndAtoms[sym.n_sect()-1] == NULL ) { + newAtom = new SymbolAtom(*this, &sym, section); + sectionEndAtoms[sym.n_sect()-1] = newAtom; + // if this is a zero length section, so add to fAddrToAtom + if ( sym.n_value() == sectionStartAddr ) + fAddrToAtom[newAtom->getObjectAddress()] = newAtom; + } + else { + newAtom = new SymbolAliasAtom(&fStrings[sym.n_strx()], &sym, *sectionEndAtoms[sym.n_sect()-1]); + } + } + else { + // make SymbolAtom atom for this address + newAtom = new SymbolAtom(*this, &sym, section); fAddrToAtom[newAtom->getObjectAddress()] = newAtom; + } } if ( ! suppress ) fAtoms.push_back(newAtom); @@ -1569,8 +1968,29 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } } + // add anonymous atoms for any functions (as determined by dwarf unwind) have no symbol names + if ( fehFrameSection != NULL ) { + for (typename std::vector::const_iterator it = fFDEInfos.begin(); it != fFDEInfos.end(); ++it) { + // add if not already an atom at that address + if ( fAddrToAtom.find(it->function.address) == fAddrToAtom.end() ) { + AnonymousAtom* funcAtom = new AnonymousAtom(*this, getSectionForAddress(it->function.address), it->function.address, 0); + fAtoms.push_back(funcAtom); + fAddrToAtom[it->function.address] = funcAtom; + // even though we've made a new atom, be conservative and make sure they lay out together + if ( canScatterAtoms() ) { + AtomAndOffset prev = findAtomAndOffset(it->function.address-1); + if ( prev.atom != NULL ) { + if ( ((BaseAtom*)(prev.atom))->getSectionRecord() == funcAtom->getSectionRecord() ) + new Reference(A::kFollowOn, prev, AtomAndOffset(funcAtom)); + } + } + } + } + } + + // add all fixed size anonymous atoms from special sections - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { pint_t atomSize = 0; uint8_t type (sect->flags() & SECTION_TYPE); validSectionType(type); @@ -1659,7 +2079,7 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } // add all c-string anonymous atoms - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { if ( ((sect->flags() & SECTION_TYPE) == S_CSTRING_LITERALS) || strcmp(sect->sectname(), "__cstring") == 0 ) { uint32_t stringLen; pint_t stringAddr; @@ -1709,10 +2129,11 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, // fprintf(stderr, "0x%08llX %s\n", (*it)->getObjectAddress(), (*it)->getDisplayName()); // create atoms to cover any non-debug ranges not handled above - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { pint_t sectionStartAddr = sect->addr(); pint_t sectionEndAddr = sect->addr() + sect->size(); - const bool setFollowOnAtom = ! this->canScatterAtoms(); + // don't set follow-on atoms in __eh_frame section + const bool setFollowOnAtom = !canScatterAtoms() && (sect != fehFrameSection); if ( sect->size() != 0 ) { // ignore dwarf sections. If ld every supports processing dwarf, this logic will need to change if ( (sect->flags() & S_ATTR_DEBUG) != 0 ) { @@ -1723,6 +2144,8 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, fDwarfDebugAbbrevSect = sect; else if ( strcmp(sect->sectname(), "__debug_line") == 0 ) fDwarfDebugLineSect = sect; + else if ( strcmp(sect->sectname(), "__debug_str") == 0 ) + fDwarfDebugStringSect = sect; } else { if ( strcmp(sect->segname(), "__DWARFA") == 0 ) { @@ -1793,7 +2216,7 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } // add relocation based references to sections that have atoms with pending names - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { if ( fSectionsWithAtomsPendingAName.count(sect) != 0 ) addReferencesForSection(sect); } @@ -1804,14 +2227,14 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } // add relocation based references to other sections - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { if ( fSectionsWithAtomsPendingAName.count(sect) == 0 ) addReferencesForSection(sect); } // add objective-c references if ( fAppleObjc ) { - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { if ( (strcmp(sect->sectname(), "__cls_refs") == 0) && (strcmp(sect->segname(), "__OBJC") == 0) ) { for (uint32_t offset = 0; offset < sect->size(); offset += sizeof(pint_t)) { AtomAndOffset ao = this->findAtomAndOffset(sect->addr()+offset); @@ -1837,44 +2260,62 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, makeReference(A::kPointer, localNonLazy->fAddress, nonLazyPtrValue); } - // add implicit direct reference from each C++ function to its eh info - for (const macho_section

* sect=sectionsStart; sect < sectionsEnd; ++sect) { - if ( ((sect->flags() & SECTION_TYPE) == S_COALESCED) && (strcmp(sect->sectname(), "__eh_frame") == 0) ) { - for (typename AddrToAtomMap::iterator it=fAddrToAtom.begin(); it != fAddrToAtom.end(); it++) { - // note: this algorithm depens on the map iterator returning entries in address order - if ( (it->first >= sect->addr()) && (it->first < sect->addr()+sect->size()) ) { - pint_t ehAtomAddress = it->first; - BaseAtom* ehAtom = it->second; - const char* ehName = ehAtom->getName(); - if ( (ehName != NULL) && (strcmp(&ehName[strlen(ehName)-3], ".eh") == 0) ) { - makeReferenceToEH(ehName, ehAtomAddress, sect); - // make EH symbol static so linker does not try to coalesce - if ( fOptions.fForFinalLinkedImage ) - ehAtom->setScope(ObjectFile::Atom::scopeTranslationUnit); - // if it has a reference to a LSDA, add a group reference - std::vector& ehrefs = ehAtom->getReferences(); - // all FDE's have at least 2 references (to CIE and to function) - if ( ehrefs.size() > 2 ) { - // a third reference means there is a LSDA - ObjectFile::Atom* lsdaAtom = NULL; - for (std::vector::iterator rit=ehrefs.begin(); rit != ehrefs.end(); rit++) { - ObjectFile::Reference* ref = *rit; - switch ( ref->getFixUpOffset() ) { - case 4: - case 8: - // these are CIE and function references - break; - default: - // this is LSDA reference - lsdaAtom = &ref->getTarget(); - } - } - if ( lsdaAtom != NULL ) { - new Reference(A::kGroupSubordinate, AtomAndOffset(ehAtom), AtomAndOffset(lsdaAtom)); - } - } - } - } + + // add personality references to CIEs + for (typename std::vector::const_iterator it = fCIEInfos.begin(); it != fCIEInfos.end(); ++it) { + if ( it->personality.offsetInFDE != 0 ) + addCiePersonalityReference(fAddrToAtom[it->cieAddress], it->personality.offsetInFDE, it->personality.encodingOfAddress); + } + + // add all references for FDEs, including implicit group references + for (typename std::vector::const_iterator it = fFDEInfos.begin(); it != fFDEInfos.end(); ++it) { + AtomAndOffset funcAO = this->findAtomAndOffset(it->function.address); + if ( funcAO.offset != 0 ) + warning("FDE does not point to start of function %s\n", funcAO.atom->getDisplayName()); + AtomAndOffset fdeAO = this->findAtomAndOffset(it->fdeAddress); + if ( fdeAO.offset != 0 ) + warning("FDE does start its own atom %s\n", funcAO.atom->getDisplayName()); + AtomAndOffset cieAO = this->findAtomAndOffset(it->cie.address); + if ( cieAO.offset != 0 ) + warning("CIE does start its own atom %s\n", cieAO.atom->getDisplayName()); + AtomAndOffset lsdaAO; + if ( it->lsda.address != 0 ) { + lsdaAO = this->findAtomAndOffset(it->lsda.address); + if ( lsdaAO.offset != 0 ) + warning("LSDA does start its own atom %s\n", lsdaAO.atom->getDisplayName()); + } + + // add reference from FDE to CIE + AtomAndOffset cieInfdeAO = AtomAndOffset(fdeAO.atom, it->cie.offsetInFDE); + new Reference(A::kPointerDiff32, cieInfdeAO, cieAO, cieInfdeAO); + + // add reference from FDE to function + addFdeReference(it->function.encodingOfAddress, AtomAndOffset(fdeAO.atom, it->function.offsetInFDE), funcAO); + + // add reference from FDE to LSDA + if ( it->lsda.address != 0 ) { + addFdeReference(it->lsda.encodingOfAddress, AtomAndOffset(fdeAO.atom, it->lsda.offsetInFDE), lsdaAO); + } + + // FDE is in group lead by function atom + new Reference(A::kGroupSubordinate, funcAO, fdeAO); + + // LSDA is in group lead by function atom + if ( it->lsda.address != 0 ) { + new Reference(A::kGroupSubordinate, funcAO, lsdaAO); + // add back reference from LSDA to owning function + new Reference(A::kNoFixUp, lsdaAO, funcAO); + } + + // compute compact encoding for this FDE + if ( fOptions.fAddCompactUnwindEncoding ) { + ((BaseAtom*)(funcAO.atom))->setCompactUnwindEncoding(it->fdeAddress); + // add reference from function atom to personality function + // the only reference a CIE can have is the reference to the personality function + std::vector& cieRefs = cieAO.atom->getReferences(); + if ( cieRefs.size() == 1 ) { + new Reference((typename A::ReferenceKinds)((BaseAtom*)(funcAO.atom))->getPersonalityReferenceKind(), + funcAO, cieRefs[0]->getTargetName(), 0); } } } @@ -1902,7 +2343,7 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } } - // turn indirect symbols int SymbolAliasAtom + // turn indirect symbols into SymbolAliasAtom if ( fHaveIndirectSymbols ) { for (uint32_t i=0; i < fSymbolCount; ++i) { const macho_nlist

& sym = fSymbols[i]; @@ -1957,36 +2398,43 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, uint32_t curAtomOffset = 0; uint32_t curAtomAddress = 0; uint32_t curAtomSize = 0; - while ( line_next (lines, &result, line_stop_pc) ) { - //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d, curAtomAddress=0x%X, curAtomSize=0x%X\n", - // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize); - // work around weird debug line table compiler generates if no functions in __text section - if ( (curAtom == NULL) && (result.pc == 0) && result.end_of_sequence && (result.file == 1)) - continue; - // for performance, see if in next pc is in current atom - if ( (curAtom != NULL) && (curAtomAddress <= result.pc) && (result.pc < (curAtomAddress+curAtomSize)) ) { - curAtomOffset = result.pc - curAtomAddress; - } - // or pc at end of current atom - else if ( result.end_of_sequence && (curAtom != NULL) && (result.pc == (curAtomAddress+curAtomSize)) ) { - curAtomOffset = result.pc - curAtomAddress; - } - else { - // do slow look up of atom by address - AtomAndOffset ao = this->findAtomAndOffset(result.pc); - curAtom = ao.atom; - if ( curAtom == NULL ) - break; // file has line info but no functions - if ( result.end_of_sequence && (curAtomAddress+curAtomSize < result.pc) ) { - // a one line function can be returned by line_next() as one entry with pc at end of blob - // look for alt atom starting at end of previous atom - uint32_t previousEnd = curAtomAddress+curAtomSize; - AtomAndOffset alt = this->findAtomAndOffset(previousEnd); - if ( result.pc <= previousEnd - alt.offset + alt.atom->getSize() ) { - curAtom = alt.atom; - curAtomOffset = alt.offset; - curAtomAddress = previousEnd - alt.offset; - curAtomSize = curAtom->getSize(); + if ( lines != NULL ) { + while ( line_next (lines, &result, line_stop_pc) ) { + //fprintf(stderr, "curAtom=%p, result.pc=0x%llX, result.line=%llu, result.end_of_sequence=%d, curAtomAddress=0x%X, curAtomSize=0x%X\n", + // curAtom, result.pc, result.line, result.end_of_sequence, curAtomAddress, curAtomSize); + // work around weird debug line table compiler generates if no functions in __text section + if ( (curAtom == NULL) && (result.pc == 0) && result.end_of_sequence && (result.file == 1)) + continue; + // for performance, see if in next pc is in current atom + if ( (curAtom != NULL) && (curAtomAddress <= result.pc) && (result.pc < (curAtomAddress+curAtomSize)) ) { + curAtomOffset = result.pc - curAtomAddress; + } + // or pc at end of current atom + else if ( result.end_of_sequence && (curAtom != NULL) && (result.pc == (curAtomAddress+curAtomSize)) ) { + curAtomOffset = result.pc - curAtomAddress; + } + else { + // do slow look up of atom by address + AtomAndOffset ao = this->findAtomAndOffset(result.pc); + curAtom = ao.atom; + if ( curAtom == NULL ) + break; // file has line info but no functions + if ( result.end_of_sequence && (curAtomAddress+curAtomSize < result.pc) ) { + // a one line function can be returned by line_next() as one entry with pc at end of blob + // look for alt atom starting at end of previous atom + uint32_t previousEnd = curAtomAddress+curAtomSize; + AtomAndOffset alt = this->findAtomAndOffset(previousEnd); + if ( result.pc <= previousEnd - alt.offset + alt.atom->getSize() ) { + curAtom = alt.atom; + curAtomOffset = alt.offset; + curAtomAddress = previousEnd - alt.offset; + curAtomSize = curAtom->getSize(); + } + else { + curAtomOffset = ao.offset; + curAtomAddress = result.pc - ao.offset; + curAtomSize = curAtom->getSize(); + } } else { curAtomOffset = ao.offset; @@ -1994,33 +2442,28 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, curAtomSize = curAtom->getSize(); } } + const char* filename; + std::map::iterator pos = fDwarfIndexToFile.find(result.file); + if ( pos == fDwarfIndexToFile.end() ) { + filename = line_file(lines, result.file); + fDwarfIndexToFile[result.file] = filename; + } else { - curAtomOffset = ao.offset; - curAtomAddress = result.pc - ao.offset; - curAtomSize = curAtom->getSize(); + filename = pos->second; + } + ObjectFile::LineInfo info; + info.atomOffset = curAtomOffset; + info.fileName = filename; + info.lineNumber = result.line; + //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n", + // result.pc, result.line, filename, curAtom->getDisplayName(), curAtomSize, result.end_of_sequence); + ((BaseAtom*)curAtom)->addLineInfo(info); + if ( result.end_of_sequence ) { + curAtom = NULL; } } - const char* filename; - std::map::iterator pos = fDwarfIndexToFile.find(result.file); - if ( pos == fDwarfIndexToFile.end() ) { - filename = line_file(lines, result.file); - fDwarfIndexToFile[result.file] = filename; - } - else { - filename = pos->second; - } - ObjectFile::LineInfo info; - info.atomOffset = curAtomOffset; - info.fileName = filename; - info.lineNumber = result.line; - //fprintf(stderr, "addr=0x%08llX, line=%lld, file=%s, atom=%s, atom.size=0x%X, end=%d\n", - // result.pc, result.line, filename, curAtom->getDisplayName(), curAtomSize, result.end_of_sequence); - ((BaseAtom*)curAtom)->addLineInfo(info); - if ( result.end_of_sequence ) { - curAtom = NULL; - } - } line_free(lines); + } } else { warning("could not parse dwarf line number info in %s", this->getPath()); @@ -2106,7 +2549,9 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, } } if ( stab.atom == NULL ) { - warning("can't find atom for N_GSYM stabs %s in %s", symString, path); + // ld_classic added bogus GSYM stabs for old style dtrace probes + if ( (strncmp(symString, "__dtrace_probe$", 15) != 0) ) + warning("can't find atom for N_GSYM stabs %s in %s", symString, path); useStab = false; } break; @@ -2230,22 +2675,536 @@ Reader::Reader(const uint8_t* fileContent, const char* path, time_t modTime, fAtoms.push_back(phony); } } -#endif +#endif + + // sort all atoms by address + std::sort(fAtoms.begin(), fAtoms.end(), BaseAtomSorter()); + + // set ordinal and sort references in each atom + uint32_t index = fOrdinalBase; + for (std::vector::iterator it=fAtoms.begin(); it != fAtoms.end(); it++) { + BaseAtom* atom = (BaseAtom*)(*it); + atom->setOrdinal(index++); + atom->sortReferences(); + } + +} + +template +const macho_section* Reader::getSectionForAddress(pint_t addr) +{ + for (const macho_section

* sect=fSectionsStart; sect < fSectionsEnd; ++sect) { + if ( (sect->addr() <= addr) && (addr < (sect->addr()+sect->size())) ) + return sect; + } + throwf("section not found for address 0x%08llX", (uint64_t)addr); +} + +template +ObjectFile::Atom* Reader::getFunctionAtomFromFDEAddress(pint_t addr) +{ + for (typename std::vector::const_iterator it = fFDEInfos.begin(); it != fFDEInfos.end(); ++it) { + if ( it->fdeAddress == addr ) { + return findAtomAndOffset(it->function.address).atom; + } + } + // CIEs won't be in fFDEInfos + return NULL; +} + +template +ObjectFile::Atom* Reader::getFunctionAtomFromLSDAAddress(pint_t addr) +{ + for (typename std::vector::const_iterator it = fFDEInfos.begin(); it != fFDEInfos.end(); ++it) { + if ( it->lsda.address == addr ) { + return findAtomAndOffset(it->function.address).atom; + } + } + return NULL; +} + + +template <> +void ObjectFileAddressSpace::buildRelocatedMap(const macho_section

* sect, std::map& map) +{ + // mach-o x86_64 is different, the content of a section with a relocation is the addend + const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fReader.fHeader) + sect->reloff()); + const macho_relocation_info

* relocsEnd = &relocs[sect->nreloc()]; + for (const macho_relocation_info

* reloc = relocs; reloc < relocsEnd; ++reloc) { + std::map::iterator pos; + switch ( reloc->r_type() ) { + case X86_64_RELOC_UNSIGNED: + pos = map.find(reloc->r_address()); + if ( pos != map.end() ) + pos->second += fReader.fSymbols[reloc->r_symbolnum()].n_value(); + else + map[reloc->r_address()] = fReader.fSymbols[reloc->r_symbolnum()].n_value(); + break; + case X86_64_RELOC_SUBTRACTOR: + map[reloc->r_address()] = -fReader.fSymbols[reloc->r_symbolnum()].n_value(); + break; + case X86_64_RELOC_GOT: + // there is no good address to return here. + // GOT slots are synthsized by the linker + // this is used for the reference to the personality function in CIEs + map[reloc->r_address()] = 0; + break; + default: + fprintf(stderr, "ObjectFileAddressSpace::buildRelocatedMap() unexpected relocation at r_address=0x%08X\n", reloc->r_address()); + break; + } + } +} + +template +void ObjectFileAddressSpace::buildRelocatedMap(const macho_section

* sect, std::map& map) +{ + // in all architectures except x86_64, the section contents are already fixed up to point + // to content in the same object file. +} + +template <> +uint64_t ObjectFileAddressSpace::relocated(uint32_t sectOffset, uint32_t relocsOffset, uint32_t relocsCount) +{ + // mach-o x86_64 is different, the content of a section with a relocation is the addend + uint64_t result = 0; + const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fReader.fHeader) + relocsOffset); + const macho_relocation_info

* relocsEnd = &relocs[relocsCount]; + for (const macho_relocation_info

* reloc = relocs; reloc < relocsEnd; ++reloc) { + //fprintf(stderr, "ObjectFileAddressSpace::relocated(0x%08X), r_address=0x%08X\n", sectOffset, reloc->r_address()); + if ( reloc->r_address() == sectOffset ) { + switch ( reloc->r_type() ) { + case X86_64_RELOC_UNSIGNED: + result += fReader.fSymbols[reloc->r_symbolnum()].n_value(); + break; + case X86_64_RELOC_SUBTRACTOR: + result -= fReader.fSymbols[reloc->r_symbolnum()].n_value(); + break; + case X86_64_RELOC_GOT: + // there is no good address to return here. + // GOT slots are synthsized by the linker + // this is used for the reference to the personality function in CIEs + result = 0; + break; + default: + fprintf(stderr, "ObjectFileAddressSpace::relocated(0x%08X) => type=%d, value=0x%08X\n", sectOffset, reloc->r_type(), reloc->r_symbolnum()); + break; + } + } + } + //fprintf(stderr, "ObjectFileAddressSpace::relocated(0x%08X) => 0x%0llX\n", sectOffset, result); + return result; +} + +template +typename A::P::uint_t ObjectFileAddressSpace::relocated(uint32_t sectOffset, uint32_t relocsOffset, uint32_t relocsCount) +{ + // in all architectures except x86_64, the section contents are already fixed up to point + // to content in the same object file. + return 0; +} + + + +// FSF exception handling Pointer-Encoding constants +// Used in CFI augmentation by gcc compiler +enum { + DW_EH_PE_ptr = 0x00, + DW_EH_PE_uleb128 = 0x01, + DW_EH_PE_udata2 = 0x02, + DW_EH_PE_udata4 = 0x03, + DW_EH_PE_udata8 = 0x04, + DW_EH_PE_signed = 0x08, + DW_EH_PE_sleb128 = 0x09, + DW_EH_PE_sdata2 = 0x0A, + DW_EH_PE_sdata4 = 0x0B, + DW_EH_PE_sdata8 = 0x0C, + DW_EH_PE_absptr = 0x00, + DW_EH_PE_pcrel = 0x10, + DW_EH_PE_textrel = 0x20, + DW_EH_PE_datarel = 0x30, + DW_EH_PE_funcrel = 0x40, + DW_EH_PE_aligned = 0x50, + DW_EH_PE_indirect = 0x80, + DW_EH_PE_omit = 0xFF +}; + +template <> +void Reader::addCiePersonalityReference(BaseAtom* cieAtom, uint32_t offsetInCIE, uint8_t encoding) +{ + if ( encoding != (DW_EH_PE_indirect|DW_EH_PE_pcrel|DW_EH_PE_sdata4) ) + throw "unexpected personality encoding in CIE"; + + // walk relocs looking for reloc in this CIE + uint32_t sectOffset = (cieAtom->getObjectAddress() + offsetInCIE) - fehFrameSection->addr(); + const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fHeader) + fehFrameSection->reloff()); + const macho_relocation_info

* relocsEnd = &relocs[fehFrameSection->nreloc()]; + for (const macho_relocation_info

* reloc = relocs; reloc < relocsEnd; ++reloc) { + if ( reloc->r_address() == sectOffset ) { + switch ( reloc->r_type() ) { + case X86_64_RELOC_GOT: + if ( !reloc->r_extern() ) + throw "GOT reloc not extern for personality function"; + new Reference(x86_64::kPCRel32GOT, AtomAndOffset(cieAtom, offsetInCIE), &fStrings[fSymbols[reloc->r_symbolnum()].n_strx()], 4); + return; + default: + throw "expected GOT reloc for personality function"; + } + } + } + throw "personality function not found for CIE"; +} + +template <> +bool Reader::isSectDiffReloc(uint8_t r_type) +{ + switch ( r_type ) { + case PPC_RELOC_LOCAL_SECTDIFF: + case PPC_RELOC_SECTDIFF: + return true; + } + return false; +} + +template <> +bool Reader::isSectDiffReloc(uint8_t r_type) +{ + switch ( r_type ) { + case PPC_RELOC_LOCAL_SECTDIFF: + case PPC_RELOC_SECTDIFF: + return true; + } + return false; +} + +template <> +bool Reader::isSectDiffReloc(uint8_t r_type) +{ + switch ( r_type ) { + case GENERIC_RELOC_LOCAL_SECTDIFF: + case GENERIC_RELOC_SECTDIFF: + return true; + } + return false; +} + +template <> +bool Reader::isSectDiffReloc(uint8_t r_type) +{ + switch ( r_type ) { + case ARM_RELOC_LOCAL_SECTDIFF: + case ARM_RELOC_SECTDIFF: + return true; + } + return false; +} + +template +void Reader::addCiePersonalityReference(BaseAtom* cieAtom, uint32_t offsetInCIE, uint8_t encoding) +{ + if ( (encoding != (DW_EH_PE_indirect|DW_EH_PE_pcrel|DW_EH_PE_sdata4)) && (encoding != (DW_EH_PE_indirect|DW_EH_PE_pcrel)) ) + throw "unexpected personality encoding in CIE"; + + // walk relocs looking for personality reloc in this CIE + uint32_t sectOffset = (cieAtom->getObjectAddress() + offsetInCIE) - fehFrameSection->addr(); + const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fHeader) + fehFrameSection->reloff()); + const macho_relocation_info

* relocsEnd = &relocs[fehFrameSection->nreloc()]; + for (const macho_relocation_info

* reloc = relocs; reloc < relocsEnd; ++reloc) { + if ( (reloc->r_address() & R_SCATTERED) == 0 ) { + // ignore + } + else { + const macho_scattered_relocation_info

* sreloc = (macho_scattered_relocation_info

*)reloc; + if ( sreloc->r_address() == sectOffset ) { + if ( isSectDiffReloc(sreloc->r_type()) ) { + // r_value is address of non-lazy-pointer to personality function + new Reference(A::kPointerDiff32, AtomAndOffset(cieAtom, offsetInCIE), AtomAndOffset(cieAtom, offsetInCIE), + findAtomAndOffset(sreloc->r_value())); + return; + } + } + } + } + throw "can't find relocation for personality in CIE"; +} - // sort all atoms by address - std::sort(fAtoms.begin(), fAtoms.end(), BaseAtomSorter()); +template +void Reader::addFdeReference(uint8_t encoding, AtomAndOffset inFDE, AtomAndOffset target) +{ + if ( (encoding & 0xF0) != DW_EH_PE_pcrel ) + throw "unsupported encoding in FDE"; + Kinds kind = A::kNoFixUp; + switch ( encoding & 0xF ) { + case DW_EH_PE_ptr: + kind = A::kPointerDiff; + break; + case DW_EH_PE_sdata4: + kind = A::kPointerDiff32; + break; + default: + throw "unsupported encoding in FDE"; + } + new Reference(kind, inFDE, inFDE, target); +} - // set ordinal and sort references in each atom - uint32_t index = fOrdinalBase; - for (std::vector::iterator it=fAtoms.begin(); it != fAtoms.end(); it++) { - BaseAtom* atom = (BaseAtom*)(*it); - atom->setOrdinal(index++); - atom->sortReferences(); +template +typename A::P::uint_t ObjectFileAddressSpace::getEncodedP(pint_t& addr, pint_t end, uint8_t encoding) +{ + pint_t startAddr = addr; + pint_t p = addr; + pint_t result; + + // first get value + switch (encoding & 0x0F) { + case DW_EH_PE_ptr: + result = getP(addr); + p += sizeof(pint_t); + addr = (pint_t)p; + break; + case DW_EH_PE_uleb128: + result = getULEB128(addr, end); + break; + case DW_EH_PE_udata2: + result = get16(addr); + p += 2; + addr = (pint_t)p; + break; + case DW_EH_PE_udata4: + result = get32(addr); + p += 4; + addr = (pint_t)p; + break; + case DW_EH_PE_udata8: + result = get64(addr); + p += 8; + addr = (pint_t)p; + break; + case DW_EH_PE_sleb128: + result = getSLEB128(addr, end); + break; + case DW_EH_PE_sdata2: + result = (int16_t)get16(addr); + p += 2; + addr = (pint_t)p; + break; + case DW_EH_PE_sdata4: + result = (int32_t)get32(addr); + p += 4; + addr = (pint_t)p; + break; + case DW_EH_PE_sdata8: + result = get64(addr); + p += 8; + addr = (pint_t)p; + break; + default: + throwf("ObjectFileAddressSpace::getEncodedP() encoding 0x%08X not supported", encoding); + } + + // then add relative offset + switch ( encoding & 0x70 ) { + case DW_EH_PE_absptr: + // do nothing + break; + case DW_EH_PE_pcrel: + result += startAddr; + break; + case DW_EH_PE_textrel: + throw "DW_EH_PE_textrel pointer encoding not supported"; + break; + case DW_EH_PE_datarel: + throw "DW_EH_PE_datarel pointer encoding not supported"; + break; + case DW_EH_PE_funcrel: + throw "DW_EH_PE_funcrel pointer encoding not supported"; + break; + case DW_EH_PE_aligned: + throw "DW_EH_PE_aligned pointer encoding not supported"; + break; + default: + throwf("ObjectFileAddressSpace::getEncodedP() encoding 0x%08X not supported", encoding); + break; } + if ( encoding & DW_EH_PE_indirect ) + result = getP(result); + + return result; +} + +template <> +uint32_t SymbolAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + pint_t lsda; + pint_t personality; + char warningBuffer[1024]; + uint32_t result = libunwind::DwarfInstructions, libunwind::Registers_x86>::createCompactEncodingFromFDE( + fOwner.fObjectAddressSpace, ehAtomAddress, &lsda, &personality, warningBuffer); + if ( (result & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF ) { + //if ( fOwner.fOptions.fForDyld ) + // throwf("can't make compact unwind encoding from dwarf for %s", this->getDisplayName()); + //else + if ( fOwner.fOptions.fWarnCompactUnwind ) + warning("can't make compact unwind encoding from dwarf for %s in %s because %s", this->getDisplayName(), fOwner.getPath(), warningBuffer); + } + return result; +} + +template <> +uint32_t SymbolAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + pint_t lsda; + pint_t personality; + char warningBuffer[1024]; + uint32_t result = libunwind::DwarfInstructions, libunwind::Registers_x86_64>::createCompactEncodingFromFDE( + fOwner.fObjectAddressSpace, ehAtomAddress, &lsda, &personality, warningBuffer); + if ( (result & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF ) { + //if ( fOwner.fOptions.fForDyld ) + // throwf("can't make compact unwind encoding from dwarf for %s", this->getDisplayName()); + //else + if ( fOwner.fOptions.fWarnCompactUnwind ) + warning("can't make compact unwind encoding from dwarf for %s in %s because %s", this->getDisplayName(), fOwner.getPath(), warningBuffer); + } + return result; +} + +template <> +uint32_t SymbolAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for ppc + return 0; +} + +template <> +uint32_t SymbolAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for ppc64 + return 0; +} + +template <> +uint32_t SymbolAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for arm + return 0; +} + + +template +uint8_t SymbolAtom::getLSDAReferenceKind() const +{ + return A::kGroupSubordinate; +} + +template <> +uint8_t SymbolAtom::getPersonalityReferenceKind() const +{ + return x86_64::kGOTNoFixUp; +} + +template <> +uint8_t SymbolAtom::getPersonalityReferenceKind() const +{ + return x86::kNoFixUp; +} + +template +uint8_t SymbolAtom::getPersonalityReferenceKind() const +{ + // only used with architectures that support compact unwinding + return 0; +} + + +template <> +uint32_t AnonymousAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + pint_t lsda; + pint_t personality; + char warningBuffer[1024]; + uint32_t result = libunwind::DwarfInstructions, libunwind::Registers_x86>::createCompactEncodingFromFDE( + fOwner.fObjectAddressSpace, ehAtomAddress, &lsda, &personality, warningBuffer); + if ( (result & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF ) { + //if ( fOwner.fOptions.fForDyld ) + // throwf("can't make compact unwind encoding from dwarf for %s", this->getDisplayName()); + //else + if ( fOwner.fOptions.fWarnCompactUnwind ) + warning("can't make compact unwind encoding from dwarf for %s in %s", this->getDisplayName(), fOwner.getPath()); + } + return result; +} + +template <> +uint32_t AnonymousAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + pint_t lsda; + pint_t personality; + char warningBuffer[1024]; + uint32_t result = libunwind::DwarfInstructions, libunwind::Registers_x86_64>::createCompactEncodingFromFDE( + fOwner.fObjectAddressSpace, ehAtomAddress, &lsda, &personality, warningBuffer); + if ( (result & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF ) { + //if ( fOwner.fOptions.fForDyld ) + // throwf("can't make compact unwind encoding from dwarf for %s", this->getDisplayName()); + //else + if ( fOwner.fOptions.fWarnCompactUnwind ) + warning("can't make compact unwind encoding from dwarf for %s in %s", this->getDisplayName(), fOwner.getPath()); + } + return result; +} + +template <> +uint32_t AnonymousAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for ppc + return 0; +} + +template <> +uint32_t AnonymousAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for ppc64 + return 0; +} + +template <> +uint32_t AnonymousAtom::getCompactUnwindEncoding(uint64_t ehAtomAddress) +{ + // compact encoding not supported for arm + return 0; +} + + +template +uint8_t AnonymousAtom::getLSDAReferenceKind() const +{ + return A::kGroupSubordinate; +} + +template <> +uint8_t AnonymousAtom::getPersonalityReferenceKind() const +{ + return x86_64::kGOTNoFixUp; +} + +template <> +uint8_t AnonymousAtom::getPersonalityReferenceKind() const +{ + return x86::kNoFixUp; +} + +template +uint8_t AnonymousAtom::getPersonalityReferenceKind() const +{ + // only used with architectures that support compact unwinding + return 0; } + + + + + template <> void Reader::setCpuConstraint(uint32_t cpusubtype) { @@ -2474,13 +3433,16 @@ Reference* Reader::makeByNameReference(Kinds kind, pint_t atAddr, const ch } template -Reference* Reader::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect) +BaseAtom* Reader::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect) { - // add a direct reference from function atom to its eh frame atom + // add a group subordinate reference from function atom to its eh frame atom const uint8_t* ehContent = (const uint8_t*)(fHeader) + ehAtomAddress - ehSect->addr() + ehSect->offset(); int32_t deltaMinus8 = P::getP(*(pint_t*)(&ehContent[8])); // offset 8 in eh info is delta to function pint_t funcAddr = ehAtomAddress + deltaMinus8 + 8; - return makeReference(A::kGroupSubordinate, funcAddr, ehAtomAddress); + ObjectFile::Atom* funcAtom = findAtomAndOffset(funcAddr).atom; + ObjectFile::Atom* ehAtom = findAtomAndOffset(ehAtomAddress).atom; + new Reference(A::kGroupSubordinate, funcAtom, ehAtom); + return (BaseAtom*)funcAtom; } @@ -2510,9 +3472,9 @@ Reference* Reader::makeReferenceToSymbol(Kinds kind, pint_t atAd template <> -Reference* Reader::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect) +BaseAtom* Reader::makeReferenceToEH(const char* ehName, pint_t ehAtomAddress, const macho_section

* ehSect) { - // add a direct reference from function atom to its eh frame atom + // add a group subordinate reference from function atom to its eh frame atom // for x86_64 the __eh_frame section contains the addends, so need to use relocs to find target uint32_t ehAtomDeltaSectionOffset = ehAtomAddress + 8 - ehSect->addr(); // offset 8 in eh info is delta to function const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fHeader) + ehSect->reloff()); @@ -2520,7 +3482,10 @@ Reference* Reader::makeReferenceToEH(const char* ehName, pint_t for (const macho_relocation_info

* reloc = relocs; reloc < relocsEnd; ++reloc) { if ( (reloc->r_address() == ehAtomDeltaSectionOffset) && (reloc->r_type() == X86_64_RELOC_UNSIGNED) ) { pint_t funcAddr = fSymbols[reloc->r_symbolnum()].n_value(); - return makeReference(x86_64::kGroupSubordinate, funcAddr, ehAtomAddress); + ObjectFile::Atom* funcAtom = findAtomAndOffset(funcAddr).atom; + ObjectFile::Atom* ehAtom = findAtomAndOffset(ehAtomAddress).atom; + new Reference(x86_64::kGroupSubordinate, funcAtom, ehAtom); + return (BaseAtom*)funcAtom; } } warning("can't find matching function for eh symbol %s", ehName); @@ -2557,13 +3522,16 @@ AtomAndOffset Reader::findAtomAndOffset(pint_t baseAddr, pint_t realAddr) AtomAndOffset result; result.atom = it->second; result.offset = realAddr - it->first; + if ( result.atom->isThumb() ) + result.offset &= -2; //fprintf(stderr, "findAtomAndOffset(0x%08X, 0x%08X) => %s + 0x%08X\n", baseAddr, realAddr, result.atom->getDisplayName(), result.offset); return result; } // getting here means we have a scattered relocation to an address without a label - // we should never get here... - // one case we do get here is because sometimes the compiler generates non-lazy pointers in the __data section - return findAtomAndOffset(realAddr); + // so, find the atom that contains the baseAddr, and offset from that to the readAddr + AtomAndOffset result = findAtomAndOffset(baseAddr); + result.offset += (realAddr-baseAddr); + return result; } @@ -2669,7 +3637,7 @@ bool Reader::skip_form(const uint8_t ** offset, const uint8_t * end, uint64_t case DW_FORM_strp: case DW_FORM_ref_addr: - sz = dwarf64 ? 8 : 4; + sz = 4; break; default: @@ -2681,6 +3649,25 @@ bool Reader::skip_form(const uint8_t ** offset, const uint8_t * end, uint64_t return true; } +template +const char* Reader::getDwarfString(uint64_t form, const uint8_t* p) +{ + if ( form == DW_FORM_string ) + return (const char*)p; + else if ( form == DW_FORM_strp ) { + uint32_t offset = E::get32(*((uint32_t*)p)); + const char* dwarfStrings = (char*)(fHeader) + fDwarfDebugStringSect->offset(); + if ( offset > fDwarfDebugStringSect->size() ) { + warning("unknown dwarf DW_FORM_strp (offset=0x%08X) is too big in %s\n", offset, this->getPath()); + return NULL; + } + return &dwarfStrings[offset]; + } + warning("unknown dwarf string encoding (form=%lld) in %s\n", form, this->getPath()); + return NULL; +} + + // Look at the compilation unit DIE and determine // its NAME, compilation directory (in COMP_DIR) and its // line number information offset (in STMT_LIST). NAME and COMP_DIR @@ -2801,13 +3788,10 @@ bool Reader::read_comp_unit(const char ** name, const char ** comp_dir, if (form == DW_FORM_indirect) form = read_uleb128 (&di, end); - if (attr == DW_AT_name && form == DW_FORM_string) - *name = (const char *) di; - else if (attr == DW_AT_comp_dir && form == DW_FORM_string) - *comp_dir = (const char *) di; - /* Really we should support DW_FORM_strp here, too, but - there's usually no reason for the producer to use that form - for the DW_AT_name and DW_AT_comp_dir attributes. */ + if (attr == DW_AT_name) + *name = getDwarfString(form, di); + else if (attr == DW_AT_comp_dir) + *comp_dir = getDwarfString(form, di); else if (attr == DW_AT_stmt_list && form == DW_FORM_data4) *stmt_list = A::P::E::get32(*(uint32_t*)di); else if (attr == DW_AT_stmt_list && form == DW_FORM_data8) @@ -2844,7 +3828,7 @@ const char* Reader::assureFullPath(const char* path) template <> -bool Reader::validFile(const uint8_t* fileContent) +bool Reader::validFile(const uint8_t* fileContent, bool, cpu_subtype_t) { const macho_header

* header = (const macho_header

*)fileContent; if ( header->magic() != MH_MAGIC ) @@ -2857,7 +3841,7 @@ bool Reader::validFile(const uint8_t* fileContent) } template <> -bool Reader::validFile(const uint8_t* fileContent) +bool Reader::validFile(const uint8_t* fileContent, bool, cpu_subtype_t) { const macho_header

* header = (const macho_header

*)fileContent; if ( header->magic() != MH_MAGIC_64 ) @@ -2870,7 +3854,7 @@ bool Reader::validFile(const uint8_t* fileContent) } template <> -bool Reader::validFile(const uint8_t* fileContent) +bool Reader::validFile(const uint8_t* fileContent, bool, cpu_subtype_t) { const macho_header

* header = (const macho_header

*)fileContent; if ( header->magic() != MH_MAGIC ) @@ -2883,7 +3867,7 @@ bool Reader::validFile(const uint8_t* fileContent) } template <> -bool Reader::validFile(const uint8_t* fileContent) +bool Reader::validFile(const uint8_t* fileContent, bool, cpu_subtype_t) { const macho_header

* header = (const macho_header

*)fileContent; if ( header->magic() != MH_MAGIC_64 ) @@ -2896,7 +3880,7 @@ bool Reader::validFile(const uint8_t* fileContent) } template <> -bool Reader::validFile(const uint8_t* fileContent) +bool Reader::validFile(const uint8_t* fileContent, bool subtypeMustMatch, cpu_subtype_t subtype) { const macho_header

* header = (const macho_header

*)fileContent; if ( header->magic() != MH_MAGIC ) @@ -2905,6 +3889,8 @@ bool Reader::validFile(const uint8_t* fileContent) return false; if ( header->filetype() != MH_OBJECT ) return false; + if ( subtypeMustMatch && ((cpu_subtype_t)header->cpusubtype() != subtype) ) + return false; return true; } @@ -3023,8 +4009,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO16: { if ( nextReloc->r_type() != PPC_RELOC_PAIR ) { - warning("PPC_RELOC_LO16 missing following pair"); - break; + throw "PPC_RELOC_LO16 missing following pair"; } result = true; lowBits = (instruction & 0xFFFF); @@ -3051,8 +4036,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO14: { if ( nextReloc->r_type() != PPC_RELOC_PAIR ) { - warning("PPC_RELOC_LO14 missing following pair"); - break; + throw "PPC_RELOC_LO14 missing following pair"; } result = true; lowBits = (instruction & 0xFFFC); @@ -3079,8 +4063,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_HI16: { if ( nextReloc->r_type() != PPC_RELOC_PAIR ) { - warning("PPC_RELOC_HI16 missing following pair"); - break; + throw "PPC_RELOC_HI16 missing following pair"; } result = true; if ( reloc->r_extern() ) { @@ -3106,8 +4089,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_HA16: { if ( nextReloc->r_type() != PPC_RELOC_PAIR ) { - warning("PPC_RELOC_HA16 missing following pair"); - break; + throw "PPC_RELOC_HA16 missing following pair"; } result = true; lowBits = (nextReloc->r_address() & 0x0000FFFF); @@ -3148,11 +4130,15 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_JBSR: // this is from -mlong-branch codegen. We ignore the jump island and make reference to the real target if ( nextReloc->r_type() != PPC_RELOC_PAIR ) { - warning("PPC_RELOC_JBSR missing following pair"); - break; + throw "PPC_RELOC_JBSR missing following pair"; } + if ( !fHasLongBranchStubs ) + warning("object file compiled with -mlong-branch which is no longer needed. To remove this warning, recompile without -mlong-branch: %s", fPath); fHasLongBranchStubs = true; result = true; + if ( reloc->r_extern() ) { + throw "PPC_RELOC_JBSR should not be using an external relocation"; + } makeReference(A::kBranch24, srcAddr, nextReloc->r_address()); if ( (instruction & 0x4C000000) == 0x48000000 ) { displacement = (instruction & 0x03FFFFFC); @@ -3162,9 +4148,6 @@ bool Reader::addRelocReference_powerpc(const macho_section* se else { fprintf(stderr, "bad instruction for BR24 reloc"); } - if ( reloc->r_extern() ) { - fprintf(stderr, "PPC_RELOC_JBSR should not be using an external relocation"); - } break; default: warning("unknown relocation type %d", reloc->r_type()); @@ -3232,8 +4215,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO16_SECTDIFF: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_LO16_SECTDIFF missing following PAIR"); - break; + throw "PPC_RELOC_LO16_SECTDIFF missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (instruction & 0xFFFF); @@ -3244,8 +4226,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO14_SECTDIFF: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_LO14_SECTDIFF missing following PAIR"); - break; + throw "PPC_RELOC_LO14_SECTDIFF missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (instruction & 0xFFFC); @@ -3256,8 +4237,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_HA16_SECTDIFF: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_HA16_SECTDIFF missing following PAIR"); - break; + throw "PPC_RELOC_HA16_SECTDIFF missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (nextRelocAddress & 0x0000FFFF); @@ -3268,8 +4248,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO14: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_LO14 missing following PAIR"); - break; + throw "PPC_RELOC_LO14 missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (instruction & 0xFFFC); @@ -3280,8 +4259,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LO16: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_LO16 missing following PAIR"); - break; + throw "PPC_RELOC_LO16 missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (instruction & 0xFFFF); @@ -3292,8 +4270,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_HA16: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_HA16 missing following PAIR"); - break; + throw "PPC_RELOC_HA16 missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (nextRelocAddress & 0xFFFF); @@ -3304,8 +4281,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_HI16: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_HI16 missing following PAIR"); - break; + throw "PPC_RELOC_HI16 missing following pair"; } instruction = BigEndian::get32(*fixUpPtr); lowBits = (nextRelocAddress & 0xFFFF); @@ -3317,8 +4293,7 @@ bool Reader::addRelocReference_powerpc(const macho_section* se case PPC_RELOC_LOCAL_SECTDIFF: { if ( ! nextRelocIsPair ) { - warning("PPC_RELOC_SECTDIFF missing following pair"); - break; + throw "PPC_RELOC_SECTDIFF missing following pair"; } Kinds kind = A::kPointerDiff32;; uint32_t contentAddr = 0; @@ -3499,10 +4474,27 @@ bool Reader::addRelocReference(const macho_section* sect, const mac //fprintf(stderr, "pointer reloc: srcAddr=0x%08X, dstAddr=0x%08X, pointer=0x%08lX\n", srcAddr, dstAddr, betterDstAddr); // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr) if ( sreloc->r_pcrel() ) { - betterDstAddr += srcAddr + 4; - makeReferenceWithToBase(x86::kPCRel32, srcAddr, betterDstAddr, dstAddr); + switch ( sreloc->r_length() ) { + case 2: + betterDstAddr += srcAddr + 4; + makeReferenceWithToBase(x86::kPCRel32, srcAddr, betterDstAddr, dstAddr); + break; + case 1: + betterDstAddr = LittleEndian::get16(*((uint16_t*)fixUpPtr)) + srcAddr + 2; + makeReferenceWithToBase(x86::kPCRel16, srcAddr, betterDstAddr, dstAddr); + break; + case 0: + betterDstAddr = *((uint8_t*)fixUpPtr) + srcAddr + 1; + makeReferenceWithToBase(x86::kPCRel8, srcAddr, betterDstAddr, dstAddr); + break; + case 3: + throwf("unsupported r_length=3 for scattered pc-rel vanilla reloc"); + break; + } } else { + if ( sreloc->r_length() != 2 ) + throwf("unsupported r_length=%d for scattered vanilla reloc", sreloc->r_length()); if ( strcmp(sect->segname(), "__TEXT") == 0 ) makeReferenceWithToBase(x86::kAbsolute32, srcAddr, betterDstAddr, dstAddr); else @@ -3513,8 +4505,7 @@ bool Reader::addRelocReference(const macho_section* sect, const mac case GENERIC_RELOC_LOCAL_SECTDIFF: { if ( !nextRelocIsPair ) { - warning("GENERIC_RELOC_SECTDIFF missing following pair"); - break; + throw "GENERIC_RELOC_SECTDIFF missing following pair"; } x86::ReferenceKinds kind = x86::kPointerDiff; uint32_t contentAddr = 0; @@ -3575,7 +4566,7 @@ bool Reader::addRelocReference(const macho_section* sect, con const char* targetName = NULL; srcAddr = sect->addr() + reloc->r_address(); fixUpPtr = (uint32_t*)((char*)(fHeader) + sect->offset() + reloc->r_address()); - //fprintf(stderr, "addReloc type=%d\n", reloc->r_type()); + //fprintf(stderr, "addReloc type=%d, len=%d, address=0x%X\n", reloc->r_type(), reloc->r_length(), reloc->r_address()); if ( reloc->r_extern() ) { targetSymbol = &fSymbols[reloc->r_symbolnum()]; targetName = &fStrings[targetSymbol->n_strx()]; @@ -3584,14 +4575,26 @@ bool Reader::addRelocReference(const macho_section* sect, con case X86_64_RELOC_UNSIGNED: if ( reloc->r_pcrel() ) throw "pcrel and X86_64_RELOC_UNSIGNED not supported"; - if ( reloc->r_length() != 3 ) - throw "length < 3 and X86_64_RELOC_UNSIGNED not supported"; + switch ( reloc->r_length() ) { + case 0: + case 1: + throw "length < 2 and X86_64_RELOC_UNSIGNED not supported"; + case 2: + kind = x86_64::kPointer32; + break; + case 3: + if ( reloc->r_extern() && isWeakImportSymbol(targetSymbol) ) + kind = x86_64::kPointerWeakImport; + else + kind = x86_64::kPointer; + break; + } dstAddr = E::get64(*((uint64_t*)fixUpPtr)); if ( reloc->r_extern() ) { - makeReferenceToSymbol(x86_64::kPointer, srcAddr, targetSymbol, dstAddr); + makeReferenceToSymbol(kind, srcAddr, targetSymbol, dstAddr); } else { - makeReference(x86_64::kPointer, srcAddr, dstAddr); + makeReference(kind, srcAddr, dstAddr); // verify that dstAddr is in the section being targeted int sectNum = reloc->r_symbolnum(); const macho_section

* const sectionsStart = (macho_section

*)((char*)fSegment + sizeof(macho_segment_command

)); @@ -3766,7 +4769,8 @@ bool Reader::addRelocReference(const macho_section* sect, con dstAddr = E::get64(*((uint64_t*)fixUpPtr)); // addend is in content negativeAddend = ((dstAddr & 0x8000000000000000ULL) != 0); } - ObjectFile::Atom* inAtom = this->findAtomAndOffset(srcAddr).atom; + AtomAndOffset inAtomAndOffset = this->findAtomAndOffset(srcAddr); + ObjectFile::Atom* inAtom = inAtomAndOffset.atom; // create reference with "to" target if ( nextReloc->r_extern() ) { const macho_nlist

* targetSymbol = &fSymbols[nextReloc->r_symbolnum()]; @@ -3796,6 +4800,9 @@ bool Reader::addRelocReference(const macho_section* sect, con ref->setFromTargetName(fromTargetName); } } + else { + throw "X86_64_RELOC_SUBTRACTOR not supported with r_extern=0"; + } // addend goes in from side iff negative if ( negativeAddend ) ref->setFromTargetOffset(-dstAddr); @@ -3824,6 +4831,7 @@ bool Reader::addRelocReference(const macho_section* sect, uint32_t srcAddr; uint32_t dstAddr; uint32_t pointerValue; + arm::ReferenceKinds kind = arm::kNoFixUp; if ( (reloc->r_address() & R_SCATTERED) == 0 ) { // non-scattered relocation @@ -3898,12 +4906,21 @@ bool Reader::addRelocReference(const macho_section* sect, break; case ARM_THUMB_RELOC_BR22: - // First instruction has upper 11 bits of the displacement. - displacement = (instruction & 0x7FF) << 12; - if ( (displacement & 0x400000) != 0 ) - displacement |= 0xFF800000; - // Second instruction has lower eleven bits of the displacement. - displacement += ((instruction >> 16) & 0x7FF) << 1; + // thumb2 added two more bits to displacement, complicating the displacement decoding + { + uint32_t s = (instruction >> 10) & 0x1; + uint32_t j1 = (instruction >> 29) & 0x1; + uint32_t j2 = (instruction >> 27) & 0x1; + uint32_t imm10 = instruction & 0x3FF; + uint32_t imm11 = (instruction >> 16) & 0x7FF; + uint32_t i1 = (j1 == s); + uint32_t i2 = (j2 == s); + uint32_t dis = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1); + int32_t sdis = dis; + if ( s ) + sdis |= 0xFE000000; + displacement = sdis; + } // The pc added will be +4 from the pc displacement += 4; // If the instruction was blx, force the low 2 bits to be clear @@ -3959,22 +4976,27 @@ bool Reader::addRelocReference(const macho_section* sect, throw "bad length for ARM_RELOC_VANILLA"; pointerValue = instruction; + kind = arm::kPointer; + if ( strcmp(sect->segname(), "__TEXT") == 0 ) + kind = arm::kReadOnlyPointer; + if ( weakImport ) + kind = arm::kPointerWeakImport; if ( reloc->r_extern() ) { - if ( weakImport ) - makeByNameReference(arm::kPointerWeakImport, srcAddr, targetName, pointerValue); - else if ( strcmp(sect->segname(), "__TEXT") == 0 ) - makeByNameReference(arm::kReadOnlyPointer, srcAddr, targetName, pointerValue); - else - makeByNameReference(arm::kPointer, srcAddr, targetName, pointerValue); + makeByNameReference(kind, srcAddr, targetName, pointerValue); } else { - if ( strcmp(sect->segname(), "__TEXT") == 0 ) - makeReference(arm::kReadOnlyPointer, srcAddr, pointerValue); - else - makeReference(arm::kPointer, srcAddr, pointerValue); + AtomAndOffset at = findAtomAndOffset(srcAddr); + AtomAndOffset to = findAtomAndOffset(pointerValue); + if ( to.atom->isThumb() ) + to.offset &= -2; + new Reference(kind, at, to); } break; + case ARM_THUMB_32BIT_BRANCH: + // work around for + break; + default: warning("unexpected relocation type %u", reloc->r_type()); break; @@ -4006,13 +5028,13 @@ bool Reader::addRelocReference(const macho_section* sect, if ( sreloc->r_length() != 2 ) throw "bad length for ARM_RELOC_VANILLA"; - betterDstAddr = LittleEndian::get32(*fixUpPtr); //fprintf(stderr, "scattered pointer reloc: srcAddr=0x%08X, dstAddr=0x%08X, pointer=0x%08X\n", srcAddr, dstAddr, betterDstAddr); + betterDstAddr = LittleEndian::get32(*fixUpPtr); + kind = arm::kPointer; + if ( strcmp(sect->segname(), "__TEXT") == 0 ) + kind = arm::kReadOnlyPointer; // with a scattered relocation we get both the target (sreloc->r_value()) and the target+offset (*fixUpPtr) - if ( strcmp(sect->segname(), "__TEXT") == 0 ) - makeReferenceWithToBase(arm::kReadOnlyPointer, srcAddr, betterDstAddr, dstAddr); - else - makeReferenceWithToBase(arm::kPointer, srcAddr, betterDstAddr, dstAddr); + makeReferenceWithToBase(kind, srcAddr, betterDstAddr, dstAddr); break; case ARM_RELOC_BR24: @@ -4030,12 +5052,21 @@ bool Reader::addRelocReference(const macho_section* sect, break; case ARM_THUMB_RELOC_BR22: - // First instruction has upper 11 bits of the displacement. - displacement = (instruction & 0x7FF) << 12; - if ( (displacement & 0x400000) != 0 ) - displacement |= 0xFF800000; - // Second instruction has lower eleven bits of the displacement. - displacement += ((instruction >> 16) & 0x7FF) << 1; + // thumb2 added two more bits to displacement, complicating the displacement decoding + { + uint32_t s = (instruction >> 10) & 0x1; + uint32_t j1 = (instruction >> 29) & 0x1; + uint32_t j2 = (instruction >> 27) & 0x1; + uint32_t imm10 = instruction & 0x3FF; + uint32_t imm11 = (instruction >> 16) & 0x7FF; + uint32_t i1 = (j1 == s); + uint32_t i2 = (j2 == s); + uint32_t dis = (s << 24) | (i1 << 23) | (i2 << 22) | (imm10 << 12) | (imm11 << 1); + int32_t sdis = dis; + if ( s ) + sdis |= 0xFE000000; + displacement = sdis; + } // The pc added will be +4 from the pc displacement += 4; betterDstAddr = srcAddr+displacement; @@ -4048,8 +5079,7 @@ bool Reader::addRelocReference(const macho_section* sect, case ARM_RELOC_SECTDIFF: case ARM_RELOC_LOCAL_SECTDIFF: if ( !nextRelocIsPair ) { - warning("ARM_RELOC_SECTDIFF missing following pair"); - break; + throw "ARM_RELOC_SECTDIFF missing following pair"; } if ( sreloc->r_length() != 2 ) throw "bad length for ARM_RELOC_SECTDIFF"; @@ -4090,6 +5120,9 @@ void Reader::addReferencesForSection(const macho_section

* sect) // we ignore compiler generated stubs, so ignore those relocs too break; default: + // ignore all relocations in __eh_frame section + if ( sect == fehFrameSection ) + return; const macho_relocation_info

* relocs = (macho_relocation_info

*)((char*)(fHeader) + sect->reloff()); const uint32_t relocCount = sect->nreloc(); //fprintf(stderr, "relocCount = %d in section %s\n", relocCount, sect->sectname()); @@ -4133,8 +5166,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04X, 32-bit pointer difference: (&%s%s%s + 0x%08X) - (&%s%s%s + 0x%08X)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } break; @@ -4144,8 +5177,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04X, 16-bit pointer difference: (&%s%s%s + 0x%08X) - (&%s%s%s + 0x%08X)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } break; @@ -4164,6 +5197,18 @@ const char* Reference::getDescription() const case x86::kAbsolute32: sprintf(temp, "offset 0x%04X, absolute32 reference to ", fFixUpOffsetInSrc); break; + case x86::kImageOffset32: + sprintf(temp, "offset 0x%04X, 32-bit offset of ", fFixUpOffsetInSrc); + break; + case x86::kPointerDiff24: + sprintf(temp, "offset 0x%04X, 24-bit pointer difference: (&%s + 0x%08X) - (&%s + 0x%08X)", + fFixUpOffsetInSrc, this->getTargetDisplayName(), fToTarget.offset, + this->getFromTargetDisplayName(), fFromTarget.offset ); + return temp; + break; + case x86::kSectionOffset24: + sprintf(temp, "offset 0x%04X, 24-bit section offset of ", fFixUpOffsetInSrc); + break; case x86::kDtraceProbe: sprintf(temp, "offset 0x%04X, dtrace static probe ", fFixUpOffsetInSrc); break; @@ -4222,8 +5267,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04X, 16-bit pointer difference: (&%s%s%s + %d) - (&%s%s%s + %d)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case ppc::kPointerDiff32: @@ -4232,8 +5277,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04X, 32-bit pointer difference: (&%s%s%s + %d) - (&%s%s%s + %d)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case ppc::kPointerDiff64: @@ -4324,8 +5369,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04llX, 64-bit pointer difference: (&%s%s%s + %u) - (&%s%s%s + %u)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case ppc64::kPointerDiff32: @@ -4334,8 +5379,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04llX, 32-bit pointer difference: (&%s%s%s + %u) - (&%s%s%s + %u)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case ppc64::kPointerDiff16: @@ -4344,8 +5389,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04llX, 16-bit pointer difference: (&%s%s%s + %u) - (&%s%s%s + %u)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case ppc64::kBranch24WeakImport: @@ -4428,6 +5473,9 @@ const char* Reference::getDescription() const case x86_64::kPointer: sprintf(temp, "offset 0x%04llX, pointer to ", fFixUpOffsetInSrc); break; + case x86_64::kPointer32: + sprintf(temp, "offset 0x%04llX, 32-bit pointer to ", fFixUpOffsetInSrc); + break; case x86_64::kPointerDiff32: case x86_64::kPointerDiff: { @@ -4436,8 +5484,8 @@ const char* Reference::getDescription() const const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; const char* size = (fKind == x86_64::kPointerDiff32) ? "32-bit" : "64-bit"; sprintf(temp, "offset 0x%04llX, %s pointer difference: (&%s%s%s + 0x%08X) - (&%s%s%s + 0x%08X)", - fFixUpOffsetInSrc, size, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, size, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } break; @@ -4471,9 +5519,23 @@ const char* Reference::getDescription() const case x86_64::kPCRel32GOTLoadWeakImport: sprintf(temp, "offset 0x%04llX, rel32 reference to GOT entry for weak imported ", fFixUpOffsetInSrc); break; + case x86_64::kGOTNoFixUp: + sprintf(temp, "reference to GOT entry for "); + break; case x86_64::kBranchPCRel8: sprintf(temp, "offset 0x%04llX, branch rel8 reference to ", fFixUpOffsetInSrc); break; + case x86_64::kPointerDiff24: + sprintf(temp, "offset 0x%04llX, 24-bit pointer difference: (&%s + 0x%08X) - (&%s + 0x%08X)", + fFixUpOffsetInSrc, this->getTargetDisplayName(), fToTarget.offset, + this->getFromTargetDisplayName(), fFromTarget.offset ); + return temp; + case x86_64::kImageOffset32: + sprintf(temp, "offset 0x%04llX, 32bit offset of ", fFixUpOffsetInSrc); + break; + case x86_64::kSectionOffset24: + sprintf(temp, "offset 0x%04llX, 24-bit section offset of ", fFixUpOffsetInSrc); + break; case x86_64::kDtraceProbe: sprintf(temp, "offset 0x%04llX, dtrace static probe ", fFixUpOffsetInSrc); break; @@ -4505,6 +5567,7 @@ const char* Reference::getDescription() const return temp; } + template <> const char* Reference::getDescription() const { @@ -4531,8 +5594,8 @@ const char* Reference::getDescription() const const char* targetQuotes = (&(this->getTarget()) == NULL) ? "\"" : ""; const char* fromQuotes = (&(this->getFromTarget()) == NULL) ? "\"" : ""; sprintf(temp, "offset 0x%04X, 32-bit pointer difference: (&%s%s%s + %d) - (&%s%s%s + %d)", - fFixUpOffsetInSrc, targetQuotes, this->getTargetName(), targetQuotes, fToTarget.offset, - fromQuotes, this->getFromTargetName(), fromQuotes, fFromTarget.offset ); + fFixUpOffsetInSrc, targetQuotes, this->getTargetDisplayName(), targetQuotes, fToTarget.offset, + fromQuotes, this->getFromTargetDisplayName(), fromQuotes, fFromTarget.offset ); return temp; } case arm::kReadOnlyPointer: @@ -4577,6 +5640,71 @@ const char* Reference::getDescription() const return temp; } + +template <> +bool Reference::isBranch() const +{ + switch ( fKind ) { + case x86::kPCRel32: + case x86::kPCRel32WeakImport: + return true; + default: + return false; + } +} + +template <> +bool Reference::isBranch() const +{ + switch ( fKind ) { + case x86_64::kBranchPCRel32: + case x86_64::kBranchPCRel32WeakImport: + return true; + default: + return false; + } +} + +template <> +bool Reference::isBranch() const +{ + switch ( fKind ) { + case ppc::kBranch24: + case ppc::kBranch24WeakImport: + return true; + default: + return false; + } +} + +template <> +bool Reference::isBranch() const +{ + switch ( fKind ) { + case ppc64::kBranch24: + case ppc64::kBranch24WeakImport: + return true; + default: + return false; + } +} + +template <> +bool Reference::isBranch() const +{ + switch ( fKind ) { + case arm::kBranch24: + case arm::kBranch24WeakImport: + case arm::kThumbBranch22: + case arm::kThumbBranch22WeakImport: + return true; + default: + return false; + } +} + + + }; // namespace relocatable }; // namespace mach_o diff --git a/src/MachOWriterExecutable.hpp b/src/ld/MachOWriterExecutable.hpp old mode 100755 new mode 100644 similarity index 67% rename from src/MachOWriterExecutable.hpp rename to src/ld/MachOWriterExecutable.hpp index 8667ae4..b019af2 --- a/src/MachOWriterExecutable.hpp +++ b/src/ld/MachOWriterExecutable.hpp @@ -1,6 +1,6 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * - * Copyright (c) 2005-2008 Apple Inc. All rights reserved. + * Copyright (c) 2005-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -45,6 +45,7 @@ #include "Options.h" #include "MachOFileAbstraction.hpp" +#include "MachOTrie.hpp" // @@ -73,6 +74,7 @@ template class MachHeaderAtom; template class SegmentLoadCommandsAtom; template class EncryptionLoadCommandsAtom; template class SymbolTableLoadCommandsAtom; +template class DyldInfoLoadCommandsAtom; template class ThreadsLoadCommandsAtom; template class DylibIDLoadCommandsAtom; template class RoutinesLoadCommandsAtom; @@ -80,6 +82,11 @@ template class DyldLoadCommandsAtom; template class UUIDLoadCommandAtom; template class LinkEditAtom; template class SectionRelocationsLinkEditAtom; +template class CompressedRebaseInfoLinkEditAtom; +template class CompressedBindingInfoLinkEditAtom; +template class CompressedWeakBindingInfoLinkEditAtom; +template class CompressedLazyBindingInfoLinkEditAtom; +template class CompressedExportInfoLinkEditAtom; template class LocalRelocationsLinkEditAtom; template class ExternalRelocationsLinkEditAtom; template class SymbolTableLinkEditAtom; @@ -89,8 +96,14 @@ template class IndirectTableLinkEditAtom; template class ModuleInfoLinkEditAtom; template class StringsLinkEditAtom; template class LoadCommandsPaddingAtom; +template class UnwindInfoAtom; template class StubAtom; template class StubHelperAtom; +template class ClassicStubHelperAtom; +template class HybridStubHelperAtom; +template class HybridStubHelperHelperAtom; +template class FastStubHelperAtom; +template class FastStubHelperHelperAtom; template class LazyPointerAtom; template class NonLazyPointerAtom; template class DylibLoadCommandsAtom; @@ -102,7 +115,8 @@ public: SectionInfo() : fFileOffset(0), fSize(0), fRelocCount(0), fRelocOffset(0), fIndirectSymbolOffset(0), fAlignment(0), fAllLazyPointers(false), fAllLazyDylibPointers(false),fAllNonLazyPointers(false), fAllStubs(false), - fAllSelfModifyingStubs(false), fAllZeroFill(false), fVirtualSection(false), + fAllSelfModifyingStubs(false), fAllStubHelpers(false), + fAllZeroFill(false), fVirtualSection(false), fHasTextLocalRelocs(false), fHasTextExternalRelocs(false) { fSegmentName[0] = '\0'; fSectionName[0] = '\0'; } void setIndex(unsigned int index) { fIndex=index; } @@ -120,6 +134,7 @@ public: bool fAllNonLazyPointers; bool fAllStubs; bool fAllSelfModifyingStubs; + bool fAllStubHelpers; bool fAllZeroFill; bool fVirtualSection; bool fHasTextLocalRelocs; @@ -130,9 +145,9 @@ public: class SegmentInfo { public: - SegmentInfo() : fInitProtection(0), fMaxProtection(0), fFileOffset(0), fFileSize(0), - fBaseAddress(0), fSize(0), fFixedAddress(false), - fIndependentAddress(false) { fName[0] = '\0'; } + SegmentInfo(uint64_t pageSize) : fInitProtection(0), fMaxProtection(0), fFileOffset(0), fFileSize(0), + fBaseAddress(0), fSize(0), fPageSize(pageSize), fFixedAddress(false), + fIndependentAddress(false), fHasLoadCommand(true) { fName[0] = '\0'; } std::vector fSections; char fName[20]; uint32_t fInitProtection; @@ -141,10 +156,119 @@ public: uint64_t fFileSize; uint64_t fBaseAddress; uint64_t fSize; + uint64_t fPageSize; bool fFixedAddress; bool fIndependentAddress; + bool fHasLoadCommand; }; + +struct RebaseInfo { + RebaseInfo(uint8_t t, uint64_t addr) : fType(t), fAddress(addr) {} + uint8_t fType; + uint64_t fAddress; + // for sorting + int operator<(const RebaseInfo& rhs) const { + // sort by type, then address + if ( this->fType != rhs.fType ) + return (this->fType < rhs.fType ); + return (this->fAddress < rhs.fAddress ); + } +}; + +struct BindingInfo { + BindingInfo(uint8_t t, int ord, const char* sym, bool weak_import, uint64_t addr, int64_t addend) + : fType(t), fFlags(weak_import ? BIND_SYMBOL_FLAGS_WEAK_IMPORT : 0 ), fLibraryOrdinal(ord), + fSymbolName(sym), fAddress(addr), fAddend(addend) {} + BindingInfo(uint8_t t, const char* sym, bool non_weak_definition, uint64_t addr, int64_t addend) + : fType(t), fFlags(non_weak_definition ? BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION : 0 ), fLibraryOrdinal(0), + fSymbolName(sym), fAddress(addr), fAddend(addend) {} + uint8_t fType; + uint8_t fFlags; + int fLibraryOrdinal; + const char* fSymbolName; + uint64_t fAddress; + int64_t fAddend; + + // for sorting + int operator<(const BindingInfo& rhs) const { + // sort by library, symbol, type, then address + if ( this->fLibraryOrdinal != rhs.fLibraryOrdinal ) + return (this->fLibraryOrdinal < rhs.fLibraryOrdinal ); + if ( this->fSymbolName != rhs.fSymbolName ) + return ( strcmp(this->fSymbolName, rhs.fSymbolName) < 0 ); + if ( this->fType != rhs.fType ) + return (this->fType < rhs.fType ); + return (this->fAddress < rhs.fAddress ); + } +}; + + +class ByteStream { +private: + std::vector fData; +public: + std::vector& bytes() { return fData; } + unsigned long size() const { return fData.size(); } + void reserve(unsigned long l) { fData.reserve(l); } + const uint8_t* start() const { return &fData[0]; } + + void append_uleb128(uint64_t value) { + uint8_t byte; + do { + byte = value & 0x7F; + value &= ~0x7F; + if ( value != 0 ) + byte |= 0x80; + fData.push_back(byte); + value = value >> 7; + } while( byte >= 0x80 ); + } + + void append_sleb128(int64_t value) { + bool isNeg = ( value < 0 ); + uint8_t byte; + bool more; + do { + byte = value & 0x7F; + value = value >> 7; + if ( isNeg ) + more = ( (value != -1) || ((byte & 0x40) == 0) ); + else + more = ( (value != 0) || ((byte & 0x40) != 0) ); + if ( more ) + byte |= 0x80; + fData.push_back(byte); + } + while( more ); + } + + void append_string(const char* str) { + for (const char* s = str; *s != '\0'; ++s) + fData.push_back(*s); + fData.push_back('\0'); + } + + void append_byte(uint8_t byte) { + fData.push_back(byte); + } + + static unsigned int uleb128_size(uint64_t value) { + uint32_t result = 0; + do { + value = value >> 7; + ++result; + } while ( value != 0 ); + return result; + } + + void pad_to_size(unsigned int alignment) { + while ( (fData.size() % alignment) != 0 ) + fData.push_back(0); + } +}; + + template class Writer : public ExecutableFile::Writer { @@ -165,11 +289,14 @@ public: virtual uint64_t write(std::vector& atoms, std::vector& stabs, class ObjectFile::Atom* entryPointAtom, - class ObjectFile::Atom* dyldHelperAtom, + class ObjectFile::Atom* dyldClassicHelperAtom, + class ObjectFile::Atom* dyldCompressedHelperAtom, class ObjectFile::Atom* dyldLazyDylibHelperAtom, bool createUUID, bool canScatter, ObjectFile::Reader::CpuConstraint cpuConstraint, - bool biggerThanTwoGigs, bool overridesDylibWeakDefines); + bool biggerThanTwoGigs, + std::set& atomsThatOverrideWeak, + bool hasExternalWeakDefinitions); private: typedef typename A::P P; @@ -179,6 +306,9 @@ private: void assignFileOffsets(); void synthesizeStubs(); + void synthesizeKextGOT(); + void createSplitSegContent(); + void synthesizeUnwindInfoTable(); void insertDummyStubs(); void partitionIntoSections(); bool addBranchIslands(); @@ -200,6 +330,7 @@ private: void addLocalLabel(ObjectFile::Atom& atom, uint32_t offsetInAtom, const char* name); void addGlobalLabel(ObjectFile::Atom& atom, uint32_t offsetInAtom, const char* name); void buildSymbolTable(); + bool stringsNeedLabelsInObjects(); const char* symbolTableName(const ObjectFile::Atom* atom); void setExportNlist(const ObjectFile::Atom* atom, macho_nlist

* entry); void setImportNlist(const ObjectFile::Atom* atom, macho_nlist

* entry); @@ -207,6 +338,8 @@ private: void copyNlistRange(const std::vector >& entries, uint32_t startIndex); uint64_t getAtomLoadAddress(const ObjectFile::Atom* atom); uint8_t ordinalForLibrary(ObjectFile::Reader* file); + bool targetRequiresWeakBinding(const ObjectFile::Atom& target); + int compressedOrdinalForImortedAtom(ObjectFile::Atom* target); bool shouldExport(const ObjectFile::Atom& atom) const; void buildFixups(); void adjustLinkEditSections(); @@ -241,7 +374,7 @@ private: void scanForAbsoluteReferences(); bool needsModuleTable(); void optimizeDylibReferences(); - bool indirectSymbolIsLocal(const ObjectFile::Reference* ref) const; + bool indirectSymbolInRelocatableIsLocal(const ObjectFile::Reference* ref) const; struct DirectLibrary { class ObjectFile::Reader* fLibrary; @@ -256,6 +389,7 @@ private: friend class SegmentLoadCommandsAtom; friend class EncryptionLoadCommandsAtom; friend class SymbolTableLoadCommandsAtom; + friend class DyldInfoLoadCommandsAtom; friend class ThreadsLoadCommandsAtom; friend class DylibIDLoadCommandsAtom; friend class RoutinesLoadCommandsAtom; @@ -263,17 +397,28 @@ private: friend class UUIDLoadCommandAtom; friend class LinkEditAtom; friend class SectionRelocationsLinkEditAtom; + friend class CompressedRebaseInfoLinkEditAtom; + friend class CompressedBindingInfoLinkEditAtom; + friend class CompressedWeakBindingInfoLinkEditAtom; + friend class CompressedLazyBindingInfoLinkEditAtom; + friend class CompressedExportInfoLinkEditAtom; friend class LocalRelocationsLinkEditAtom; friend class ExternalRelocationsLinkEditAtom; friend class SymbolTableLinkEditAtom; friend class SegmentSplitInfoLoadCommandsAtom; friend class SegmentSplitInfoContentAtom; -// friend class IndirectTableLinkEditAtom; + friend class IndirectTableLinkEditAtom; friend class ModuleInfoLinkEditAtom; friend class StringsLinkEditAtom; friend class LoadCommandsPaddingAtom; + friend class UnwindInfoAtom; friend class StubAtom; friend class StubHelperAtom; + friend class ClassicStubHelperAtom; + friend class HybridStubHelperAtom; + friend class FastStubHelperAtom; + friend class FastStubHelperHelperAtom; + friend class HybridStubHelperHelperAtom; friend class LazyPointerAtom; friend class NonLazyPointerAtom; friend class DylibLoadCommandsAtom; @@ -282,28 +427,39 @@ private: Options& fOptions; std::vector* fAllAtoms; std::vector* fStabs; + std::set* fRegularDefAtomsThatOverrideADylibsWeakDef; class SectionInfo* fLoadCommandsSection; class SegmentInfo* fLoadCommandsSegment; + class MachHeaderAtom* fMachHeaderAtom; class EncryptionLoadCommandsAtom* fEncryptionLoadCommand; class SegmentLoadCommandsAtom* fSegmentCommands; class SymbolTableLoadCommandsAtom* fSymbolTableCommands; class LoadCommandsPaddingAtom* fHeaderPadding; + class UnwindInfoAtom* fUnwindInfoAtom; class UUIDLoadCommandAtom* fUUIDAtom; std::vector fWriterSynthesizedAtoms; std::vector fSegmentInfos; class SegmentInfo* fPadSegmentInfo; class ObjectFile::Atom* fEntryPoint; - class ObjectFile::Atom* fDyldHelper; + class ObjectFile::Atom* fDyldClassicHelperAtom; + class ObjectFile::Atom* fDyldCompressedHelperAtom; class ObjectFile::Atom* fDyldLazyDylibHelper; std::map*> fLibraryToLoadCommand; std::map fLibraryToOrdinal; std::map fLibraryAliases; + std::set fForcedWeakImportReaders; std::vector fExportedAtoms; std::vector fImportedAtoms; std::vector fLocalSymbolAtoms; std::vector > fLocalExtraLabels; std::vector > fGlobalExtraLabels; - class SectionRelocationsLinkEditAtom* fSectionRelocationsAtom; + std::map fAtomToSymbolIndex; + class SectionRelocationsLinkEditAtom* fSectionRelocationsAtom; + class CompressedRebaseInfoLinkEditAtom* fCompressedRebaseInfoAtom; + class CompressedBindingInfoLinkEditAtom* fCompressedBindingInfoAtom; + class CompressedWeakBindingInfoLinkEditAtom* fCompressedWeakBindingInfoAtom; + class CompressedLazyBindingInfoLinkEditAtom* fCompressedLazyBindingInfoAtom; + class CompressedExportInfoLinkEditAtom* fCompressedExportInfoAtom; class LocalRelocationsLinkEditAtom* fLocalRelocationsAtom; class ExternalRelocationsLinkEditAtom* fExternalRelocationsAtom; class SymbolTableLinkEditAtom* fSymbolTableAtom; @@ -312,10 +468,14 @@ private: class ModuleInfoLinkEditAtom* fModuleInfoAtom; class StringsLinkEditAtom* fStringsAtom; class PageZeroAtom* fPageZeroAtom; + class NonLazyPointerAtom* fFastStubGOTAtom; macho_nlist

* fSymbolTable; std::vector > fSectionRelocs; std::vector > fInternalRelocs; std::vector > fExternalRelocs; + std::vector fRebaseInfo; + std::vector fBindingInfo; + std::vector fWeakBindingInfo; std::map fStubsMap; std::map fGOTMap; std::vector*> fAllSynthesizedStubs; @@ -369,6 +529,7 @@ public: static Segment fgROImportSegment; static Segment fgDataSegment; static Segment fgObjCSegment; + static Segment fgHeaderSegment; private: @@ -387,6 +548,7 @@ Segment Segment::fgImportSegment("__IMPORT", true, true, true, false); Segment Segment::fgROImportSegment("__IMPORT", true, false, true, false); Segment Segment::fgDataSegment("__DATA", true, true, false, false); Segment Segment::fgObjCSegment("__OBJC", true, true, false, false); +Segment Segment::fgHeaderSegment("__HEADER", true, false, true, false); template @@ -422,6 +584,9 @@ protected: typedef typename A::P P; typedef typename A::P::E E; + static Segment& headerSegment(Writer& writer) { return (writer.fOptions.outputKind()==Options::kPreload) + ? Segment::fgHeaderSegment : Segment::fgTextSegment; } + static std::vector fgEmptyReferenceList; Writer& fWriter; @@ -469,7 +634,7 @@ template class MachHeaderAtom : public WriterAtom { public: - MachHeaderAtom(Writer& writer) : WriterAtom(writer, Segment::fgTextSegment) {} + MachHeaderAtom(Writer& writer) : WriterAtom(writer, headerSegment(writer)) {} virtual const char* getName() const; virtual const char* getDisplayName() const; virtual ObjectFile::Atom::Scope getScope() const; @@ -505,7 +670,7 @@ template class LoadCommandAtom : public WriterAtom { protected: - LoadCommandAtom(Writer& writer, Segment& segment) : WriterAtom(writer, segment), fOrdinal(fgCurrentOrdinal++) {} + LoadCommandAtom(Writer& writer) : WriterAtom(writer, headerSegment(writer)), fOrdinal(fgCurrentOrdinal++) {} virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(log2(sizeof(typename A::P::uint_t))); } virtual const char* getSectionName() const { return "._load_commands"; } virtual uint32_t getOrdinal() const { return fOrdinal; } @@ -522,7 +687,7 @@ class SegmentLoadCommandsAtom : public LoadCommandAtom { public: SegmentLoadCommandsAtom(Writer& writer) - : LoadCommandAtom(writer, Segment::fgTextSegment), fCommandCount(0), fSize(0) + : LoadCommandAtom(writer), fCommandCount(0), fSize(0) { writer.fSegmentCommands = this; } virtual const char* getDisplayName() const { return "segment load commands"; } virtual uint64_t getSize() const { return fSize; } @@ -562,7 +727,7 @@ class ThreadsLoadCommandsAtom : public LoadCommandAtom { public: ThreadsLoadCommandsAtom(Writer& writer) - : LoadCommandAtom(writer, Segment::fgTextSegment) {} + : LoadCommandAtom(writer) {} virtual const char* getDisplayName() const { return "thread load commands"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -577,7 +742,7 @@ template class DyldLoadCommandsAtom : public LoadCommandAtom { public: - DyldLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer, Segment::fgTextSegment) {} + DyldLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer) {} virtual const char* getDisplayName() const { return "dyld load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -590,7 +755,7 @@ template class SegmentSplitInfoLoadCommandsAtom : public LoadCommandAtom { public: - SegmentSplitInfoLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer, Segment::fgTextSegment) {} + SegmentSplitInfoLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer) {} virtual const char* getDisplayName() const { return "segment split info load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -604,7 +769,7 @@ class AllowableClientLoadCommandsAtom : public LoadCommandAtom { public: AllowableClientLoadCommandsAtom(Writer& writer, const char* client) : - LoadCommandAtom(writer, Segment::fgTextSegment), clientString(client) {} + LoadCommandAtom(writer), clientString(client) {} virtual const char* getDisplayName() const { return "allowable_client load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -619,7 +784,7 @@ class DylibLoadCommandsAtom : public LoadCommandAtom { public: DylibLoadCommandsAtom(Writer& writer, ExecutableFile::DyLibUsed& info) - : LoadCommandAtom(writer, Segment::fgTextSegment), fInfo(info), + : LoadCommandAtom(writer), fInfo(info), fOptimizedAway(false) { if (fInfo.options.fLazyLoad) this->fOrdinal += 256; } virtual const char* getDisplayName() const { return "dylib load command"; } virtual uint64_t getSize() const; @@ -637,7 +802,7 @@ template class DylibIDLoadCommandsAtom : public LoadCommandAtom { public: - DylibIDLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer, Segment::fgTextSegment) {} + DylibIDLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer) {} virtual const char* getDisplayName() const { return "dylib ID load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -650,7 +815,7 @@ template class RoutinesLoadCommandsAtom : public LoadCommandAtom { public: - RoutinesLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer, Segment::fgTextSegment) {} + RoutinesLoadCommandsAtom(Writer& writer) : LoadCommandAtom(writer) {} virtual const char* getDisplayName() const { return "routines load command"; } virtual uint64_t getSize() const { return sizeof(macho_routines_command); } virtual void copyRawContent(uint8_t buffer[]) const; @@ -664,7 +829,7 @@ class SubUmbrellaLoadCommandsAtom : public LoadCommandAtom { public: SubUmbrellaLoadCommandsAtom(Writer& writer, const char* name) - : LoadCommandAtom(writer, Segment::fgTextSegment), fName(name) {} + : LoadCommandAtom(writer), fName(name) {} virtual const char* getDisplayName() const { return "sub-umbrella load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -678,7 +843,7 @@ class SubLibraryLoadCommandsAtom : public LoadCommandAtom { public: SubLibraryLoadCommandsAtom(Writer& writer, const char* nameStart, int nameLen) - : LoadCommandAtom(writer, Segment::fgTextSegment), fNameStart(nameStart), fNameLength(nameLen) {} + : LoadCommandAtom(writer), fNameStart(nameStart), fNameLength(nameLen) {} virtual const char* getDisplayName() const { return "sub-library load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -694,7 +859,7 @@ class UmbrellaLoadCommandsAtom : public LoadCommandAtom { public: UmbrellaLoadCommandsAtom(Writer& writer, const char* name) - : LoadCommandAtom(writer, Segment::fgTextSegment), fName(name) {} + : LoadCommandAtom(writer), fName(name) {} virtual const char* getDisplayName() const { return "umbrella load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -709,7 +874,7 @@ class UUIDLoadCommandAtom : public LoadCommandAtom { public: UUIDLoadCommandAtom(Writer& writer) - : LoadCommandAtom(writer, Segment::fgTextSegment), fEmit(false) {} + : LoadCommandAtom(writer), fEmit(false) {} virtual const char* getDisplayName() const { return "uuid load command"; } virtual uint64_t getSize() const { return fEmit ? sizeof(macho_uuid_command) : 0; } virtual void copyRawContent(uint8_t buffer[]) const; @@ -729,7 +894,7 @@ class RPathLoadCommandsAtom : public LoadCommandAtom { public: RPathLoadCommandsAtom(Writer& writer, const char* path) - : LoadCommandAtom(writer, Segment::fgTextSegment), fPath(path) {} + : LoadCommandAtom(writer), fPath(path) {} virtual const char* getDisplayName() const { return "rpath load command"; } virtual uint64_t getSize() const; virtual void copyRawContent(uint8_t buffer[]) const; @@ -744,7 +909,7 @@ class EncryptionLoadCommandsAtom : public LoadCommandAtom { public: EncryptionLoadCommandsAtom(Writer& writer) - : LoadCommandAtom(writer, Segment::fgTextSegment), fStartOffset(0), + : LoadCommandAtom(writer), fStartOffset(0), fEndOffset(0) {} virtual const char* getDisplayName() const { return "encryption info load command"; } virtual uint64_t getSize() const { return sizeof(macho_encryption_info_command); } @@ -758,12 +923,27 @@ private: uint32_t fEndOffset; }; +template +class DyldInfoLoadCommandsAtom : public LoadCommandAtom +{ +public: + DyldInfoLoadCommandsAtom(Writer& writer) + : LoadCommandAtom(writer) {} + virtual const char* getDisplayName() const { return "dyld info load command"; } + virtual uint64_t getSize() const { return sizeof(macho_dyld_info_command); } + virtual void copyRawContent(uint8_t buffer[]) const; +private: + using WriterAtom::fWriter; + typedef typename A::P P; +}; + + template class LoadCommandsPaddingAtom : public WriterAtom { public: LoadCommandsPaddingAtom(Writer& writer) - : WriterAtom(writer, Segment::fgTextSegment), fSize(0) {} + : WriterAtom(writer, headerSegment(writer)), fSize(0) {} virtual const char* getDisplayName() const { return "header padding"; } virtual uint64_t getSize() const { return fSize; } virtual const char* getSectionName() const { return "._load_cmds_pad"; } @@ -776,6 +956,65 @@ private: uint64_t fSize; }; +template +class UnwindInfoAtom : public WriterAtom +{ +public: + UnwindInfoAtom(Writer& writer) : WriterAtom(writer, Segment::fgTextSegment), + fHeaderSize(0), fPagesSize(0), fAlignment(4) {} + virtual const char* getName() const { return "unwind info"; } + virtual ObjectFile::Atom::Scope getScope() const { return ObjectFile::Atom::scopeTranslationUnit; } + virtual ObjectFile::Atom::SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableNotIn; } + virtual uint64_t getSize() const { return fHeaderSize+fPagesSize; } + virtual ObjectFile::Alignment getAlignment() const { return fAlignment; } + virtual const char* getSectionName() const { return "__unwind_info"; } + virtual uint32_t getOrdinal() const { return 1; } + virtual std::vector& getReferences() const { return (std::vector&)fReferences; } + virtual void copyRawContent(uint8_t buffer[]) const; + + void addUnwindInfo(ObjectFile::Atom* func, uint32_t offset, uint32_t encoding, + ObjectFile::Reference* fdeRef, ObjectFile::Reference* lsda, + ObjectFile::Atom* personalityPointer); + void generate(); + +private: + using WriterAtom::fWriter; + typedef typename A::P P; + struct Info { ObjectFile::Atom* func; ObjectFile::Atom* fde; ObjectFile::Atom* lsda; uint32_t lsdaOffset; ObjectFile::Atom* personalityPointer; uint32_t encoding; }; + struct LSDAEntry { ObjectFile::Atom* func; ObjectFile::Atom* lsda; uint32_t lsdaOffset; }; + struct RegFixUp { uint8_t* contentPointer; ObjectFile::Atom* func; ObjectFile::Atom* fde; }; + struct CompressedFixUp { uint8_t* contentPointer; ObjectFile::Atom* func; ObjectFile::Atom* fromFunc; }; + struct CompressedEncodingFixUp { uint8_t* contentPointer; ObjectFile::Atom* fde; }; + + bool encodingMeansUseDwarf(compact_unwind_encoding_t encoding); + void compressDuplicates(std::vector& uniqueInfos); + void findCommonEncoding(const std::vector& uniqueInfos, std::map& commonEncodings); + void makeLsdaIndex(const std::vector& uniqueInfos, std::map& lsdaIndexOffsetMap); + unsigned int makeRegularSecondLevelPage(const std::vector& uniqueInfos, uint32_t pageSize, unsigned int endIndex, + uint8_t*& pageEnd); + unsigned int makeCompressedSecondLevelPage(const std::vector& uniqueInfos, + const std::map commonEncodings, + uint32_t pageSize, unsigned int endIndex, uint8_t*& pageEnd); + void makePersonalityIndex(std::vector& uniqueInfos); + + + uint32_t fHeaderSize; + uint32_t fPagesSize; + uint8_t* fHeaderContent; + uint8_t* fPagesContent; + uint8_t* fPagesContentForDelete; + ObjectFile::Alignment fAlignment; + std::vector fInfos; + std::map fPersonalityIndexMap; + std::vector fLSDAIndex; + std::vector fRegFixUps; + std::vector fCompressedFixUps; + std::vector fCompressedEncodingFixUps; + std::vector fReferences; +}; + + + template class LinkEditAtom : public WriterAtom { @@ -807,6 +1046,235 @@ private: typedef typename A::P P; }; +template +class CompressedInfoLinkEditAtom : public LinkEditAtom +{ +public: + CompressedInfoLinkEditAtom(Writer& writer) : LinkEditAtom(writer) { } + virtual uint64_t getSize() const { return fEncodedData.size(); } + virtual void copyRawContent(uint8_t buffer[]) const { memcpy(buffer, fEncodedData.start(), fEncodedData.size()); } +protected: + typedef typename A::P::uint_t pint_t; + ByteStream fEncodedData; +private: + using WriterAtom::fWriter; + typedef typename A::P P; +}; + + + +template +class CompressedRebaseInfoLinkEditAtom : public CompressedInfoLinkEditAtom +{ +public: + CompressedRebaseInfoLinkEditAtom(Writer& writer) : CompressedInfoLinkEditAtom(writer) { } + virtual const char* getDisplayName() const { return "compressed rebase info"; } + virtual const char* getSectionName() const { return "._rebase info"; } + void encode(); +private: + using CompressedInfoLinkEditAtom::fEncodedData; + using CompressedInfoLinkEditAtom::fWriter; + typedef typename A::P P; + typedef typename A::P::uint_t pint_t; +}; + +template +class CompressedBindingInfoLinkEditAtom : public CompressedInfoLinkEditAtom +{ +public: + CompressedBindingInfoLinkEditAtom(Writer& writer) : CompressedInfoLinkEditAtom(writer) { } + virtual const char* getDisplayName() const { return "compressed binding info"; } + virtual const char* getSectionName() const { return "._binding info"; } + void encode(); +private: + using CompressedInfoLinkEditAtom::fWriter; + using CompressedInfoLinkEditAtom::fEncodedData; + typedef typename A::P P; + typedef typename A::P::uint_t pint_t; +}; + +template +class CompressedWeakBindingInfoLinkEditAtom : public CompressedInfoLinkEditAtom +{ +public: + CompressedWeakBindingInfoLinkEditAtom(Writer& writer) : CompressedInfoLinkEditAtom(writer) { } + virtual const char* getDisplayName() const { return "compressed weak binding info"; } + virtual const char* getSectionName() const { return "._wkbinding info"; } + void encode(); +private: + using CompressedInfoLinkEditAtom::fWriter; + using CompressedInfoLinkEditAtom::fEncodedData; + typedef typename A::P P; + typedef typename A::P::uint_t pint_t; +}; + +template +class CompressedLazyBindingInfoLinkEditAtom : public CompressedInfoLinkEditAtom +{ +public: + CompressedLazyBindingInfoLinkEditAtom(Writer& writer) : CompressedInfoLinkEditAtom(writer) { } + virtual const char* getDisplayName() const { return "compressed lazy binding info"; } + virtual const char* getSectionName() const { return "._lzbinding info"; } + void encode(); +private: + std::vector fStarts; + + using CompressedInfoLinkEditAtom::fWriter; + using CompressedInfoLinkEditAtom::fEncodedData; + typedef typename A::P P; + typedef typename A::P::uint_t pint_t; +}; + + +template +class CompressedExportInfoLinkEditAtom : public CompressedInfoLinkEditAtom +{ +public: + CompressedExportInfoLinkEditAtom(Writer& writer) + : CompressedInfoLinkEditAtom(writer), fStartNode(strdup("")) { } + virtual const char* getDisplayName() const { return "compressed export info"; } + virtual const char* getSectionName() const { return "._export info"; } + void encode(); +private: + using WriterAtom::fWriter; + using CompressedInfoLinkEditAtom::fEncodedData; + typedef typename A::P P; + typedef typename A::P::uint_t pint_t; + struct node; + + struct edge + { + edge(const char* s, struct node* n) : fSubString(s), fChild(n) { } + ~edge() { } + const char* fSubString; + struct node* fChild; + + }; + + struct node + { + node(const char* s) : fCummulativeString(s), fAddress(0), fFlags(0), fOrdered(false), + fHaveExportInfo(false), fTrieOffset(0) {} + ~node() { } + const char* fCummulativeString; + std::vector fChildren; + uint64_t fAddress; + uint32_t fFlags; + bool fOrdered; + bool fHaveExportInfo; + uint32_t fTrieOffset; + + void addSymbol(const char* fullStr, uint64_t address, uint32_t flags) { + const char* partialStr = &fullStr[strlen(fCummulativeString)]; + for (typename std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + edge& e = *it; + int subStringLen = strlen(e.fSubString); + if ( strncmp(e.fSubString, partialStr, subStringLen) == 0 ) { + // already have matching edge, go down that path + e.fChild->addSymbol(fullStr, address, flags); + return; + } + else { + for (int i=subStringLen-1; i > 0; --i) { + if ( strncmp(e.fSubString, partialStr, i) == 0 ) { + // found a common substring, splice in new node + // was A -> C, now A -> B -> C + char* bNodeCummStr = strdup(e.fChild->fCummulativeString); + bNodeCummStr[strlen(bNodeCummStr)+i-subStringLen] = '\0'; + //node* aNode = this; + node* bNode = new node(bNodeCummStr); + node* cNode = e.fChild; + char* abEdgeStr = strdup(e.fSubString); + abEdgeStr[i] = '\0'; + char* bcEdgeStr = strdup(&e.fSubString[i]); + edge& abEdge = e; + abEdge.fSubString = abEdgeStr; + abEdge.fChild = bNode; + edge bcEdge(bcEdgeStr, cNode); + bNode->fChildren.push_back(bcEdge); + bNode->addSymbol(fullStr, address, flags); + return; + } + } + } + } + // no commonality with any existing child, make a new edge that is this whole string + node* newNode = new node(strdup(fullStr)); + edge newEdge(strdup(partialStr), newNode); + fChildren.push_back(newEdge); + newNode->fAddress = address; + newNode->fFlags = flags; + newNode->fHaveExportInfo = true; + } + + void addOrderedNodes(const char* name, std::vector& orderedNodes) { + if ( !fOrdered ) { + orderedNodes.push_back(this); + //fprintf(stderr, "ordered %p %s\n", this, fCummulativeString); + fOrdered = true; + } + const char* partialStr = &name[strlen(fCummulativeString)]; + for (typename std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + edge& e = *it; + int subStringLen = strlen(e.fSubString); + if ( strncmp(e.fSubString, partialStr, subStringLen) == 0 ) { + // already have matching edge, go down that path + e.fChild->addOrderedNodes(name, orderedNodes); + return; + } + } + } + + // byte for terminal node size in bytes, or 0x00 if not terminal node + // teminal node (uleb128 flags, uleb128 addr) + // byte for child node count + // each child: zero terminated substring, uleb128 node offset + bool updateOffset(uint32_t& offset) { + uint32_t nodeSize = 1; // byte for length of export info + if ( fHaveExportInfo ) + nodeSize += ByteStream::uleb128_size(fFlags) + ByteStream::uleb128_size(fAddress); + + // add children + ++nodeSize; // byte for count of chidren + for (typename std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + edge& e = *it; + nodeSize += strlen(e.fSubString) + 1 + ByteStream::uleb128_size(e.fChild->fTrieOffset); + } + bool result = (fTrieOffset != offset); + fTrieOffset = offset; + //fprintf(stderr, "updateOffset %p %05d %s\n", this, fTrieOffset, fCummulativeString); + offset += nodeSize; + // return true if fTrieOffset was changed + return result; + } + + void appendToStream(ByteStream& out) { + if ( fHaveExportInfo ) { + // nodes with export info: size, flags, address + out.append_byte(out.uleb128_size(fFlags) + out.uleb128_size(fAddress)); + out.append_uleb128(fFlags); + out.append_uleb128(fAddress); + } + else { + // no export info + out.append_byte(0); + } + // write number of children + out.append_byte(fChildren.size()); + // write each child + for (typename std::vector::iterator it = fChildren.begin(); it != fChildren.end(); ++it) { + edge& e = *it; + out.append_string(e.fSubString); + out.append_uleb128(e.fChild->fTrieOffset); + } + } + + }; + + + struct node fStartNode; +}; + template class LocalRelocationsLinkEditAtom : public LinkEditAtom { @@ -927,6 +1395,7 @@ public: private: using WriterAtom::fWriter; typedef typename A::P P; + typedef typename A::P::uint_t pint_t; uint32_t fModuleNameOffset; }; @@ -1023,25 +1492,107 @@ private: bool fForLazyDylib; }; + +template +class FastStubHelperHelperAtom : public WriterAtom +{ +public: + FastStubHelperHelperAtom(Writer& writer); + virtual const char* getName() const { return " stub helpers"; } // name sorts to start of helpers + virtual ObjectFile::Atom::SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableIn; } + virtual ObjectFile::Atom::Scope getScope() const { return ObjectFile::Atom::scopeLinkageUnit; } + virtual uint64_t getSize() const; + virtual const char* getSectionName() const { return "__stub_helper"; } + virtual std::vector& getReferences() const { return (std::vector&)(fReferences); } + virtual void copyRawContent(uint8_t buffer[]) const; + virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); } +protected: + using WriterAtom::fWriter; + std::vector fReferences; +}; + +template +class HybridStubHelperHelperAtom : public WriterAtom +{ +public: + HybridStubHelperHelperAtom(Writer& writer); + virtual const char* getName() const { return " stub helpers"; } // name sorts to start of helpers + virtual ObjectFile::Atom::SymbolTableInclusion getSymbolTableInclusion() const { return ObjectFile::Atom::kSymbolTableIn; } + virtual ObjectFile::Atom::Scope getScope() const { return ObjectFile::Atom::scopeLinkageUnit; } + virtual uint64_t getSize() const; + virtual const char* getSectionName() const { return "__stub_helper"; } + virtual std::vector& getReferences() const { return (std::vector&)(fReferences); } + virtual void copyRawContent(uint8_t buffer[]) const; + virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); } +protected: + using WriterAtom::fWriter; + std::vector fReferences; +}; + template class StubHelperAtom : public WriterAtom { public: - StubHelperAtom(Writer& writer, ObjectFile::Atom& target, ObjectFile::Atom& lazyPointer, bool forLazyDylib); + StubHelperAtom(Writer& writer, ObjectFile::Atom& target, + LazyPointerAtom& lazyPointer, bool forLazyDylib) + : WriterAtom(writer, Segment::fgTextSegment), fName(stubName(target.getName())), + fTarget(target), fLazyPointerAtom(lazyPointer) { + writer.fAllSynthesizedStubHelpers.push_back(this); + } + virtual const char* getName() const { return fName; } virtual ObjectFile::Atom::Scope getScope() const { return ObjectFile::Atom::scopeLinkageUnit; } - virtual uint64_t getSize() const; virtual const char* getSectionName() const { return "__stub_helper"; } virtual std::vector& getReferences() const { return (std::vector&)(fReferences); } - virtual void copyRawContent(uint8_t buffer[]) const; ObjectFile::Atom* getTarget() { return &fTarget; } -private: + virtual ObjectFile::Alignment getAlignment() const { return ObjectFile::Alignment(0); } +protected: static const char* stubName(const char* importName); using WriterAtom::fWriter; const char* fName; ObjectFile::Atom& fTarget; + LazyPointerAtom& fLazyPointerAtom; std::vector fReferences; }; + +template +class ClassicStubHelperAtom : public StubHelperAtom +{ +public: + ClassicStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib); + + virtual uint64_t getSize() const; + virtual void copyRawContent(uint8_t buffer[]) const; +}; + + +template +class HybridStubHelperAtom : public StubHelperAtom +{ +public: + HybridStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib); + + virtual uint64_t getSize() const; + virtual void copyRawContent(uint8_t buffer[]) const; + static class HybridStubHelperHelperAtom* fgHelperHelperAtom; +}; +template class HybridStubHelperHelperAtom* HybridStubHelperAtom::fgHelperHelperAtom = NULL; + +template +class FastStubHelperAtom : public StubHelperAtom +{ +public: + FastStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib); + virtual uint64_t getSize() const; + virtual void copyRawContent(uint8_t buffer[]) const; + static FastStubHelperHelperAtom* fgHelperHelperAtom; +}; +template FastStubHelperHelperAtom* FastStubHelperAtom::fgHelperHelperAtom = NULL; + + template class LazyPointerAtom : public WriterAtom @@ -1056,6 +1607,8 @@ public: virtual std::vector& getReferences() const { return (std::vector&)(fReferences); } virtual void copyRawContent(uint8_t buffer[]) const; ObjectFile::Atom* getTarget() { return &fExternalTarget; } + void setLazyBindingInfoOffset(uint32_t off) { fLazyBindingOffset = off; } + uint32_t getLazyBindingInfoOffset() { return fLazyBindingOffset; } private: using WriterAtom::fWriter; static const char* lazyPointerName(const char* importName); @@ -1064,6 +1617,7 @@ private: ObjectFile::Atom& fExternalTarget; std::vector fReferences; bool fForLazyDylib; + uint32_t fLazyBindingOffset; }; @@ -1072,18 +1626,20 @@ class NonLazyPointerAtom : public WriterAtom { public: NonLazyPointerAtom(Writer& writer, ObjectFile::Atom& target); + NonLazyPointerAtom(Writer& writer, const char* targetName); + NonLazyPointerAtom(Writer& writer); virtual const char* getName() const { return fName; } virtual ObjectFile::Atom::Scope getScope() const { return ObjectFile::Atom::scopeLinkageUnit; } virtual uint64_t getSize() const { return sizeof(typename A::P::uint_t); } - virtual const char* getSectionName() const { return "__nl_symbol_ptr"; } + virtual const char* getSectionName() const { return (fWriter.fOptions.outputKind() == Options::kKextBundle) ? "__got" : "__nl_symbol_ptr"; } virtual std::vector& getReferences() const { return (std::vector&)(fReferences); } virtual void copyRawContent(uint8_t buffer[]) const; - ObjectFile::Atom* getTarget() { return &fTarget; } + ObjectFile::Atom* getTarget() { return fTarget; } private: using WriterAtom::fWriter; static const char* nonlazyPointerName(const char* importName); const char* fName; - ObjectFile::Atom& fTarget; + ObjectFile::Atom* fTarget; std::vector fReferences; }; @@ -1113,16 +1669,19 @@ public: WriterReference(uint32_t offset, Kinds kind, ObjectFile::Atom* target, uint32_t toOffset=0, ObjectFile::Atom* fromTarget=NULL, uint32_t fromOffset=0) - : fKind(kind), fFixUpOffsetInSrc(offset), fTarget(target), + : fKind(kind), fFixUpOffsetInSrc(offset), fTarget(target), fTargetName(target->getName()), fTargetOffset(toOffset), fFromTarget(fromTarget), fFromTargetOffset(fromOffset) {} + WriterReference(uint32_t offset, Kinds kind, const char* targetName) + : fKind(kind), fFixUpOffsetInSrc(offset), fTarget(NULL), fTargetName(targetName), + fTargetOffset(0), fFromTarget(NULL), fFromTargetOffset(0) {} virtual ~WriterReference() {} - virtual ObjectFile::Reference::TargetBinding getTargetBinding() const { return ObjectFile::Reference::kBoundDirectly; } + virtual ObjectFile::Reference::TargetBinding getTargetBinding() const { return (fTarget != NULL) ? ObjectFile::Reference::kBoundDirectly : ObjectFile::Reference::kUnboundByName; } virtual ObjectFile::Reference::TargetBinding getFromTargetBinding() const { return (fFromTarget != NULL) ? ObjectFile::Reference::kBoundDirectly : ObjectFile::Reference::kDontBind; } virtual uint8_t getKind() const { return (uint8_t)fKind; } virtual uint64_t getFixUpOffset() const { return fFixUpOffsetInSrc; } - virtual const char* getTargetName() const { return fTarget->getName(); } + virtual const char* getTargetName() const { return fTargetName; } virtual ObjectFile::Atom& getTarget() const { return *fTarget; } virtual uint64_t getTargetOffset() const { return fTargetOffset; } virtual ObjectFile::Atom& getFromTarget() const { return *fFromTarget; } @@ -1138,41 +1697,48 @@ private: Kinds fKind; uint32_t fFixUpOffsetInSrc; ObjectFile::Atom* fTarget; + const char* fTargetName; uint32_t fTargetOffset; ObjectFile::Atom* fFromTarget; uint32_t fFromTargetOffset; }; +template +const char* StubHelperAtom::stubName(const char* name) +{ + char* buf; + asprintf(&buf, "%s$stubHelper", name); + return buf; +} template <> -StubHelperAtom::StubHelperAtom(Writer& writer, ObjectFile::Atom& target, - ObjectFile::Atom& lazyPointer, bool forLazyDylib) - : WriterAtom(writer, Segment::fgTextSegment), fName(stubName(target.getName())), fTarget(target) +ClassicStubHelperAtom::ClassicStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) { - writer.fAllSynthesizedStubHelpers.push_back(this); - - fReferences.push_back(new WriterReference(3, x86_64::kPCRel32, &lazyPointer)); + fReferences.push_back(new WriterReference(3, x86_64::kPCRel32, &fLazyPointerAtom)); if ( forLazyDylib ) { - if ( writer.fDyldLazyDylibHelper == NULL ) + if ( fWriter.fDyldLazyDylibHelper == NULL ) throw "symbol dyld_lazy_dylib_stub_binding_helper not defined (usually in lazydylib1.o)"; - fReferences.push_back(new WriterReference(8, x86_64::kPCRel32, writer.fDyldLazyDylibHelper)); + fReferences.push_back(new WriterReference(8, x86_64::kPCRel32, fWriter.fDyldLazyDylibHelper)); } else { - if ( writer.fDyldHelper == NULL ) + if ( fWriter.fDyldClassicHelperAtom == NULL ) throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; - fReferences.push_back(new WriterReference(8, x86_64::kPCRel32, writer.fDyldHelper)); + fReferences.push_back(new WriterReference(8, x86_64::kPCRel32, fWriter.fDyldClassicHelperAtom)); } } + template <> -uint64_t StubHelperAtom::getSize() const +uint64_t ClassicStubHelperAtom::getSize() const { return 12; } template <> -void StubHelperAtom::copyRawContent(uint8_t buffer[]) const +void ClassicStubHelperAtom::copyRawContent(uint8_t buffer[]) const { buffer[0] = 0x4C; // lea foo$lazy_ptr(%rip),%r11 buffer[1] = 0x8D; @@ -1189,49 +1755,479 @@ void StubHelperAtom::copyRawContent(uint8_t buffer[]) const } -template -const char* StubHelperAtom::stubName(const char* name) +template <> +FastStubHelperHelperAtom::FastStubHelperHelperAtom(Writer& writer) + : WriterAtom(writer, Segment::fgTextSegment) { - char* buf; - asprintf(&buf, "%s$stubHelper", name); - return buf; + fReferences.push_back(new WriterReference(3, x86_64::kPCRel32, new NonLazyPointerAtom(writer))); + fReferences.push_back(new WriterReference(11, x86_64::kPCRel32, writer.fFastStubGOTAtom)); } - -// specialize lazy pointer for x86_64 to initially pointer to stub helper template <> -LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) - : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), - fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib) +uint64_t FastStubHelperHelperAtom::getSize() const { - if ( forLazyDylib ) - writer.fAllSynthesizedLazyDylibPointers.push_back(this); - else - writer.fAllSynthesizedLazyPointers.push_back(this); - - StubHelperAtom* helper = new StubHelperAtom(writer, target, *this, forLazyDylib); - fReferences.push_back(new WriterReference(0, x86_64::kPointer, helper)); + return 16; } -// specialize lazy pointer for x86 to initially pointer to second half of stub template <> -LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) - : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), - fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib) +void FastStubHelperHelperAtom::copyRawContent(uint8_t buffer[]) const { - if ( forLazyDylib ) - writer.fAllSynthesizedLazyDylibPointers.push_back(this); - else - writer.fAllSynthesizedLazyPointers.push_back(this); + buffer[0] = 0x4C; // leaq dyld_mageLoaderCache(%rip),%r11 + buffer[1] = 0x8D; + buffer[2] = 0x1D; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x00; + buffer[6] = 0x00; + buffer[7] = 0x41; // pushq %r11 + buffer[8] = 0x53; + buffer[9] = 0xFF; // jmp *_fast_lazy_bind(%rip) + buffer[10] = 0x25; + buffer[11] = 0x00; + buffer[12] = 0x00; + buffer[13] = 0x00; + buffer[14] = 0x00; + buffer[15] = 0x90; // nop +} - // helper part of stub is 14 or 6 bytes into stub - fReferences.push_back(new WriterReference(0, x86::kPointer, &stub, writer.fSlideable ? 14 : 6)); + +template <> +HybridStubHelperHelperAtom::HybridStubHelperHelperAtom(Writer& writer) + : WriterAtom(writer, Segment::fgTextSegment) +{ + if ( writer.fDyldClassicHelperAtom == NULL ) + throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; + fReferences.push_back(new WriterReference(3, x86_64::kPCRel32_1, writer.fFastStubGOTAtom)); + fReferences.push_back(new WriterReference(13, x86_64::kPCRel32, new NonLazyPointerAtom(writer))); + fReferences.push_back(new WriterReference(21, x86_64::kPCRel32, writer.fFastStubGOTAtom)); + fReferences.push_back(new WriterReference(30, x86_64::kPCRel32, writer.fDyldClassicHelperAtom)); } -template -LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) - : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), - fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib) +template <> +uint64_t HybridStubHelperHelperAtom::getSize() const +{ + return 34; +} + +template <> +void HybridStubHelperHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x48; // cmpl $0x00,_fast_lazy_bind + buffer[1] = 0x83; + buffer[2] = 0x3D; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x00; + buffer[6] = 0x00; + buffer[7] = 0x00; + buffer[8] = 0x74; // je 16 + buffer[9] = 0x0F; + buffer[10] = 0x4C; // leaq imageCache(%rip),%r11 + buffer[11] = 0x8D; + buffer[12] = 0x1D; + buffer[13] = 0x00; + buffer[14] = 0x00; + buffer[15] = 0x00; + buffer[16] = 0x00; + buffer[17] = 0x41; // pushq %r11 + buffer[18] = 0x53; + buffer[19] = 0xFF; // jmp *_fast_lazy_bind(%rip) + buffer[20] = 0x25; + buffer[21] = 0x00; + buffer[22] = 0x00; + buffer[23] = 0x00; + buffer[24] = 0x00; + buffer[25] = 0x48; // addq $8,%rsp + buffer[26] = 0x83; + buffer[27] = 0xC4; + buffer[28] = 0x08; + buffer[29] = 0xE9; // jmp dyld_stub_binding_helper + buffer[30] = 0x00; + buffer[31] = 0x00; + buffer[32] = 0x00; + buffer[33] = 0x00; +} + + +template <> +HybridStubHelperAtom::HybridStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) +{ + if ( fgHelperHelperAtom == NULL ) { + fgHelperHelperAtom = new HybridStubHelperHelperAtom::HybridStubHelperHelperAtom(fWriter); + fWriter.fAllSynthesizedStubHelpers.push_back(fgHelperHelperAtom); + } + fReferences.push_back(new WriterReference(8, x86_64::kPCRel32, &fLazyPointerAtom)); + fReferences.push_back(new WriterReference(13, x86_64::kPCRel32, fgHelperHelperAtom)); +} + +template <> +uint64_t HybridStubHelperAtom::getSize() const +{ + return 18; +} + +template <> +void HybridStubHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushq $lazy-info-offset + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x4C; // lea foo$lazy_ptr(%rip),%r11 + buffer[6] = 0x8D; + buffer[7] = 0x1D; + buffer[8] = 0x00; + buffer[9] = 0x00; + buffer[10] = 0x00; + buffer[11] = 0x00; + buffer[12] = 0xE9; // jmp helper-helper + buffer[13] = 0x00; + buffer[14] = 0x00; + buffer[15] = 0x00; + buffer[16] = 0x00; + buffer[17] = 0x90; // nop + + // the lazy binding info is created later than this helper atom, so there + // is no Reference to update. Instead we blast the offset here. + uint32_t offset; + LittleEndian::set32(offset, fLazyPointerAtom.getLazyBindingInfoOffset()); + memcpy(&buffer[1], &offset, 4); +} + +template <> +FastStubHelperAtom::FastStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) +{ + if ( fgHelperHelperAtom == NULL ) { + fgHelperHelperAtom = new FastStubHelperHelperAtom::FastStubHelperHelperAtom(fWriter); + fWriter.fAllSynthesizedStubHelpers.push_back(fgHelperHelperAtom); + } + fReferences.push_back(new WriterReference(6, x86_64::kPCRel32, fgHelperHelperAtom)); +} + +template <> +uint64_t FastStubHelperAtom::getSize() const +{ + return 10; +} + +template <> +void FastStubHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushq $lazy-info-offset + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0xE9; // jmp helperhelper + buffer[6] = 0x00; + buffer[7] = 0x00; + buffer[8] = 0x00; + buffer[9] = 0x00; + + // the lazy binding info is created later than this helper atom, so there + // is no Reference to update. Instead we blast the offset here. + uint32_t offset; + LittleEndian::set32(offset, fLazyPointerAtom.getLazyBindingInfoOffset()); + memcpy(&buffer[1], &offset, 4); +} + +template <> +FastStubHelperHelperAtom::FastStubHelperHelperAtom(Writer& writer) + : WriterAtom(writer, Segment::fgTextSegment) +{ + fReferences.push_back(new WriterReference(1, x86::kAbsolute32, new NonLazyPointerAtom(writer))); + fReferences.push_back(new WriterReference(7, x86::kAbsolute32, writer.fFastStubGOTAtom)); +} + +template <> +uint64_t FastStubHelperHelperAtom::getSize() const +{ + return 12; +} + +template <> +void FastStubHelperHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushl $dyld_ImageLoaderCache + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0xFF; // jmp *_fast_lazy_bind(%rip) + buffer[6] = 0x25; + buffer[7] = 0x00; + buffer[8] = 0x00; + buffer[9] = 0x00; + buffer[10] = 0x00; + buffer[11] = 0x90; // nop +} + + +template <> +HybridStubHelperHelperAtom::HybridStubHelperHelperAtom(Writer& writer) + : WriterAtom(writer, Segment::fgTextSegment) +{ + if ( writer.fDyldClassicHelperAtom == NULL ) + throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; + fReferences.push_back(new WriterReference(2, x86::kAbsolute32, writer.fFastStubGOTAtom)); + fReferences.push_back(new WriterReference(18, x86::kPCRel32, writer.fDyldClassicHelperAtom)); + fReferences.push_back(new WriterReference(26, x86::kAbsolute32, new NonLazyPointerAtom(writer))); + fReferences.push_back(new WriterReference(32, x86::kAbsolute32, writer.fFastStubGOTAtom)); +} + +template <> +uint64_t HybridStubHelperHelperAtom::getSize() const +{ + return 36; +} + + +template <> +void HybridStubHelperHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x83; // cmpl $0x00,_fast_lazy_bind + buffer[1] = 0x3D; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x00; + buffer[6] = 0x00; + buffer[7] = 0x75; // jne 22 + buffer[8] = 0x0D; + buffer[9] = 0x89; // %eax,4(%esp) + buffer[10] = 0x44; + buffer[11] = 0x24; + buffer[12] = 0x04; + buffer[13] = 0x58; // popl %eax + buffer[14] = 0x87; // xchgl (%esp),%eax + buffer[15] = 0x04; + buffer[16] = 0x24; + buffer[17] = 0xE9; // jmpl dyld_stub_binding_helper + buffer[18] = 0x00; + buffer[19] = 0x00; + buffer[20] = 0x00; + buffer[21] = 0x00; + buffer[22] = 0x83; // addl $0x04,%esp + buffer[23] = 0xC4; + buffer[24] = 0x04; + buffer[25] = 0x68; // pushl imageloadercahce + buffer[26] = 0x00; + buffer[27] = 0x00; + buffer[28] = 0x00; + buffer[29] = 0x00; + buffer[30] = 0xFF; // jmp *_fast_lazy_bind(%rip) + buffer[31] = 0x25; + buffer[32] = 0x00; + buffer[33] = 0x00; + buffer[34] = 0x00; + buffer[35] = 0x00; +} + + +template <> +ClassicStubHelperAtom::ClassicStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) +{ + fReferences.push_back(new WriterReference(1, x86::kAbsolute32, &fLazyPointerAtom)); + if ( forLazyDylib ) { + if ( fWriter.fDyldLazyDylibHelper == NULL ) + throw "symbol dyld_lazy_dylib_stub_binding_helper not defined (usually in lazydylib1.o)"; + fReferences.push_back(new WriterReference(6, x86::kPCRel32, fWriter.fDyldLazyDylibHelper)); + } + else { + if ( fWriter.fDyldClassicHelperAtom == NULL ) + throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; + fReferences.push_back(new WriterReference(6, x86::kPCRel32, fWriter.fDyldClassicHelperAtom)); + } +} + +template <> +uint64_t ClassicStubHelperAtom::getSize() const +{ + return 10; +} + +template <> +void ClassicStubHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushl $foo$lazy_ptr + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0xE9; // jmp helperhelper + buffer[6] = 0x00; + buffer[7] = 0x00; + buffer[8] = 0x00; + buffer[9] = 0x00; +} + +template <> +HybridStubHelperAtom::HybridStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) +{ + if ( fgHelperHelperAtom == NULL ) { + fgHelperHelperAtom = new HybridStubHelperHelperAtom::HybridStubHelperHelperAtom(fWriter); + fWriter.fAllSynthesizedStubHelpers.push_back(fgHelperHelperAtom); + } + fReferences.push_back(new WriterReference(6, x86::kAbsolute32, &fLazyPointerAtom)); + fReferences.push_back(new WriterReference(11, x86::kPCRel32, fgHelperHelperAtom)); +} + + +template <> +uint64_t HybridStubHelperAtom::getSize() const +{ + return 16; +} + +template <> +void HybridStubHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushl $lazy-info-offset + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x68; // pushl $foo$lazy_ptr + buffer[6] = 0x00; + buffer[7] = 0x00; + buffer[8] = 0x00; + buffer[9] = 0x00; + buffer[10] = 0xE9; // jmp dyld_hybrid_stub_binding_helper + buffer[11] = 0x00; + buffer[12] = 0x00; + buffer[13] = 0x00; + buffer[14] = 0x00; + buffer[15] = 0x90; // nop + + // the lazy binding info is created later than this helper atom, so there + // is no Reference to update. Instead we blast the offset here. + uint32_t offset; + LittleEndian::set32(offset, fLazyPointerAtom.getLazyBindingInfoOffset()); + memcpy(&buffer[1], &offset, 4); +} + + +template <> +FastStubHelperAtom::FastStubHelperAtom(Writer& writer, ObjectFile::Atom& target, + class LazyPointerAtom& lazyPointer, bool forLazyDylib) + : StubHelperAtom(writer, target, lazyPointer, forLazyDylib) +{ + if ( fgHelperHelperAtom == NULL ) { + fgHelperHelperAtom = new FastStubHelperHelperAtom::FastStubHelperHelperAtom(fWriter); + fWriter.fAllSynthesizedStubHelpers.push_back(fgHelperHelperAtom); + } + fReferences.push_back(new WriterReference(6, x86::kPCRel32, fgHelperHelperAtom)); +} + + +template <> +uint64_t FastStubHelperAtom::getSize() const +{ + return 10; +} + +template <> +void FastStubHelperAtom::copyRawContent(uint8_t buffer[]) const +{ + buffer[0] = 0x68; // pushl $lazy-info-offset + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0xE9; // jmp helperhelper + buffer[6] = 0x00; + buffer[7] = 0x00; + buffer[8] = 0x00; + buffer[9] = 0x00; + + // the lazy binding info is created later than this helper atom, so there + // is no Reference to update. Instead we blast the offset here. + uint32_t offset; + LittleEndian::set32(offset, fLazyPointerAtom.getLazyBindingInfoOffset()); + memcpy(&buffer[1], &offset, 4); +} + + + +// specialize lazy pointer for x86_64 to initially pointer to stub helper +template <> +LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) + : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), + fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib), fLazyBindingOffset(0) +{ + if ( forLazyDylib ) + writer.fAllSynthesizedLazyDylibPointers.push_back(this); + else + writer.fAllSynthesizedLazyPointers.push_back(this); + + ObjectFile::Atom* helper; + if ( writer.fOptions.makeCompressedDyldInfo() && !forLazyDylib ) { + if ( writer.fOptions.makeClassicDyldInfo() ) + // hybrid LINKEDIT, no fast bind info for weak symbols so use traditional helper + if ( writer.targetRequiresWeakBinding(target) ) + helper = new ClassicStubHelperAtom(writer, target, *this, forLazyDylib); + else + helper = new HybridStubHelperAtom(writer, target, *this, forLazyDylib); + else { + if ( target.getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) + helper = ⌖ + else + helper = new FastStubHelperAtom(writer, target, *this, forLazyDylib); + } + } + else { + helper = new ClassicStubHelperAtom(writer, target, *this, forLazyDylib); + } + fReferences.push_back(new WriterReference(0, x86_64::kPointer, helper)); +} + + +// specialize lazy pointer for x86 to initially pointer to stub helper +template <> +LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) + : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), + fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib) +{ + if ( forLazyDylib ) + writer.fAllSynthesizedLazyDylibPointers.push_back(this); + else + writer.fAllSynthesizedLazyPointers.push_back(this); + + ObjectFile::Atom* helper; + if ( writer.fOptions.makeCompressedDyldInfo() && !forLazyDylib ) { + if ( writer.fOptions.makeClassicDyldInfo() ) { + // hybrid LINKEDIT, no fast bind info for weak symbols so use traditional helper + if ( writer.targetRequiresWeakBinding(target) ) + helper = new ClassicStubHelperAtom(writer, target, *this, forLazyDylib); + else + helper = new HybridStubHelperAtom(writer, target, *this, forLazyDylib); + } + else { + if ( target.getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) + helper = ⌖ + else + helper = new FastStubHelperAtom(writer, target, *this, forLazyDylib); + } + } + else { + helper = new ClassicStubHelperAtom(writer, target, *this, forLazyDylib); + } + fReferences.push_back(new WriterReference(0, x86::kPointer, helper)); +} + +template +LazyPointerAtom::LazyPointerAtom(Writer& writer, ObjectFile::Atom& target, StubAtom& stub, bool forLazyDylib) + : WriterAtom(writer, Segment::fgDataSegment), fName(lazyPointerName(target.getName())), fTarget(target), + fExternalTarget(*stub.getTarget()), fForLazyDylib(forLazyDylib) { if ( forLazyDylib ) writer.fAllSynthesizedLazyDylibPointers.push_back(this); @@ -1260,13 +2256,27 @@ void LazyPointerAtom::copyRawContent(uint8_t buffer[]) const template NonLazyPointerAtom::NonLazyPointerAtom(Writer& writer, ObjectFile::Atom& target) - : WriterAtom(writer, Segment::fgDataSegment), fName(nonlazyPointerName(target.getName())), fTarget(target) + : WriterAtom(writer, Segment::fgDataSegment), fName(nonlazyPointerName(target.getName())), fTarget(&target) { writer.fAllSynthesizedNonLazyPointers.push_back(this); - fReferences.push_back(new WriterReference(0, A::kPointer, &target)); } +template +NonLazyPointerAtom::NonLazyPointerAtom(Writer& writer) + : WriterAtom(writer, Segment::fgDataSegment), fName("none"), fTarget(NULL) +{ + writer.fAllSynthesizedNonLazyPointers.push_back(this); +} + +template +NonLazyPointerAtom::NonLazyPointerAtom(Writer& writer, const char* targetName) + : WriterAtom(writer, Segment::fgDataSegment), fName(nonlazyPointerName(targetName)), fTarget(NULL) +{ + writer.fAllSynthesizedNonLazyPointers.push_back(this); + fReferences.push_back(new WriterReference(0, A::kPointer, targetName)); +} + template const char* NonLazyPointerAtom::nonlazyPointerName(const char* name) { @@ -1336,9 +2346,9 @@ StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool forL lp = new LazyPointerAtom(writer, *writer.fDyldLazyDylibHelper, *this, forLazyDylib); } else { - if ( writer.fDyldHelper == NULL ) + if ( writer.fDyldClassicHelperAtom == NULL ) throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; - lp = new LazyPointerAtom(writer, *writer.fDyldHelper, *this, forLazyDylib); + lp = new LazyPointerAtom(writer, *writer.fDyldClassicHelperAtom, *this, forLazyDylib); } } if ( pic() ) { @@ -1366,9 +2376,9 @@ StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool lp = new LazyPointerAtom(writer, *writer.fDyldLazyDylibHelper, *this, forLazyDylib); } else { - if ( writer.fDyldHelper == NULL ) + if ( writer.fDyldClassicHelperAtom == NULL ) throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; - lp = new LazyPointerAtom(writer, *writer.fDyldHelper, *this, forLazyDylib); + lp = new LazyPointerAtom(writer, *writer.fDyldClassicHelperAtom, *this, forLazyDylib); } if ( pic() ) { // picbase is 8 bytes into atom @@ -1381,38 +2391,16 @@ StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool } } -// specialize to put x86 fast stub in __IMPORT segment with no lazy pointer template <> StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool forLazyDylib) - : WriterAtom(writer, (writer.fOptions.slowx86Stubs() || forLazyDylib) ? Segment::fgTextSegment : - ( writer.fOptions.readOnlyx86Stubs() ? Segment::fgROImportSegment : Segment::fgImportSegment)), - fTarget(target), fForLazyDylib(forLazyDylib) + : WriterAtom(writer, (writer.fOptions.makeCompressedDyldInfo()|| forLazyDylib) ? Segment::fgTextSegment : Segment::fgImportSegment), + fName(NULL), fTarget(target), fForLazyDylib(forLazyDylib) { - if ( writer.fOptions.slowx86Stubs() || forLazyDylib ) { + if ( writer.fOptions.makeCompressedDyldInfo() || forLazyDylib ) { fName = stubName(target.getName()); - writer.fAllSynthesizedStubs.push_back(this); LazyPointerAtom* lp = new LazyPointerAtom(writer, target, *this, forLazyDylib); - ObjectFile::Atom* helper; - if ( forLazyDylib ) { - if ( writer.fDyldLazyDylibHelper == NULL ) - throw "symbol dyld_lazy_dylib_stub_binding_helper not defined (usually in lazydylib1.o)"; - helper = writer.fDyldLazyDylibHelper; - } - else { - if ( writer.fDyldHelper == NULL ) - throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; - helper = writer.fDyldHelper; - } - if ( pic() ) { - // picbase is 5 bytes into atom - fReferences.push_back(new WriterReference(8, x86::kPointerDiff, lp, 0, this, 5)); - fReferences.push_back(new WriterReference(16, x86::kPCRel32, helper)); - } - else { - fReferences.push_back(new WriterReference(2, x86::kAbsolute32, lp)); - fReferences.push_back(new WriterReference(7, x86::kAbsolute32, lp)); - fReferences.push_back(new WriterReference(12, x86::kPCRel32, helper)); - } + fReferences.push_back(new WriterReference(2, x86::kAbsolute32, lp)); + writer.fAllSynthesizedStubs.push_back(this); } else { if ( &target == NULL ) @@ -1424,6 +2412,7 @@ StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool forL } } + template <> StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool forLazyDylib) : WriterAtom(writer, Segment::fgTextSegment), fName(stubName(target.getName())), fTarget(target) @@ -1455,9 +2444,9 @@ StubAtom::StubAtom(Writer& writer, ObjectFile::Atom& target, bool forL helper = writer.fDyldLazyDylibHelper; } else { - if ( writer.fDyldHelper == NULL ) + if ( writer.fDyldClassicHelperAtom == NULL ) throw "symbol dyld_stub_binding_helper not defined (usually in crt1.o/dylib1.o/bundle1.o)"; - helper = writer.fDyldHelper; + helper = writer.fDyldClassicHelperAtom; } lp = new LazyPointerAtom(writer, *helper, *this, forLazyDylib); } @@ -1497,13 +2486,10 @@ uint64_t StubAtom::getSize() const template <> uint64_t StubAtom::getSize() const { - if ( fWriter.fOptions.slowx86Stubs() || fForLazyDylib ) { - if ( pic() ) - return 20; - else - return 16; - } - return 5; + if ( fWriter.fOptions.makeCompressedDyldInfo() || fForLazyDylib ) + return 6; + else + return 5; } template <> @@ -1515,10 +2501,10 @@ uint64_t StubAtom::getSize() const template <> ObjectFile::Alignment StubAtom::getAlignment() const { - if ( fWriter.fOptions.slowx86Stubs() || fForLazyDylib ) - return 2; + if ( fWriter.fOptions.makeCompressedDyldInfo() || fForLazyDylib ) + return 1; else - return 0; // special case x86 fast stubs to be byte aligned + return 0; // special case x86 self-modifying stubs to be byte aligned } template <> @@ -1566,47 +2552,13 @@ void StubAtom::copyRawContent(uint8_t buffer[]) const template <> void StubAtom::copyRawContent(uint8_t buffer[]) const { - if ( fWriter.fOptions.slowx86Stubs() || fForLazyDylib ) { - if ( pic() ) { - buffer[0] = 0xE8; // call picbase - buffer[1] = 0x00; - buffer[2] = 0x00; - buffer[3] = 0x00; - buffer[4] = 0x00; - buffer[5] = 0x58; // pop eax - buffer[6] = 0x8D; // lea foo$lazy_pointer-picbase(eax),eax - buffer[7] = 0x80; - buffer[8] = 0x00; - buffer[9] = 0x00; - buffer[10] = 0x00; - buffer[11] = 0x00; - buffer[12] = 0xFF; // jmp *(eax) - buffer[13] = 0x20; - buffer[14] = 0x50; // push eax - buffer[15] = 0xE9; // jump dyld_stub_binding_helper - buffer[16] = 0x00; - buffer[17] = 0x00; - buffer[18] = 0x00; - buffer[19] = 0x00; - } - else { - buffer[0] = 0xFF; // jmp *foo$lazy_pointer - buffer[1] = 0x25; - buffer[2] = 0x00; - buffer[3] = 0x00; - buffer[4] = 0x00; - buffer[5] = 0x00; - buffer[6] = 0x68; // pushl $foo$lazy_pointer - buffer[7] = 0x00; - buffer[8] = 0x00; - buffer[9] = 0x00; - buffer[10] = 0x00; - buffer[11] = 0xE9; // jump dyld_stub_binding_helper - buffer[12] = 0x00; - buffer[13] = 0x00; - buffer[14] = 0x00; - buffer[15] = 0x00; - } + if ( fWriter.fOptions.makeCompressedDyldInfo() || fForLazyDylib ) { + buffer[0] = 0xFF; // jmp *foo$lazy_pointer + buffer[1] = 0x25; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + buffer[5] = 0x00; } else { if ( fWriter.fOptions.prebind() ) { @@ -1655,11 +2607,11 @@ void StubAtom::copyRawContent(uint8_t buffer[]) const } } -// x86_64 stubs are 7 bytes and need no alignment +// x86_64 stubs are 6 bytes template <> ObjectFile::Alignment StubAtom::getAlignment() const { - return 0; + return 1; } template <> @@ -1683,13 +2635,10 @@ const char* StubAtom::getSectionName() const template <> const char* StubAtom::getSectionName() const { - if ( fWriter.fOptions.slowx86Stubs() || fForLazyDylib ) { - if ( pic() ) - return "__picsymbol_stub"; - else - return "__symbol_stub"; - } - return "__jump_table"; + if ( fWriter.fOptions.makeCompressedDyldInfo() || fForLazyDylib ) + return "__symbol_stub"; + else + return "__jump_table"; } @@ -1720,14 +2669,17 @@ struct ExternalRelocSorter template Writer::Writer(const char* path, Options& options, std::vector& dynamicLibraries) : ExecutableFile::Writer(dynamicLibraries), fFilePath(strdup(path)), fOptions(options), - fAllAtoms(NULL), fStabs(NULL), fLoadCommandsSection(NULL), - fLoadCommandsSegment(NULL), fEncryptionLoadCommand(NULL), fSegmentCommands(NULL), - fSymbolTableCommands(NULL), fHeaderPadding(NULL), - fUUIDAtom(NULL), fPadSegmentInfo(NULL), fEntryPoint( NULL), fDyldHelper(NULL), fDyldLazyDylibHelper(NULL), - fSectionRelocationsAtom(NULL), fLocalRelocationsAtom(NULL), fExternalRelocationsAtom(NULL), + fAllAtoms(NULL), fStabs(NULL), fRegularDefAtomsThatOverrideADylibsWeakDef(NULL), fLoadCommandsSection(NULL), + fLoadCommandsSegment(NULL), fMachHeaderAtom(NULL), fEncryptionLoadCommand(NULL), fSegmentCommands(NULL), + fSymbolTableCommands(NULL), fHeaderPadding(NULL), fUnwindInfoAtom(NULL), + fUUIDAtom(NULL), fPadSegmentInfo(NULL), fEntryPoint( NULL), + fDyldClassicHelperAtom(NULL), fDyldCompressedHelperAtom(NULL), fDyldLazyDylibHelper(NULL), + fSectionRelocationsAtom(NULL), fCompressedRebaseInfoAtom(NULL), fCompressedBindingInfoAtom(NULL), + fCompressedWeakBindingInfoAtom(NULL), fCompressedLazyBindingInfoAtom(NULL), fCompressedExportInfoAtom(NULL), + fLocalRelocationsAtom(NULL), fExternalRelocationsAtom(NULL), fSymbolTableAtom(NULL), fSplitCodeToDataContentAtom(NULL), fIndirectTableAtom(NULL), fModuleInfoAtom(NULL), - fStringsAtom(NULL), fPageZeroAtom(NULL), fSymbolTable(NULL), fSymbolTableCount(0), fSymbolTableStabsCount(0), - fSymbolTableLocalCount(0), fSymbolTableExportCount(0), fSymbolTableImportCount(0), + fStringsAtom(NULL), fPageZeroAtom(NULL), fFastStubGOTAtom(NULL), fSymbolTable(NULL), fSymbolTableCount(0), + fSymbolTableStabsCount(0), fSymbolTableLocalCount(0), fSymbolTableExportCount(0), fSymbolTableImportCount(0), fLargestAtomSize(1), fEmitVirtualSections(false), fHasWeakExports(false), fReferencesWeakImports(false), fCanScatter(false), fWritableSegmentPastFirst4GB(false), fNoReExportedDylibs(false), @@ -1741,8 +2693,10 @@ Writer::Writer(const char* path, Options& options, std::vector(*this)); if ( fOptions.outputKind() == Options::kDynamicExecutable ) fWriterSynthesizedAtoms.push_back(new DsoHandleAtom(*this)); - fWriterSynthesizedAtoms.push_back(new MachHeaderAtom(*this)); + fWriterSynthesizedAtoms.push_back(fMachHeaderAtom = new MachHeaderAtom(*this)); fWriterSynthesizedAtoms.push_back(new SegmentLoadCommandsAtom(*this)); + if ( fOptions.makeCompressedDyldInfo() ) + fWriterSynthesizedAtoms.push_back(new DyldInfoLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(new SymbolTableLoadCommandsAtom(*this)); if ( fOptions.outputKind() == Options::kDynamicExecutable ) fWriterSynthesizedAtoms.push_back(new DyldLoadCommandsAtom(*this)); @@ -1751,19 +2705,43 @@ Writer::Writer(const char* path, Options& options, std::vector(*this)); fWriterSynthesizedAtoms.push_back(fHeaderPadding = new LoadCommandsPaddingAtom(*this)); + if ( fOptions.needsUnwindInfoSection() ) + fWriterSynthesizedAtoms.push_back(fUnwindInfoAtom = new UnwindInfoAtom(*this)); fWriterSynthesizedAtoms.push_back(fSectionRelocationsAtom = new SectionRelocationsLinkEditAtom(*this)); - fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); + if ( fOptions.makeCompressedDyldInfo() ) { + fWriterSynthesizedAtoms.push_back(fCompressedRebaseInfoAtom = new CompressedRebaseInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedBindingInfoAtom = new CompressedBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedWeakBindingInfoAtom = new CompressedWeakBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedLazyBindingInfoAtom = new CompressedLazyBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedExportInfoAtom = new CompressedExportInfoLinkEditAtom(*this)); + } + if ( fOptions.makeClassicDyldInfo() ) + fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fSymbolTableAtom = new SymbolTableLinkEditAtom(*this)); + if ( fOptions.makeClassicDyldInfo() ) + fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fIndirectTableAtom = new IndirectTableLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fStringsAtom = new StringsLinkEditAtom(*this)); + break; + case Options::kPreload: + fWriterSynthesizedAtoms.push_back(fMachHeaderAtom = new MachHeaderAtom(*this)); + fWriterSynthesizedAtoms.push_back(new SegmentLoadCommandsAtom(*this)); + fWriterSynthesizedAtoms.push_back(new SymbolTableLoadCommandsAtom(*this)); + fWriterSynthesizedAtoms.push_back(fUUIDAtom = new UUIDLoadCommandAtom(*this)); + fWriterSynthesizedAtoms.push_back(new ThreadsLoadCommandsAtom(*this)); + fWriterSynthesizedAtoms.push_back(fHeaderPadding = new LoadCommandsPaddingAtom(*this)); + fWriterSynthesizedAtoms.push_back(fSectionRelocationsAtom = new SectionRelocationsLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fIndirectTableAtom = new IndirectTableLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fSymbolTableAtom = new SymbolTableLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fStringsAtom = new StringsLinkEditAtom(*this)); break; case Options::kDynamicLibrary: case Options::kDynamicBundle: fWriterSynthesizedAtoms.push_back(new DsoHandleAtom(*this)); - // fall through - case Options::kObjectFile: - fWriterSynthesizedAtoms.push_back(new MachHeaderAtom(*this)); + case Options::kKextBundle: + fWriterSynthesizedAtoms.push_back(fMachHeaderAtom = new MachHeaderAtom(*this)); fWriterSynthesizedAtoms.push_back(new SegmentLoadCommandsAtom(*this)); if ( fOptions.outputKind() == Options::kDynamicLibrary ) { fWriterSynthesizedAtoms.push_back(new DylibIDLoadCommandsAtom(*this)); @@ -1771,31 +2749,60 @@ Writer::Writer(const char* path, Options& options, std::vector(*this)); } fWriterSynthesizedAtoms.push_back(fUUIDAtom = new UUIDLoadCommandAtom(*this)); + if ( fOptions.makeCompressedDyldInfo() ) + fWriterSynthesizedAtoms.push_back(new DyldInfoLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(new SymbolTableLoadCommandsAtom(*this)); if ( fOptions.sharedRegionEligible() ) fWriterSynthesizedAtoms.push_back(new SegmentSplitInfoLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(fHeaderPadding = new LoadCommandsPaddingAtom(*this)); + if ( fOptions.needsUnwindInfoSection() ) + fWriterSynthesizedAtoms.push_back(fUnwindInfoAtom = new UnwindInfoAtom(*this)); fWriterSynthesizedAtoms.push_back(fSectionRelocationsAtom = new SectionRelocationsLinkEditAtom(*this)); - fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); + if ( fOptions.makeCompressedDyldInfo() ) { + fWriterSynthesizedAtoms.push_back(fCompressedRebaseInfoAtom = new CompressedRebaseInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedBindingInfoAtom = new CompressedBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedWeakBindingInfoAtom = new CompressedWeakBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedLazyBindingInfoAtom = new CompressedLazyBindingInfoLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fCompressedExportInfoAtom = new CompressedExportInfoLinkEditAtom(*this)); + } + if ( fOptions.makeClassicDyldInfo() ) + fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); if ( fOptions.sharedRegionEligible() ) { fWriterSynthesizedAtoms.push_back(fSplitCodeToDataContentAtom = new SegmentSplitInfoContentAtom(*this)); } fWriterSynthesizedAtoms.push_back(fSymbolTableAtom = new SymbolTableLinkEditAtom(*this)); - fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); - fWriterSynthesizedAtoms.push_back(fIndirectTableAtom = new IndirectTableLinkEditAtom(*this)); + if ( fOptions.makeClassicDyldInfo() ) + fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); + if ( fOptions.outputKind() != Options::kKextBundle ) + fWriterSynthesizedAtoms.push_back(fIndirectTableAtom = new IndirectTableLinkEditAtom(*this)); if ( this->needsModuleTable() ) fWriterSynthesizedAtoms.push_back(fModuleInfoAtom = new ModuleInfoLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fStringsAtom = new StringsLinkEditAtom(*this)); break; + case Options::kObjectFile: + fWriterSynthesizedAtoms.push_back(fMachHeaderAtom = new MachHeaderAtom(*this)); + fWriterSynthesizedAtoms.push_back(new SegmentLoadCommandsAtom(*this)); + fWriterSynthesizedAtoms.push_back(fUUIDAtom = new UUIDLoadCommandAtom(*this)); + fWriterSynthesizedAtoms.push_back(new SymbolTableLoadCommandsAtom(*this)); + fWriterSynthesizedAtoms.push_back(fHeaderPadding = new LoadCommandsPaddingAtom(*this)); + fWriterSynthesizedAtoms.push_back(fSectionRelocationsAtom = new SectionRelocationsLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fSymbolTableAtom = new SymbolTableLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fIndirectTableAtom = new IndirectTableLinkEditAtom(*this)); + fWriterSynthesizedAtoms.push_back(fStringsAtom = new StringsLinkEditAtom(*this)); + break; case Options::kDyld: fWriterSynthesizedAtoms.push_back(new DsoHandleAtom(*this)); - fWriterSynthesizedAtoms.push_back(new MachHeaderAtom(*this)); + fWriterSynthesizedAtoms.push_back(fMachHeaderAtom = new MachHeaderAtom(*this)); fWriterSynthesizedAtoms.push_back(new SegmentLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(new SymbolTableLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(new DyldLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(fUUIDAtom = new UUIDLoadCommandAtom(*this)); fWriterSynthesizedAtoms.push_back(new ThreadsLoadCommandsAtom(*this)); fWriterSynthesizedAtoms.push_back(fHeaderPadding = new LoadCommandsPaddingAtom(*this)); + if ( fOptions.needsUnwindInfoSection() ) + fWriterSynthesizedAtoms.push_back(fUnwindInfoAtom = new UnwindInfoAtom(*this)); fWriterSynthesizedAtoms.push_back(fLocalRelocationsAtom = new LocalRelocationsLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fSymbolTableAtom = new SymbolTableLinkEditAtom(*this)); fWriterSynthesizedAtoms.push_back(fExternalRelocationsAtom = new ExternalRelocationsLinkEditAtom(*this)); @@ -1835,6 +2842,10 @@ Writer::Writer(const char* path, Options& options, std::vector::Writer(const char* path, Options& options, std::vector::Writer(const char* path, Options& options, std::vector bool Writer::mightNeedPadSegment() { return false; } template ObjectFile::Atom* Writer::getUndefinedProxyAtom(const char* name) { - if ( fOptions.outputKind() == Options::kObjectFile ) { - // when doing -r -exported_symbols_list, don't creat proxy for a symbol + if ( fOptions.outputKind() == Options::kKextBundle ) { + return new UndefinedSymbolProxyAtom(*this, name); + } + else if ( fOptions.outputKind() == Options::kObjectFile ) { + // when doing -r -exported_symbols_list, don't create proxy for a symbol // that is supposed to be exported. We want an error instead // ld does not report error when -r is used and exported symbols are not defined. - if ( fOptions.hasExportRestrictList() && fOptions.shouldExport(name) ) + if ( fOptions.hasExportMaskList() && fOptions.shouldExport(name) ) return NULL; else return new UndefinedSymbolProxyAtom(*this, name); @@ -2001,6 +3019,59 @@ uint8_t Writer::ordinalForLibrary(ObjectFile::Reader* lib) throw "can't find ordinal for imported symbol"; } +template +bool Writer::targetRequiresWeakBinding(const ObjectFile::Atom& target) +{ + switch ( target.getDefinitionKind() ) { + case ObjectFile::Atom::kExternalWeakDefinition: + case ObjectFile::Atom::kWeakDefinition: + return true; + case ObjectFile::Atom::kExternalDefinition: + case ObjectFile::Atom::kAbsoluteSymbol: + case ObjectFile::Atom::kRegularDefinition: + case ObjectFile::Atom::kTentativeDefinition: + break; + } + return false; +} + +template +int Writer::compressedOrdinalForImortedAtom(ObjectFile::Atom* target) +{ + // flat namespace images use zero for all ordinals + if ( fOptions.nameSpace() != Options::kTwoLevelNameSpace ) + return BIND_SPECIAL_DYLIB_FLAT_LOOKUP; + + // is an UndefinedSymbolProxyAtom + ObjectFile::Reader* lib = target->getFile(); + if ( lib == this ) + if ( fOptions.nameSpace() == Options::kTwoLevelNameSpace ) + return BIND_SPECIAL_DYLIB_FLAT_LOOKUP; + + std::map::iterator pos; + switch ( target->getDefinitionKind() ) { + case ObjectFile::Atom::kExternalDefinition: + case ObjectFile::Atom::kExternalWeakDefinition: + pos = fLibraryToOrdinal.find(lib); + if ( pos != fLibraryToOrdinal.end() ) { + if ( pos->second == EXECUTABLE_ORDINAL ) + return BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; + else + return pos->second; + } + break; + case ObjectFile::Atom::kWeakDefinition: + throw "compressedOrdinalForImortedAtom() should not have been called on a weak definition"; + case ObjectFile::Atom::kAbsoluteSymbol: + case ObjectFile::Atom::kRegularDefinition: + case ObjectFile::Atom::kTentativeDefinition: + return BIND_SPECIAL_DYLIB_SELF; + } + + throw "can't find ordinal for imported symbol"; +} + + template ObjectFile::Atom& Writer::makeObjcInfoAtom(ObjectFile::Reader::ObjcConstraint objcContraint, bool objcReplacementClasses) { @@ -2011,20 +3082,27 @@ ObjectFile::Atom& Writer::makeObjcInfoAtom(ObjectFile::Reader::ObjcConstraint template uint64_t Writer::write(std::vector& atoms, std::vector& stabs, - class ObjectFile::Atom* entryPointAtom, class ObjectFile::Atom* dyldHelperAtom, + class ObjectFile::Atom* entryPointAtom, + class ObjectFile::Atom* dyldClassicHelperAtom, + class ObjectFile::Atom* dyldCompressedHelperAtom, class ObjectFile::Atom* dyldLazyDylibHelperAtom, bool createUUID, bool canScatter, ObjectFile::Reader::CpuConstraint cpuConstraint, - bool biggerThanTwoGigs, bool overridesDylibWeakDefines) + bool biggerThanTwoGigs, + std::set& atomsThatOverrideWeak, + bool hasExternalWeakDefinitions) { fAllAtoms = &atoms; fStabs = &stabs; fEntryPoint = entryPointAtom; - fDyldHelper = dyldHelperAtom; + fDyldClassicHelperAtom = dyldClassicHelperAtom; + fDyldCompressedHelperAtom = dyldCompressedHelperAtom; fDyldLazyDylibHelper = dyldLazyDylibHelperAtom; fCanScatter = canScatter; fCpuConstraint = cpuConstraint; fBiggerThanTwoGigs = biggerThanTwoGigs; - fHasWeakExports = overridesDylibWeakDefines; // dyld needs to search this image as if it had weak exports + fHasWeakExports = hasExternalWeakDefinitions; // dyld needs to search this image as if it had weak exports + fRegularDefAtomsThatOverrideADylibsWeakDef = &atomsThatOverrideWeak; + try { // Set for create UUID @@ -2040,6 +3118,9 @@ uint64_t Writer::write(std::vector& atoms, // create inter-library stubs synthesizeStubs(); + // create table of unwind info + synthesizeUnwindInfoTable(); + // create SegmentInfo and SectionInfo objects and assign all atoms to a section partitionIntoSections(); @@ -2052,6 +3133,17 @@ uint64_t Writer::write(std::vector& atoms, // if need to add branch islands, reassign file offsets if ( addBranchIslands() ) assignFileOffsets(); + + // now that addresses are assigned, create unwind info + if ( fUnwindInfoAtom != NULL ) { + fUnwindInfoAtom->generate(); + // re-layout + adjustLoadCommandsAndPadding(); + assignFileOffsets(); + } + + // make spit-seg info now that all atoms exist + createSplitSegContent(); // build symbol table and relocations buildLinkEdit(); @@ -2087,20 +3179,30 @@ uint64_t Writer::getAtomLoadAddress(const ObjectFile::Atom* atom) // return info->getBaseAddress() + atom->getSectionOffset(); } - template <> -const char* Writer::symbolTableName(const ObjectFile::Atom* atom) +bool Writer::stringsNeedLabelsInObjects() { - static unsigned int counter = 0; - const char* name = atom->getName(); - if ( strncmp(name, "cstring=", 8) == 0 ) - asprintf((char**)&name, "LC%u", counter++); - return name; + return true; +} + +template +bool Writer::stringsNeedLabelsInObjects() +{ + return false; } template const char* Writer::symbolTableName(const ObjectFile::Atom* atom) { + static unsigned int counter = 0; + const char* name; + if ( stringsNeedLabelsInObjects() + && (atom->getContentType() == ObjectFile::Atom::kCStringType) + && (atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition) ) + asprintf((char**)&name, "LC%u", counter++); + else + name = atom->getName(); + return name; return atom->getName(); } @@ -2138,6 +3240,8 @@ void Writer::setExportNlist(const ObjectFile::Atom* atom, macho_nlist

* ent desc |= N_ARM_THUMB_DEF; if ( atom->getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableInAndNeverStrip ) desc |= REFERENCED_DYNAMICALLY; + if ( atom->dontDeadStrip() && (fOptions.outputKind() == Options::kObjectFile) ) + desc |= N_NO_DEAD_STRIP; if ( atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) { desc |= N_WEAK_DEF; fHasWeakExports = true; @@ -2158,14 +3262,19 @@ void Writer::setImportNlist(const ObjectFile::Atom* atom, macho_nlist

* ent entry->set_n_strx(this->fStringsAtom->add(atom->getName())); // set n_type - if ( (fOptions.outputKind() == Options::kObjectFile) - && (atom->getScope() == ObjectFile::Atom::scopeLinkageUnit) - && (atom->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) ) - entry->set_n_type(N_UNDF | N_EXT | N_PEXT); - else if ( fOptions.prebind() ) - entry->set_n_type(N_PBUD | N_EXT); - else - entry->set_n_type(N_UNDF | N_EXT); + if ( fOptions.outputKind() == Options::kObjectFile ) { + if ( (atom->getScope() == ObjectFile::Atom::scopeLinkageUnit) + && (atom->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) ) + entry->set_n_type(N_UNDF | N_EXT | N_PEXT); + else + entry->set_n_type(N_UNDF | N_EXT); + } + else { + if ( fOptions.prebind() ) + entry->set_n_type(N_PBUD | N_EXT); + else + entry->set_n_type(N_UNDF | N_EXT); + } // set n_sect entry->set_n_sect(0); @@ -2201,7 +3310,7 @@ void Writer::setImportNlist(const ObjectFile::Atom* atom, macho_nlist

* ent fReferencesWeakImports = true; } // set weak_import attribute - if ( fWeakImportMap[atom] ) + if ( fWeakImportMap[atom] ) desc |= N_WEAK_REF; entry->set_n_desc(desc); @@ -2217,8 +3326,14 @@ void Writer::setLocalNlist(const ObjectFile::Atom* atom, macho_nlist

* entr const char* symbolName = this->symbolTableName(atom); char anonName[32]; if ( (fOptions.outputKind() == Options::kObjectFile) && !fOptions.keepLocalSymbol(symbolName) ) { - sprintf(anonName, "l%u", fAnonNameIndex++); - symbolName = anonName; + if ( stringsNeedLabelsInObjects() && (atom->getContentType() == ObjectFile::Atom::kCStringType) ) { + // don't use 'l' labels for x86_64 strings + // x86_64 obj-c runtime confused when static lib is stripped + } + else { + sprintf(anonName, "l%u", fAnonNameIndex++); + symbolName = anonName; + } } entry->set_n_strx(this->fStringsAtom->add(symbolName)); @@ -2241,6 +3356,8 @@ void Writer::setLocalNlist(const ObjectFile::Atom* atom, macho_nlist

* entr // set n_desc uint16_t desc = 0; + if ( atom->dontDeadStrip() && (fOptions.outputKind() == Options::kObjectFile) ) + desc |= N_NO_DEAD_STRIP; if ( atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) desc |= N_WEAK_DEF; if ( atom->isThumb() ) @@ -2379,6 +3496,27 @@ void Writer::buildSymbolTable() // set up module table if ( fModuleInfoAtom != NULL ) fModuleInfoAtom->setName(); + + // create atom to symbol index map + // imports + int i = 0; + for(std::vector::iterator it=fImportedAtoms.begin(); it != fImportedAtoms.end(); ++it) { + fAtomToSymbolIndex[*it] = i + fSymbolTableImportStartIndex; + ++i; + } + // locals + i = 0; + for(std::vector::iterator it=fLocalSymbolAtoms.begin(); it != fLocalSymbolAtoms.end(); ++it) { + fAtomToSymbolIndex[*it] = i + fSymbolTableLocalStartIndex; + ++i; + } + // exports + i = 0; + for(std::vector::iterator it=fExportedAtoms.begin(); it != fExportedAtoms.end(); ++it) { + fAtomToSymbolIndex[*it] = i + fSymbolTableExportStartIndex; + ++i; + } + } @@ -2431,8 +3569,17 @@ void Writer::collectExportedAndImportedAndLocalAtoms() break; } // else fall into - case ObjectFile::Atom::kRegularDefinition: case ObjectFile::Atom::kWeakDefinition: + if ( stringsNeedLabelsInObjects() + && (fOptions.outputKind() == Options::kObjectFile) + && (atom->getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableIn) + && (atom->getScope() == ObjectFile::Atom::scopeLinkageUnit) + && (atom->getContentType() == ObjectFile::Atom::kCStringType) ) { + fLocalSymbolAtoms.push_back(atom); + break; + } + // else fall into + case ObjectFile::Atom::kRegularDefinition: case ObjectFile::Atom::kAbsoluteSymbol: if ( this->shouldExport(*atom) ) fExportedAtoms.push_back(atom); @@ -2579,30 +3726,9 @@ void Writer::addStabs(uint32_t startIndex) template uint32_t Writer::symbolIndex(ObjectFile::Atom& atom) { - // search imports - int i = 0; - for(std::vector::iterator it=fImportedAtoms.begin(); it != fImportedAtoms.end(); ++it) { - if ( &atom == *it ) - return i + fSymbolTableImportStartIndex; - ++i; - } - - // search locals - i = 0; - for(std::vector::iterator it=fLocalSymbolAtoms.begin(); it != fLocalSymbolAtoms.end(); ++it) { - if ( &atom == *it ) - return i + fSymbolTableLocalStartIndex; - ++i; - } - - // search exports - i = 0; - for(std::vector::iterator it=fExportedAtoms.begin(); it != fExportedAtoms.end(); ++it) { - if ( &atom == *it ) - return i + fSymbolTableExportStartIndex; - ++i; - } - + std::map::iterator pos = fAtomToSymbolIndex.find(&atom); + if ( pos != fAtomToSymbolIndex.end() ) + return pos->second; throwf("atom not found in symbolIndex(%s) for %s", atom.getDisplayName(), atom.getFile()->getPath()); } @@ -2667,6 +3793,7 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Ref switch ( kind ) { case x86_64::kNoFixUp: + case x86_64::kGOTNoFixUp: case x86_64::kFollowOn: case x86_64::kGroupSubordinate: return 0; @@ -2682,6 +3809,16 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Ref fSectionRelocs.push_back(reloc1); return 1; + case x86_64::kPointer32: + reloc1.set_r_address(address); + reloc1.set_r_symbolnum(symbolIndex); + reloc1.set_r_pcrel(false); + reloc1.set_r_length(2); + reloc1.set_r_extern(external); + reloc1.set_r_type(X86_64_RELOC_UNSIGNED); + fSectionRelocs.push_back(reloc1); + return 1; + case x86_64::kPointerDiff32: case x86_64::kPointerDiff: { @@ -2790,6 +3927,15 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Ref fSectionRelocs.push_back(reloc1); return 1; + case x86_64::kPointerDiff24: + throw "internal linker error, kPointerDiff24 can't be encoded into object files"; + + case x86_64::kImageOffset32: + throw "internal linker error, kImageOffset32 can't be encoded into object files"; + + case x86_64::kSectionOffset24: + throw "internal linker error, kSectionOffset24 can't be encoded into object files"; + case x86_64::kDtraceTypeReference: case x86_64::kDtraceProbe: // generates no relocs @@ -2865,12 +4011,16 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Refere sreloc1->set_r_type(GENERIC_RELOC_SECTDIFF); sreloc1->set_r_address(address); sreloc1->set_r_value(target.getAddress()); + sreloc2->set_r_scattered(true); sreloc2->set_r_pcrel(false); sreloc2->set_r_length( (kind==x86::kPointerDiff) ? 2 : 1 ); sreloc2->set_r_type(GENERIC_RELOC_PAIR); sreloc2->set_r_address(0); - sreloc2->set_r_value(ref->getFromTarget().getAddress()+ref->getFromTargetOffset()); + if ( &ref->getFromTarget() == atom ) + sreloc2->set_r_value(ref->getFromTarget().getAddress()+ref->getFromTargetOffset()); + else + sreloc2->set_r_value(ref->getFromTarget().getAddress()); fSectionRelocs.push_back(reloc2); fSectionRelocs.push_back(reloc1); return 2; @@ -2902,6 +4052,15 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Refere fSectionRelocs.push_back(reloc1); return 1; + case x86::kPointerDiff24: + throw "internal linker error, kPointerDiff24 can't be encoded into object files"; + + case x86::kImageOffset32: + throw "internal linker error, kImageOffset32 can't be encoded into object files"; + + case x86::kSectionOffset24: + throw "internal linker error, kSectionOffset24 can't be encoded into object files"; + case x86::kDtraceTypeReference: case x86::kDtraceProbe: // generates no relocs @@ -2977,7 +4136,10 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Refere sreloc2->set_r_length(2); sreloc2->set_r_type(ARM_RELOC_PAIR); sreloc2->set_r_address(0); - sreloc2->set_r_value(ref->getFromTarget().getAddress()+ref->getFromTargetOffset()); + if ( &ref->getFromTarget() == atom ) + sreloc2->set_r_value(ref->getFromTarget().getAddress()+ref->getFromTargetOffset()); + else + sreloc2->set_r_value(ref->getFromTarget().getAddress()); fSectionRelocs.push_back(reloc2); fSectionRelocs.push_back(reloc1); return 2; @@ -3010,7 +4172,7 @@ uint32_t Writer::addObjectRelocs(ObjectFile::Atom* atom, ObjectFile::Refere case arm::kThumbBranch22WeakImport: case arm::kThumbBranch22: if ( !isExtern && (ref->getTargetOffset() != 0) ) { - // use scattered reloc is target offset is non-zero + // use scattered reloc if target offset is non-zero sreloc1->set_r_scattered(true); sreloc1->set_r_pcrel(true); sreloc1->set_r_length(2); @@ -3364,10 +4526,19 @@ uint32_t Writer::addObjectRelocs_powerpc(ObjectFile::Atom* atom, ObjectFile:: // must also change. // template -bool Writer::indirectSymbolIsLocal(const ObjectFile::Reference* ref) const +bool Writer::indirectSymbolInRelocatableIsLocal(const ObjectFile::Reference* ref) const { - // use INDIRECT_SYMBOL_LOCAL in non-lazy-pointers for atoms that won't be in symbol table or have an addend - return ( !this->shouldExport(ref->getTarget()) || (ref->getTargetOffset() != 0) ); + // cannot use INDIRECT_SYMBOL_LOCAL to tentative definitions in object files + // because tentative defs don't have addresses + if ( ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition ) + return false; + + // must use INDIRECT_SYMBOL_LOCAL if there is an addend + if ( ref->getTargetOffset() != 0 ) + return true; + + // don't use INDIRECT_SYMBOL_LOCAL for external symbols + return ! this->shouldExport(ref->getTarget()); } @@ -3393,7 +4564,7 @@ void Writer::buildObjectFileFixups() const int atomCount = sectionAtoms.size(); for (int k=0; k < atomCount; ++k) { ObjectFile::Atom* atom = sectionAtoms[k]; - //fprintf(stderr, "buildObjectFileFixups(): atom %s\n", atom->getDisplayName()); + //fprintf(stderr, "buildObjectFileFixups(): atom %s has %lu references\n", atom->getDisplayName(), atom->getReferences().size()); std::vector& refs = atom->getReferences(); const int refCount = refs.size(); for (int l=0; l < refCount; ++l) { @@ -3411,7 +4582,7 @@ void Writer::buildObjectFileFixups() } else if ( curSection->fAllNonLazyPointers) { // only use INDIRECT_SYMBOL_LOCAL in non-lazy-pointers for atoms that won't be in symbol table or have an addend - if ( this->indirectSymbolIsLocal(ref) ) + if ( this->indirectSymbolInRelocatableIsLocal(ref) ) undefinedSymbolIndex = INDIRECT_SYMBOL_LOCAL; else undefinedSymbolIndex = this->symbolIndex(ref->getTarget()); @@ -3475,6 +4646,37 @@ void Writer::buildObjectFileFixups() } + +template <> +uint64_t Writer::relocAddressInFinalLinkedImage(uint64_t address, const ObjectFile::Atom* atom) const +{ + uint64_t result; + if ( fOptions.outputKind() == Options::kKextBundle ) { + // for x86_64 kext bundles, the r_address field in relocs + // is the offset from the start address of the first segment + result = address - fSegmentInfos[0]->fBaseAddress; + if ( result > 0xFFFFFFFF ) { + throwf("kext bundle too large: address can't fit in 31-bit r_address field in %s from %s", + atom->getDisplayName(), atom->getFile()->getPath()); + } + } + else { + // for x86_64, the r_address field in relocs for final linked images + // is the offset from the start address of the first writable segment + result = address - fFirstWritableSegment->fBaseAddress; + if ( result > 0xFFFFFFFF ) { + if ( strcmp(atom->getSegment().getName(), "__TEXT") == 0 ) + throwf("text relocs not supported for x86_64 in %s from %s", + atom->getDisplayName(), atom->getFile()->getPath()); + else + throwf("image too large: address can't fit in 32-bit r_address field in %s from %s", + atom->getDisplayName(), atom->getFile()->getPath()); + } + } + return result; +} + + template <> bool Writer::illegalRelocInFinalLinkedImage(const ObjectFile::Reference& ref) { @@ -3529,6 +4731,28 @@ bool Writer::illegalRelocInFinalLinkedImage(const ObjectFile::Reference& re template <> bool Writer::illegalRelocInFinalLinkedImage(const ObjectFile::Reference& ref) { + if ( fOptions.outputKind() == Options::kKextBundle ) { + switch ( ref.getTarget().getDefinitionKind() ) { + case ObjectFile::Atom::kTentativeDefinition: + case ObjectFile::Atom::kRegularDefinition: + case ObjectFile::Atom::kWeakDefinition: + case ObjectFile::Atom::kAbsoluteSymbol: + return false; + case ObjectFile::Atom::kExternalDefinition: + case ObjectFile::Atom::kExternalWeakDefinition: + // true means we need a TEXT relocs + switch ( ref.getKind() ) { + case x86_64::kBranchPCRel32: + case x86_64::kBranchPCRel32WeakImport: + case x86_64::kPCRel32GOTLoad: + case x86_64::kPCRel32GOTLoadWeakImport: + case x86_64::kPCRel32GOT: + case x86_64::kPCRel32GOTWeakImport: + return true; + } + break; + } + } return false; } @@ -3575,6 +4799,9 @@ bool Writer::generatesLocalTextReloc(const ObjectFile::Reference& ref, cons reloc.set_r_type(GENERIC_RELOC_VANILLA); fInternalRelocs.push_back(reloc); atomSection->fHasTextLocalRelocs = true; + if ( fOptions.makeCompressedDyldInfo() ) { + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_TEXT_ABSOLUTE32, atom.getAddress() + ref.getFixUpOffset())); + } return true; } return false; @@ -3732,6 +4959,67 @@ bool Writer::generatesExternalTextReloc(const ObjectFile::Reference& ref, c return false; } +template <> +bool Writer::generatesExternalTextReloc(const ObjectFile::Reference& ref, const ObjectFile::Atom& atom, SectionInfo* atomSection) +{ + if ( fOptions.outputKind() == Options::kKextBundle ) { + macho_relocation_info

reloc; + switch ( ref.getTarget().getDefinitionKind() ) { + case ObjectFile::Atom::kTentativeDefinition: + case ObjectFile::Atom::kRegularDefinition: + case ObjectFile::Atom::kWeakDefinition: + case ObjectFile::Atom::kAbsoluteSymbol: + return false; + case ObjectFile::Atom::kExternalDefinition: + case ObjectFile::Atom::kExternalWeakDefinition: + switch ( ref.getKind() ) { + case x86_64::kBranchPCRel32: + case x86_64::kBranchPCRel32WeakImport: + // a branch to something in another linkage unit is + // encoded as an external text reloc in a kext bundle + reloc.set_r_address(this->relocAddressInFinalLinkedImage(atom.getAddress() + ref.getFixUpOffset(), &atom)); + reloc.set_r_symbolnum(this->symbolIndex(ref.getTarget())); + reloc.set_r_pcrel(true); + reloc.set_r_length(2); + reloc.set_r_extern(true); + reloc.set_r_type(X86_64_RELOC_BRANCH); + fExternalRelocs.push_back(reloc); + atomSection->fHasTextExternalRelocs = true; + return true; + case x86_64::kPCRel32GOTLoad: + case x86_64::kPCRel32GOTLoadWeakImport: + // a load of the GOT entry for a symbol in another linkage unit is + // encoded as an external text reloc in a kext bundle + reloc.set_r_address(this->relocAddressInFinalLinkedImage(atom.getAddress() + ref.getFixUpOffset(), &atom)); + reloc.set_r_symbolnum(this->symbolIndex(ref.getTarget())); + reloc.set_r_pcrel(true); + reloc.set_r_length(2); + reloc.set_r_extern(true); + reloc.set_r_type(X86_64_RELOC_GOT_LOAD); + fExternalRelocs.push_back(reloc); + atomSection->fHasTextExternalRelocs = true; + return true; + case x86_64::kPCRel32GOT: + case x86_64::kPCRel32GOTWeakImport: + // a use of the GOT entry for a symbol in another linkage unit is + // encoded as an external text reloc in a kext bundle + reloc.set_r_address(this->relocAddressInFinalLinkedImage(atom.getAddress() + ref.getFixUpOffset(), &atom)); + reloc.set_r_symbolnum(this->symbolIndex(ref.getTarget())); + reloc.set_r_pcrel(true); + reloc.set_r_length(2); + reloc.set_r_extern(true); + reloc.set_r_type(X86_64_RELOC_GOT); + fExternalRelocs.push_back(reloc); + atomSection->fHasTextExternalRelocs = true; + return true; + } + break; + } + } + return false; +} + + template bool Writer::generatesExternalTextReloc(const ObjectFile::Reference&, const ObjectFile::Atom& atom, SectionInfo* curSection) { @@ -3792,6 +5080,10 @@ uint64_t Writer::relocAddressInFinalLinkedImage(uint64_t address, const Objec // for 32-bit architectures, the r_address field in relocs // for final linked images is the offset from the first segment uint64_t result = address - fSegmentInfos[0]->fBaseAddress; + if ( fOptions.outputKind() == Options::kPreload ) { + // kPreload uses a virtual __HEADER segment to cover the load commands + result = address - fSegmentInfos[1]->fBaseAddress; + } // or the offset from the first writable segment if built split-seg if ( fOptions.splitSeg() ) result = address - fFirstWritableSegment->fBaseAddress; @@ -3802,19 +5094,6 @@ uint64_t Writer::relocAddressInFinalLinkedImage(uint64_t address, const Objec return result; } -template <> -uint64_t Writer::relocAddressInFinalLinkedImage(uint64_t address, const ObjectFile::Atom* atom) const -{ - // for x86_64, the r_address field in relocs for final linked images - // is the offset from the start address of the first writable segment - uint64_t result = address - fFirstWritableSegment->fBaseAddress; - if ( result > 0xFFFFFFFF ) { - throwf("image too large: address can't fit in 32-bit r_address field in %s from %s", - atom->getDisplayName(), atom->getFile()->getPath()); - } - return result; -} - template <> uint64_t Writer::relocAddressInFinalLinkedImage(uint64_t address, const ObjectFile::Atom* atom) const { @@ -3856,7 +5135,8 @@ template <> bool Writer::preboundLazyPointerType(uint8_t* type) { *type template void Writer::buildExecutableFixups() { - fIndirectTableAtom->fTable.reserve(50); // minimize reallocations + if ( fIndirectTableAtom != NULL ) + fIndirectTableAtom->fTable.reserve(50); // minimize reallocations std::vector& segmentInfos = fSegmentInfos; const int segCount = segmentInfos.size(); for(int i=0; i < segCount; ++i) { @@ -3869,17 +5149,31 @@ void Writer::buildExecutableFixups() std::vector& sectionAtoms = curSection->fAtoms; if ( ! curSection->fAllZeroFill ) { if ( curSection->fAllNonLazyPointers || curSection->fAllLazyPointers || curSection->fAllLazyDylibPointers - || curSection->fAllStubs || curSection->fAllSelfModifyingStubs ) - curSection->fIndirectSymbolOffset = fIndirectTableAtom->fTable.size(); + || curSection->fAllStubs || curSection->fAllSelfModifyingStubs ) { + if ( fIndirectTableAtom != NULL ) + curSection->fIndirectSymbolOffset = fIndirectTableAtom->fTable.size(); + } const int atomCount = sectionAtoms.size(); for (int k=0; k < atomCount; ++k) { ObjectFile::Atom* atom = sectionAtoms[k]; std::vector& refs = atom->getReferences(); const int refCount = refs.size(); //fprintf(stderr, "atom %s has %d references in section %s, %p\n", atom->getDisplayName(), refCount, curSection->fSectionName, atom->getSection()); + if ( curSection->fAllNonLazyPointers && (refCount == 0) ) { + // handle imageloadercache GOT slot + uint32_t offsetInSection = atom->getSectionOffset(); + uint32_t indexInSection = offsetInSection / sizeof(pint_t); + uint32_t indirectTableIndex = indexInSection + curSection->fIndirectSymbolOffset; + // use INDIRECT_SYMBOL_ABS so 10.5 dyld will leave value as zero + IndirectEntry entry = { indirectTableIndex, INDIRECT_SYMBOL_ABS }; + //fprintf(stderr,"fIndirectTableAtom->fTable.push_back(tableIndex=%d, symIndex=0x%X, section=%s)\n", + // indirectTableIndex, INDIRECT_SYMBOL_LOCAL, curSection->fSectionName); + fIndirectTableAtom->fTable.push_back(entry); + } for (int l=0; l < refCount; ++l) { ObjectFile::Reference* ref = refs[l]; - if ( curSection->fAllNonLazyPointers || curSection->fAllLazyPointers || curSection->fAllLazyDylibPointers ) { + if ( (fOptions.outputKind() != Options::kKextBundle) && + (curSection->fAllNonLazyPointers || curSection->fAllLazyPointers || curSection->fAllLazyDylibPointers) ) { // if atom is in (non)lazy_pointer section, this is encoded as an indirect symbol if ( atom->getSize() != sizeof(pint_t) ) { warning("wrong size pointer atom %s from file %s", atom->getDisplayName(), atom->getFile()->getPath()); @@ -3891,16 +5185,18 @@ void Writer::buildExecutableFixups() uint32_t offsetInSection = atom->getSectionOffset(); uint32_t indexInSection = offsetInSection / sizeof(pint_t); uint32_t undefinedSymbolIndex = INDIRECT_SYMBOL_LOCAL; - if ( this->relocationNeededInFinalLinkedImage(*pointerTarget) == kRelocExternal ) + if (atom == fFastStubGOTAtom) + undefinedSymbolIndex = INDIRECT_SYMBOL_ABS; + else if ( this->relocationNeededInFinalLinkedImage(*pointerTarget) == kRelocExternal ) undefinedSymbolIndex = this->symbolIndex(*pointerTarget); uint32_t indirectTableIndex = indexInSection + curSection->fIndirectSymbolOffset; IndirectEntry entry = { indirectTableIndex, undefinedSymbolIndex }; - //fprintf(stderr,"fIndirectTableAtom->fTable.push_back(tableIndex=%d, symIndex=0x%X), pointerTarget=%s\n", - // indirectTableIndex, undefinedSymbolIndex, pointerTarget->getDisplayName()); + //fprintf(stderr,"fIndirectTableAtom->fTable.push_back(tableIndex=%d, symIndex=0x%X, section=%s)\n", + // indirectTableIndex, undefinedSymbolIndex, curSection->fSectionName); fIndirectTableAtom->fTable.push_back(entry); if ( curSection->fAllLazyPointers || curSection->fAllLazyDylibPointers ) { uint8_t preboundLazyType; - if ( fOptions.prebind() && (fDyldHelper != NULL) + if ( fOptions.prebind() && (fDyldClassicHelperAtom != NULL) && curSection->fAllLazyPointers && preboundLazyPointerType(&preboundLazyType) ) { // this is a prebound image, need special relocs for dyld to reset lazy pointers if prebinding is invalid macho_scattered_relocation_info

pblaReloc; @@ -3909,15 +5205,15 @@ void Writer::buildExecutableFixups() pblaReloc.set_r_length(); pblaReloc.set_r_type(preboundLazyType); pblaReloc.set_r_address(relocAddressInFinalLinkedImage(atom->getAddress(), atom)); - pblaReloc.set_r_value(fDyldHelper->getAddress()); + pblaReloc.set_r_value(fDyldClassicHelperAtom->getAddress()); fInternalRelocs.push_back(*((macho_relocation_info

*)&pblaReloc)); } else if ( fSlideable ) { // this is a non-prebound dylib/bundle, need vanilla internal relocation to fix up binding handler if image slides macho_relocation_info

dyldHelperReloc; uint32_t sectionNum = 1; - if ( fDyldHelper != NULL ) - sectionNum = ((SectionInfo*)(fDyldHelper->getSection()))->getIndex(); + if ( fDyldClassicHelperAtom != NULL ) + sectionNum = ((SectionInfo*)(fDyldClassicHelperAtom->getSection()))->getIndex(); //fprintf(stderr, "lazy pointer reloc, section index=%u, section name=%s\n", sectionNum, curSection->fSectionName); dyldHelperReloc.set_r_address(relocAddressInFinalLinkedImage(atom->getAddress(), atom)); dyldHelperReloc.set_r_symbolnum(sectionNum); @@ -3926,13 +5222,82 @@ void Writer::buildExecutableFixups() dyldHelperReloc.set_r_extern(false); dyldHelperReloc.set_r_type(GENERIC_RELOC_VANILLA); fInternalRelocs.push_back(dyldHelperReloc); + if ( fOptions.makeCompressedDyldInfo() ) { + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_POINTER,atom->getAddress())); + } + } + if ( fOptions.makeCompressedDyldInfo() ) { + uint8_t type = BIND_TYPE_POINTER; + uint64_t addresss = atom->getAddress() + ref->getFixUpOffset(); + if ( pointerTarget->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition ) { + // This is a referece to a weak def in some dylib (e.g. operator new) + // need to bind into to directly bind this + // later weak binding info may override + int ordinal = compressedOrdinalForImortedAtom(pointerTarget); + fBindingInfo.push_back(BindingInfo(type, ordinal, pointerTarget->getName(), false, addresss, 0)); + } + if ( targetRequiresWeakBinding(*pointerTarget) ) { + // note: lazy pointers to weak symbols are not bound lazily + fWeakBindingInfo.push_back(BindingInfo(type, pointerTarget->getName(), false, addresss, 0)); + } + } + } + if ( curSection->fAllNonLazyPointers && fOptions.makeCompressedDyldInfo() ) { + if ( pointerTarget != NULL ) { + switch ( this->relocationNeededInFinalLinkedImage(*pointerTarget) ) { + case kRelocNone: + // no rebase or binding info needed + break; + case kRelocInternal: + // a non-lazy pointer that has been optimized to LOCAL needs rebasing info + // but not the magic fFastStubGOTAtom atom + if (atom != fFastStubGOTAtom) + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_POINTER,atom->getAddress())); + break; + case kRelocExternal: + { + uint8_t type = BIND_TYPE_POINTER; + uint64_t addresss = atom->getAddress(); + if ( targetRequiresWeakBinding(ref->getTarget()) ) { + fWeakBindingInfo.push_back(BindingInfo(type, ref->getTarget().getName(), false, addresss, 0)); + // if this is a non-lazy pointer to a weak definition within this linkage unit + // the pointer needs to initially point within linkage unit and have + // rebase command to slide it. + if ( ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) { + // unless if this is a hybrid format, in which case the non-lazy pointer + // is zero on disk. So use a bind instead of a rebase to set initial value + if ( fOptions.makeClassicDyldInfo() ) + fBindingInfo.push_back(BindingInfo(type, BIND_SPECIAL_DYLIB_SELF, ref->getTarget().getName(), false, addresss, 0)); + else + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_POINTER,atom->getAddress())); + } + // if this is a non-lazy pointer to a weak definition in a dylib, + // the pointer needs to initially bind to the dylib + else if ( ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition ) { + int ordinal = compressedOrdinalForImortedAtom(pointerTarget); + fBindingInfo.push_back(BindingInfo(BIND_TYPE_POINTER, ordinal, pointerTarget->getName(), false, addresss, 0)); + } + } + else { + int ordinal = compressedOrdinalForImortedAtom(pointerTarget); + bool weak_import = fWeakImportMap[pointerTarget]; + fBindingInfo.push_back(BindingInfo(type, ordinal, ref->getTarget().getName(), weak_import, addresss, 0)); + } + } + } } } } else if ( (ref->getKind() == A::kPointer) || (ref->getKind() == A::kPointerWeakImport) ) { if ( fSlideable && ((curSegment->fInitProtection & VM_PROT_WRITE) == 0) ) { - throwf("pointer in read-only segment not allowed in slidable image, used in %s from %s", + if ( fOptions.allowTextRelocs() ) { + if ( fOptions.warnAboutTextRelocs() ) + warning("text reloc in %s to %s", atom->getDisplayName(), ref->getTargetName()); + } + else { + throwf("pointer in read-only segment not allowed in slidable image, used in %s from %s", atom->getDisplayName(), atom->getFile()->getPath()); + } } switch ( this->relocationNeededInFinalLinkedImage(ref->getTarget()) ) { case kRelocNone: @@ -3953,6 +5318,9 @@ void Writer::buildExecutableFixups() internalReloc.set_r_extern(false); internalReloc.set_r_type(GENERIC_RELOC_VANILLA); fInternalRelocs.push_back(internalReloc); + if ( fOptions.makeCompressedDyldInfo() ) { + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_POINTER, atom->getAddress() + ref->getFixUpOffset())); + } } break; case kRelocExternal: @@ -3965,12 +5333,47 @@ void Writer::buildExecutableFixups() externalReloc.set_r_extern(true); externalReloc.set_r_type(GENERIC_RELOC_VANILLA); fExternalRelocs.push_back(externalReloc); + if ( fOptions.makeCompressedDyldInfo() ) { + int64_t addend = ref->getTargetOffset(); + uint64_t addresss = atom->getAddress() + ref->getFixUpOffset(); + if ( !fOptions.makeClassicDyldInfo() ) { + if ( ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) { + // pointers to internal weak defs need a rebase + fRebaseInfo.push_back(RebaseInfo(REBASE_TYPE_POINTER, addresss)); + } + } + uint8_t type = BIND_TYPE_POINTER; + if ( targetRequiresWeakBinding(ref->getTarget()) ) { + fWeakBindingInfo.push_back(BindingInfo(type, ref->getTarget().getName(), false, addresss, addend)); + if ( fOptions.makeClassicDyldInfo() && (ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kWeakDefinition) ) { + // hybrid linkedit puts addend in data, so we need bind phase to reset pointer to local definifion + fBindingInfo.push_back(BindingInfo(type, BIND_SPECIAL_DYLIB_SELF, ref->getTarget().getName(), false, addresss, addend)); + } + // if this is a pointer to a weak definition in a dylib, + // the pointer needs to initially bind to the dylib + else if ( ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition ) { + int ordinal = compressedOrdinalForImortedAtom(&ref->getTarget()); + fBindingInfo.push_back(BindingInfo(BIND_TYPE_POINTER, ordinal, ref->getTarget().getName(), false, addresss, addend)); + } + } + else { + int ordinal = compressedOrdinalForImortedAtom(&ref->getTarget()); + bool weak_import = fWeakImportMap[&(ref->getTarget())]; + fBindingInfo.push_back(BindingInfo(type, ordinal, ref->getTarget().getName(), weak_import, addresss, addend)); + } + } } break; } } else if ( this->illegalRelocInFinalLinkedImage(*ref) ) { - if ( fOptions.allowTextRelocs() && !atom->getSegment().isContentWritable() ) { + // new x86 stubs always require text relocs + if ( curSection->fAllStubs || curSection->fAllStubHelpers ) { + if ( this->generatesLocalTextReloc(*ref, *atom, curSection) ) { + // relocs added to fInternalRelocs + } + } + else if ( fOptions.allowTextRelocs() && !atom->getSegment().isContentWritable() ) { if ( fOptions.warnAboutTextRelocs() ) warning("text reloc in %s to %s", atom->getDisplayName(), ref->getTargetName()); if ( this->generatesLocalTextReloc(*ref, *atom, curSection) ) { @@ -4005,6 +5408,16 @@ void Writer::buildExecutableFixups() } if ( fSplitCodeToDataContentAtom != NULL ) fSplitCodeToDataContentAtom->encode(); + if ( fCompressedRebaseInfoAtom != NULL ) + fCompressedRebaseInfoAtom->encode(); + if ( fCompressedBindingInfoAtom != NULL ) + fCompressedBindingInfoAtom->encode(); + if ( fCompressedWeakBindingInfoAtom != NULL ) + fCompressedWeakBindingInfoAtom->encode(); + if ( fCompressedLazyBindingInfoAtom != NULL ) + fCompressedLazyBindingInfoAtom->encode(); + if ( fCompressedExportInfoAtom != NULL ) + fCompressedExportInfoAtom->encode(); } @@ -4067,6 +5480,7 @@ void Writer::addCrossSegmentRef(const ObjectFile::Atom* atom, const ObjectF { switch ( (x86::ReferenceKinds)ref->getKind() ) { case x86::kPointerDiff: + case x86::kImageOffset32: if ( strcmp(ref->getTarget().getSegment().getName(), "__IMPORT") == 0 ) fSplitCodeToDataContentAtom->add32bitImportLocation(atom, ref->getFixUpOffset()); else @@ -4087,8 +5501,13 @@ void Writer::addCrossSegmentRef(const ObjectFile::Atom* atom, const ObjectF } // fall into warning case default: - warning("codegen in %s (offset 0x%08llX) prevents image from loading in dyld shared cache", atom->getDisplayName(), ref->getFixUpOffset()); - fSplitCodeToDataContentAtom->setCantEncode(); + if ( fOptions.makeCompressedDyldInfo() && (ref->getKind() == x86::kAbsolute32) ) { + // will be encoded in rebase info + } + else { + warning("codegen in %s (offset 0x%08llX) prevents image from loading in dyld shared cache", atom->getDisplayName(), ref->getFixUpOffset()); + fSplitCodeToDataContentAtom->setCantEncode(); + } } } @@ -4105,6 +5524,7 @@ void Writer::addCrossSegmentRef(const ObjectFile::Atom* atom, const Obje case x86_64::kPCRel32GOT: case x86_64::kPCRel32GOTWeakImport: case x86_64::kPointerDiff32: + case x86_64::kImageOffset32: fSplitCodeToDataContentAtom->add32bitPointerLocation(atom, ref->getFixUpOffset()); break; case x86_64::kPointerDiff: @@ -4113,6 +5533,7 @@ void Writer::addCrossSegmentRef(const ObjectFile::Atom* atom, const Obje case x86_64::kNoFixUp: case x86_64::kGroupSubordinate: case x86_64::kPointer: + case x86_64::kGOTNoFixUp: // ignore break; default: @@ -4422,16 +5843,14 @@ uint64_t Writer::writeAtoms() try { for (std::vector::iterator segit = fSegmentInfos.begin(); segit != fSegmentInfos.end(); ++segit) { SegmentInfo* curSegment = *segit; - bool isTextSeg = (strcmp(curSegment->fName, "__TEXT") == 0); std::vector& sectionInfos = curSegment->fSections; for (std::vector::iterator secit = sectionInfos.begin(); secit != sectionInfos.end(); ++secit) { SectionInfo* curSection = *secit; std::vector& sectionAtoms = curSection->fAtoms; //printf("writing with max atom size 0x%X\n", fLargestAtomSize); - //fprintf(stderr, "writing %lu atoms for section %s\n", sectionAtoms.size(), curSection->fSectionName); + //fprintf(stderr, "writing %lu atoms for section %p %s at file offset 0x%08llX\n", sectionAtoms.size(), curSection, curSection->fSectionName, curSection->fFileOffset); if ( ! curSection->fAllZeroFill ) { - end = curSection->fFileOffset; - bool needsNops = isTextSeg && (strcmp(curSection->fSectionName, "__cstring") != 0); + bool needsNops = ((strcmp(curSection->fSegmentName, "__TEXT") == 0) && (strncmp(curSection->fSectionName, "__text", 6) == 0)); for (std::vector::iterator ait = sectionAtoms.begin(); ait != sectionAtoms.end(); ++ait) { ObjectFile::Atom* atom = *ait; if ( (atom->getDefinitionKind() != ObjectFile::Atom::kExternalDefinition) @@ -4439,6 +5858,7 @@ uint64_t Writer::writeAtoms() && (atom->getDefinitionKind() != ObjectFile::Atom::kAbsoluteSymbol) ) { uint32_t fileOffset = curSection->fFileOffset + atom->getSectionOffset(); if ( fileOffset != end ) { + //fprintf(stderr, "writing %d pad bytes, needsNops=%d\n", fileOffset-end, needsNops); if ( needsNops ) { // fill gaps with no-ops if ( streaming ) @@ -4494,8 +5914,8 @@ uint64_t Writer::writeAtoms() catch (const char* msg) { throwf("%s in %s from %s", msg, atom->getDisplayName(), atom->getFile()->getPath()); } - //fprintf(stderr, "writing 0x%08X -> 0x%08X (addr=0x%llX, size=0x%llX), atom %s from %s\n", - // fileOffset, end, atom->getAddress(), atom->getSize(), atom->getDisplayName(), atom->getFile()->getPath()); + //fprintf(stderr, "writing 0x%08X -> 0x%08X (addr=0x%llX, size=0x%llX), atom %p %s from %s\n", + // fileOffset, end, atom->getAddress(), atom->getSize(), atom, atom->getDisplayName(), atom->getFile()->getPath()); if ( streaming ) { // write out ::pwrite(fd, buffer, atomSize, fileOffset); @@ -4592,7 +6012,7 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob uint64_t targetAddr = 0; uint32_t firstDisp; uint32_t nextDisp; - uint32_t opcode; + uint32_t opcode = 0; bool relocateableExternal = false; bool is_bl; bool is_blx; @@ -4670,12 +6090,14 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()) ); break; case arm::kReadOnlyPointer: + if ( ref->getTarget().isThumb() && (ref->getTargetOffset() == 0)) + targetAddr |= 1; switch ( ref->getTarget().getDefinitionKind() ) { case ObjectFile::Atom::kRegularDefinition: case ObjectFile::Atom::kWeakDefinition: case ObjectFile::Atom::kTentativeDefinition: // pointer contains target address - LittleEndian::set32(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); + LittleEndian::set32(*fixUp, targetAddr); break; case ObjectFile::Atom::kExternalDefinition: case ObjectFile::Atom::kExternalWeakDefinition: @@ -4684,7 +6106,7 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob break; case ObjectFile::Atom::kAbsoluteSymbol: // pointer contains target address - LittleEndian::set32(*fixUp, ref->getTarget().getSectionOffset() + ref->getTargetOffset()); + LittleEndian::set32(*fixUp, targetAddr); break; } break; @@ -4728,8 +6150,8 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob case arm::kThumbBranch22WeakImport: case arm::kThumbBranch22: instruction = LittleEndian::get32(*fixUp); - is_bl = ((instruction & 0xF8000000) == 0xF8000000); - is_blx = ((instruction & 0xF8000000) == 0xE8000000); + is_bl = ((instruction & 0xD000F800) == 0xD000F000); + is_blx = ((instruction & 0xD000F800) == 0xC000F000); targetIsThumb = ref->getTarget().isThumb(); // The pc added will be +4 from the pc @@ -4747,16 +6169,62 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob // max positive displacement is 0x003FFFFE // max negative displacement is 0xFFC00000 if ( (displacement > 4194302LL) || (displacement < (-4194304LL)) ) { - throwf("thumb bl/blx out of range (%lld max is +/-4M) from %s in %s to %s in %s", + // armv7 supports a larger displacement + if ( fOptions.preferSubArchitecture() && fOptions.subArchitecture() == CPU_SUBTYPE_ARM_V7 ) { + if ( (displacement > 16777214) || (displacement < (-16777216LL)) ) { + throwf("thumb bl/blx out of range (%lld max is +/-16M) from %s in %s to %s in %s", + displacement, inAtom->getDisplayName(), inAtom->getFile()->getPath(), + ref->getTarget().getDisplayName(), ref->getTarget().getFile()->getPath()); + } + else { + // The instruction is really two instructions: + // The lower 16 bits are the first instruction, which contains the high + // 11 bits of the displacement. + // The upper 16 bits are the second instruction, which contains the low + // 11 bits of the displacement, as well as differentiating bl and blx. + uint32_t s = (uint32_t)(displacement >> 24) & 0x1; + uint32_t i1 = (uint32_t)(displacement >> 23) & 0x1; + uint32_t i2 = (uint32_t)(displacement >> 22) & 0x1; + uint32_t imm10 = (uint32_t)(displacement >> 12) & 0x3FF; + uint32_t imm11 = (uint32_t)(displacement >> 1) & 0x7FF; + uint32_t j1 = (i1 == s); + uint32_t j2 = (i2 == s); + if ( is_bl ) { + if ( targetIsThumb ) + opcode = 0xD000F000; // keep bl + else + opcode = 0xC000F000; // change to blx + } + else if ( is_blx ) { + if ( targetIsThumb ) + opcode = 0xD000F000; // change to bl + else + opcode = 0xC000F000; // keep blx + } + else if ( !is_bl && !is_blx && !targetIsThumb ) { + throwf("don't know how to convert instruction %x referencing %s to arm", + instruction, ref->getTarget().getDisplayName()); + } + nextDisp = (j1 << 13) | (j2 << 11) | imm11; + firstDisp = (s << 10) | imm10; + newInstruction = opcode | (nextDisp << 16) | firstDisp; + //warning("s=%d, j1=%d, j2=%d, imm10=0x%0X, imm11=0x%0X, opcode=0x%08X, first=0x%04X, next=0x%04X, new=0x%08X, disp=0x%llX for %s to %s\n", + // s, j1, j2, imm10, imm11, opcode, firstDisp, nextDisp, newInstruction, displacement, inAtom->getDisplayName(), ref->getTarget().getDisplayName()); + LittleEndian::set32(*fixUp, newInstruction); + } + } + else { + throwf("thumb bl/blx out of range (%lld max is +/-4M) from %s in %s to %s in %s", displacement, inAtom->getDisplayName(), inAtom->getFile()->getPath(), ref->getTarget().getDisplayName(), ref->getTarget().getFile()->getPath()); + } } - // The instruction is really two instructions: - // The lower 16 bits are the first instruction, which contains the first - // 11 bits of the displacement. - // The upper 16 bits are the second instruction, which contains the next - // 11 bits of the displacement, as well as differentiating bl and blx. - { + else { + // The instruction is really two instructions: + // The lower 16 bits are the first instruction, which contains the high + // 11 bits of the displacement. + // The upper 16 bits are the second instruction, which contains the low + // 11 bits of the displacement, as well as differentiating bl and blx. firstDisp = (uint32_t)(displacement >> 12) & 0x7FF; nextDisp = (uint32_t)(displacement >> 1) & 0x7FF; if ( is_bl && !targetIsThumb ) { @@ -4777,7 +6245,6 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob } break; case arm::kDtraceProbeSite: - case arm::kDtraceIsEnabledSite: if ( inAtom->isThumb() ) { // change 32-bit blx call site to two thumb NOPs LittleEndian::set32(*fixUp, 0x46C046C0); @@ -4787,6 +6254,16 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob LittleEndian::set32(*fixUp, 0xE1A00000); } break; + case arm::kDtraceIsEnabledSite: + if ( inAtom->isThumb() ) { + // change 32-bit blx call site to 'nop', 'eor r0, r0' + LittleEndian::set32(*fixUp, 0x46C04040); + } + else { + // change call site to 'eor r0, r0, r0' + LittleEndian::set32(*fixUp, 0xE0200000); + } + break; case arm::kDtraceTypeReference: case arm::kDtraceProbe: // nothing to fix up @@ -4806,7 +6283,7 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co int64_t baseAddr; uint32_t firstDisp; uint32_t nextDisp; - uint32_t opcode; + uint32_t opcode = 0; bool relocateableExternal = false; bool is_bl; bool is_blx; @@ -4830,7 +6307,7 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co { if ( ((SectionInfo*)inAtom->getSection())->fAllNonLazyPointers ) { // indirect symbol table has INDIRECT_SYMBOL_LOCAL, so we must put address in content - if ( this->indirectSymbolIsLocal(ref) ) + if ( this->indirectSymbolInRelocatableIsLocal(ref) ) LittleEndian::set32(*fixUp, targetAddr); else LittleEndian::set32(*fixUp, 0); @@ -4944,10 +6421,54 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co // the mach-o way of encoding this is that the bl instruction's target addr is the offset into the target displacement -= ref->getTarget().getAddress(); } - else { - // max positive displacement is 0x003FFFFE - // max negative displacement is 0xFFC00000 - if ( (displacement > 4194302LL) || (displacement < (-4194304LL)) ) { + + if ( (displacement > 4194302LL) || (displacement < (-4194304LL)) ) { + // armv7 supports a larger displacement + if ( fOptions.preferSubArchitecture() && fOptions.subArchitecture() == CPU_SUBTYPE_ARM_V7 ) { + if ( (displacement > 16777214) || (displacement < (-16777216LL)) ) { + throwf("thumb bl/blx out of range (%lld max is +/-16M) from %s in %s to %s in %s", + displacement, inAtom->getDisplayName(), inAtom->getFile()->getPath(), + ref->getTarget().getDisplayName(), ref->getTarget().getFile()->getPath()); + } + else { + // The instruction is really two instructions: + // The lower 16 bits are the first instruction, which contains the high + // 11 bits of the displacement. + // The upper 16 bits are the second instruction, which contains the low + // 11 bits of the displacement, as well as differentiating bl and blx. + uint32_t s = (uint32_t)(displacement >> 24) & 0x1; + uint32_t i1 = (uint32_t)(displacement >> 23) & 0x1; + uint32_t i2 = (uint32_t)(displacement >> 22) & 0x1; + uint32_t imm10 = (uint32_t)(displacement >> 12) & 0x3FF; + uint32_t imm11 = (uint32_t)(displacement >> 1) & 0x7FF; + uint32_t j1 = (i1 == s); + uint32_t j2 = (i2 == s); + if ( is_bl ) { + if ( targetIsThumb ) + opcode = 0xD000F000; // keep bl + else + opcode = 0xC000F000; // change to blx + } + else if ( is_blx ) { + if ( targetIsThumb ) + opcode = 0xD000F000; // change to bl + else + opcode = 0xC000F000; // keep blx + } + else if ( !is_bl && !is_blx && !targetIsThumb ) { + throwf("don't know how to convert instruction %x referencing %s to arm", + instruction, ref->getTarget().getDisplayName()); + } + nextDisp = (j1 << 13) | (j2 << 11) | imm11; + firstDisp = (s << 10) | imm10; + newInstruction = opcode | (nextDisp << 16) | firstDisp; + //warning("s=%d, j1=%d, j2=%d, imm10=0x%0X, imm11=0x%0X, opcode=0x%08X, first=0x%04X, next=0x%04X, new=0x%08X, disp=0x%llX for %s to %s\n", + // s, j1, j2, imm10, imm11, opcode, firstDisp, nextDisp, newInstruction, displacement, inAtom->getDisplayName(), ref->getTarget().getDisplayName()); + LittleEndian::set32(*fixUp, newInstruction); + break; + } + } + else { throwf("thumb bl/blx out of range (%lld max is +/-4M) from %s in %s to %s in %s", displacement, inAtom->getDisplayName(), inAtom->getFile()->getPath(), ref->getTarget().getDisplayName(), ref->getTarget().getFile()->getPath()); @@ -4989,9 +6510,11 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob uint32_t* fixUp = (uint32_t*)&buffer[ref->getFixUpOffset()]; uint8_t* dtraceProbeSite; const int64_t kTwoGigLimit = 0x7FFFFFFF; + const int64_t kSixteenMegLimit = 0x00FFFFFF; const int64_t kSixtyFourKiloLimit = 0x7FFF; const int64_t kOneTwentyEightLimit = 0x7F; int64_t displacement; + uint32_t temp; x86::ReferenceKinds kind = (x86::ReferenceKinds)(ref->getKind()); switch ( kind ) { case x86::kNoFixUp: @@ -5020,7 +6543,12 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob break; } } - else { + else if ( !fOptions.makeClassicDyldInfo() + && (ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kWeakDefinition) ) { + // when using only compressed dyld info, pointer is initially set to point directly to weak definition + LittleEndian::set32(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); + } + else { // external relocation ==> pointer contains addend LittleEndian::set32(*fixUp, ref->getTargetOffset()); } @@ -5042,6 +6570,24 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob throwf("16-bit pointer diff out of range in %s", inAtom->getDisplayName()); LittleEndian::set16(*((uint16_t*)fixUp), (uint16_t)displacement); break; + case x86::kPointerDiff24: + displacement = (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()); + if ( (displacement > kSixteenMegLimit) || (displacement < 0) ) + throwf("24-bit pointer diff out of range in %s", inAtom->getDisplayName()); + temp = LittleEndian::get32(*fixUp); + temp &= 0xFF000000; + temp |= (displacement & 0x00FFFFFF); + LittleEndian::set32(*fixUp, temp); + break; + case x86::kSectionOffset24: + displacement = ref->getTarget().getSectionOffset(); + if ( (displacement > kSixteenMegLimit) || (displacement < 0) ) + throwf("24-bit pointer diff out of range in %s", inAtom->getDisplayName()); + temp = LittleEndian::get32(*fixUp); + temp &= 0xFF000000; + temp |= (displacement & 0x00FFFFFF); + LittleEndian::set32(*fixUp, temp); + break; case x86::kDtraceProbeSite: // change call site to a NOP dtraceProbeSite = (uint8_t*)fixUp; @@ -5081,6 +6627,7 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob break; } if ( kind == x86::kPCRel8 ) { + displacement += 3; if ( (displacement > kOneTwentyEightLimit) || (displacement < -(kOneTwentyEightLimit)) ) { //fprintf(stderr, "call out of range from %s in %s to %s in %s\n", this->getDisplayName(), this->getFile()->getPath(), target.getDisplayName(), target.getFile()->getPath()); throwf("rel8 out of range in %s", inAtom->getDisplayName()); @@ -5088,6 +6635,7 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob *(int8_t*)fixUp = (int8_t)displacement; } else if ( kind == x86::kPCRel16 ) { + displacement += 2; if ( (displacement > kSixtyFourKiloLimit) || (displacement < -(kSixtyFourKiloLimit)) ) { //fprintf(stderr, "call out of range from %s in %s to %s in %s\n", this->getDisplayName(), this->getFile()->getPath(), target.getDisplayName(), target.getFile()->getPath()); throwf("rel16 out of range in %s", inAtom->getDisplayName()); @@ -5121,6 +6669,11 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const Ob break; } break; + case x86::kImageOffset32: + // offset of target atom from mach_header + displacement = ref->getTarget().getAddress() + ref->getTargetOffset() - fMachHeaderAtom->getAddress(); + LittleEndian::set32(*fixUp, (int32_t)displacement); + break; case x86::kDtraceTypeReference: case x86::kDtraceProbe: // nothing to fix up @@ -5150,17 +6703,17 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co case x86::kPointerWeakImport: case x86::kAbsolute32: { - if ( isExtern ) { - // external relocation ==> pointer contains addend - LittleEndian::set32(*fixUp, ref->getTargetOffset()); - } - else if ( ((SectionInfo*)inAtom->getSection())->fAllNonLazyPointers ) { + if ( ((SectionInfo*)inAtom->getSection())->fAllNonLazyPointers ) { // if INDIRECT_SYMBOL_LOCAL the content is pointer, else it is zero - if ( this->indirectSymbolIsLocal(ref) ) + if ( this->indirectSymbolInRelocatableIsLocal(ref) ) LittleEndian::set32(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); else LittleEndian::set32(*fixUp, 0); } + else if ( isExtern ) { + // external relocation ==> pointer contains addend + LittleEndian::set32(*fixUp, ref->getTargetOffset()); + } else if ( ref->getTarget().getDefinitionKind() != ObjectFile::Atom::kTentativeDefinition ) { // internal relocation => pointer contains target address LittleEndian::set32(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); @@ -5220,6 +6773,12 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co } } break; + case x86::kPointerDiff24: + throw "internal linker error, kPointerDiff24 can't be encoded into object files"; + case x86::kImageOffset32: + throw "internal linker error, kImageOffset32 can't be encoded into object files"; + case x86::kSectionOffset24: + throw "internal linker error, kSectionOffset24 can't be encoded into object files"; case x86::kDtraceProbe: case x86::kDtraceTypeReference: // nothing to fix up @@ -5230,42 +6789,105 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, co template <> void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const ObjectFile::Atom* inAtom, uint8_t buffer[]) const { - const int64_t twoGigLimit = 0x7FFFFFFF; + const int64_t twoGigLimit = 0x7FFFFFFF; + const int64_t kSixteenMegLimit = 0x00FFFFFF; uint64_t* fixUp = (uint64_t*)&buffer[ref->getFixUpOffset()]; uint8_t* dtraceProbeSite; int64_t displacement = 0; + uint32_t temp; switch ( (x86_64::ReferenceKinds)(ref->getKind()) ) { case x86_64::kNoFixUp: + case x86_64::kGOTNoFixUp: case x86_64::kFollowOn: case x86_64::kGroupSubordinate: // do nothing break; case x86_64::kPointerWeakImport: case x86_64::kPointer: + { + if ( &ref->getTarget() != NULL ) { + //fprintf(stderr, "fixUpReferenceFinal: %s reference to %s\n", this->getDisplayName(), target.getDisplayName()); + if ( this->relocationNeededInFinalLinkedImage(ref->getTarget()) == kRelocExternal) { + if ( !fOptions.makeClassicDyldInfo() + && (ref->getTarget().getDefinitionKind() == ObjectFile::Atom::kWeakDefinition) ) { + // when using only compressed dyld info, pointer is initially set to point directly to weak definition + LittleEndian::set64(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); + } + else { + // external relocation ==> pointer contains addend + LittleEndian::set64(*fixUp, ref->getTargetOffset()); + } + } + else { + // internal relocation + // pointer contains target address + //printf("Atom::fixUpReferenceFinal) target.name=%s, target.address=0x%08llX\n", target.getDisplayName(), target.getAddress()); + LittleEndian::set64(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); + } + } + } + break; + case x86_64::kPointer32: { //fprintf(stderr, "fixUpReferenceFinal: %s reference to %s\n", this->getDisplayName(), target.getDisplayName()); if ( this->relocationNeededInFinalLinkedImage(ref->getTarget()) == kRelocExternal ) { - // external relocation ==> pointer contains addend - LittleEndian::set64(*fixUp, ref->getTargetOffset()); + // external relocation + throwf("32-bit pointer to dylib or weak symbol %s not supported for x86_64",ref->getTarget().getDisplayName()); } else { // internal relocation // pointer contains target address //printf("Atom::fixUpReferenceFinal) target.name=%s, target.address=0x%08llX\n", target.getDisplayName(), target.getAddress()); - LittleEndian::set64(*fixUp, ref->getTarget().getAddress() + ref->getTargetOffset()); + displacement = ref->getTarget().getAddress() + ref->getTargetOffset(); + switch ( fOptions.outputKind() ) { + case Options::kObjectFile: + case Options::kPreload: + case Options::kDyld: + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + case Options::kKextBundle: + throwf("32-bit pointer to symbol %s not supported for x86_64",ref->getTarget().getDisplayName()); + case Options::kDynamicExecutable: + // allow x86_64 main executables to use 32-bit pointers if program loads in load 2GB + if ( (displacement > twoGigLimit) || (displacement < (-twoGigLimit)) ) + throw "32-bit pointer out of range"; + break; + case Options::kStaticExecutable: + // allow x86_64 mach_kernel to truncate pointers + break; + } + LittleEndian::set32(*((uint32_t*)fixUp), (uint32_t)displacement); } } break; case x86_64::kPointerDiff32: - displacement = (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()); - if ( (displacement > twoGigLimit) || (displacement < (-twoGigLimit)) ) - throw "32-bit pointer difference out of range"; - LittleEndian::set32(*((uint32_t*)fixUp), (uint32_t)displacement); - break; + displacement = (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()); + if ( (displacement > twoGigLimit) || (displacement < (-twoGigLimit)) ) + throw "32-bit pointer difference out of range"; + LittleEndian::set32(*((uint32_t*)fixUp), (uint32_t)displacement); + break; case x86_64::kPointerDiff: - LittleEndian::set64(*fixUp, - (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()) ); - break; + LittleEndian::set64(*fixUp, + (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()) ); + break; + case x86_64::kPointerDiff24: + displacement = (ref->getTarget().getAddress() + ref->getTargetOffset()) - (ref->getFromTarget().getAddress() + ref->getFromTargetOffset()); + if ( (displacement > kSixteenMegLimit) || (displacement < 0) ) + throwf("24-bit pointer diff out of range in %s", inAtom->getDisplayName()); + temp = LittleEndian::get32(*((uint32_t*)fixUp)); + temp &= 0xFF000000; + temp |= (displacement & 0x00FFFFFF); + LittleEndian::set32(*((uint32_t*)fixUp), temp); + break; + case x86_64::kSectionOffset24: + displacement = ref->getTarget().getSectionOffset(); + if ( (displacement > kSixteenMegLimit) || (displacement < 0) ) + throwf("24-bit pointer diff out of range in %s", inAtom->getDisplayName()); + temp = LittleEndian::get32(*((uint32_t*)fixUp)); + temp &= 0xFF000000; + temp |= (displacement & 0x00FFFFFF); + LittleEndian::set32(*((uint32_t*)fixUp), temp); + break; case x86_64::kPCRel32GOTLoad: case x86_64::kPCRel32GOTLoadWeakImport: // if GOT entry was optimized away, change movq instruction to a leaq @@ -5297,7 +6919,10 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const break; case ObjectFile::Atom::kExternalDefinition: case ObjectFile::Atom::kExternalWeakDefinition: - throw "codegen problem, can't use rel32 to external symbol"; + if ( fOptions.outputKind() == Options::kKextBundle ) + displacement = 0; + else + throwf("codegen problem, can't use rel32 to external symbol %s", ref->getTarget().getDisplayName()); break; } switch ( ref->getKind() ) { @@ -5331,6 +6956,11 @@ void Writer::fixUpReferenceFinal(const ObjectFile::Reference* ref, const LittleEndian::set32(*((uint32_t*)fixUp), (int32_t)displacement); } break; + case x86_64::kImageOffset32: + // offset of target atom from mach_header + displacement = ref->getTarget().getAddress() + ref->getTargetOffset() - fMachHeaderAtom->getAddress(); + LittleEndian::set32(*((uint32_t*)fixUp), (int32_t)displacement); + break; case x86_64::kDtraceProbeSite: // change call site to a NOP dtraceProbeSite = (uint8_t*)fixUp; @@ -5366,6 +6996,7 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, int32_t temp32; switch ( (x86_64::ReferenceKinds)(ref->getKind()) ) { case x86_64::kNoFixUp: + case x86_64::kGOTNoFixUp: case x86_64::kFollowOn: case x86_64::kGroupSubordinate: // do nothing @@ -5383,13 +7014,33 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, } } break; + case x86_64::kPointer32: + { + if ( external ) { + // external relocation ==> pointer contains addend + LittleEndian::set32(*((uint32_t*)fixUp), ref->getTargetOffset()); + } + else { + // internal relocation ==> pointer contains target address + LittleEndian::set32(*((uint32_t*)fixUp), ref->getTarget().getAddress() + ref->getTargetOffset()); + } + } + break; case x86_64::kPointerDiff32: - // addend in content - LittleEndian::set32(*((uint32_t*)fixUp), ref->getTargetOffset() - ref->getFromTargetOffset() ); + displacement = ref->getTargetOffset() - ref->getFromTargetOffset(); + if ( ref->getTarget().getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn ) + displacement += ref->getTarget().getAddress(); + if ( ref->getFromTarget().getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn ) + displacement -= ref->getFromTarget().getAddress(); + LittleEndian::set32(*((uint32_t*)fixUp), displacement); break; case x86_64::kPointerDiff: - // addend in content - LittleEndian::set64(*fixUp, ref->getTargetOffset() - ref->getFromTargetOffset() ); + displacement = ref->getTargetOffset() - ref->getFromTargetOffset(); + if ( ref->getTarget().getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn ) + displacement += ref->getTarget().getAddress(); + if ( ref->getFromTarget().getSymbolTableInclusion() == ObjectFile::Atom::kSymbolTableNotIn ) + displacement -= ref->getFromTarget().getAddress(); + LittleEndian::set64(*fixUp, displacement); break; case x86_64::kBranchPCRel32: case x86_64::kBranchPCRel32WeakImport: @@ -5450,6 +7101,12 @@ void Writer::fixUpReferenceRelocatable(const ObjectFile::Reference* ref, // contains addend (usually zero) LittleEndian::set32(*((uint32_t*)fixUp), (uint32_t)(ref->getTargetOffset())); break; + case x86_64::kPointerDiff24: + throw "internal linker error, kPointerDiff24 can't be encoded into object files"; + case x86_64::kImageOffset32: + throw "internal linker error, kImageOffset32 can't be encoded into object files"; + case x86_64::kSectionOffset24: + throw "internal linker error, kSectionOffset24 can't be encoded into object files"; case x86_64::kDtraceTypeReference: case x86_64::kDtraceProbe: // nothing to fix up @@ -5536,7 +7193,7 @@ void Writer::fixUpReference_powerpc(const ObjectFile::Reference* ref, const O } else if ( !finalLinkedImage && ((SectionInfo*)inAtom->getSection())->fAllNonLazyPointers ) { // if INDIRECT_SYMBOL_LOCAL the content is pointer, else it is zero - if ( this->indirectSymbolIsLocal(ref) ) + if ( this->indirectSymbolInRelocatableIsLocal(ref) ) P::setP(*fixUpPointer, targetAddr); else P::setP(*fixUpPointer, 0); @@ -5966,6 +7623,7 @@ bool Writer::GOTReferenceKind(uint8_t kind) case x86_64::kPCRel32GOTWeakImport: case x86_64::kPCRel32GOTLoad: case x86_64::kPCRel32GOTLoadWeakImport: + case x86_64::kGOTNoFixUp: return true; } return false; @@ -6035,7 +7693,7 @@ void Writer::optimizeDylibReferences() // already noticed that this reader has same install name as another reader readerAliases[reader] = aliasPos->second; } - else if ( !reader->providedExportAtom() && (reader->implicitlyLinked() || fOptions.deadStripDylibs()) ) { + else if ( !reader->providedExportAtom() && (reader->implicitlyLinked() || reader->deadStrippable() || fOptions.deadStripDylibs()) ) { // this reader can be optimized away it->second = 0xFFFFFFFF; typename std::map* >::iterator pos = fLibraryToLoadCommand.find(reader); @@ -6158,7 +7816,7 @@ void Writer::scanForAbsoluteReferences() case ppc64::kAbsHigh16AddLow: //fprintf(stderr, "found -mdynamic-no-pic codegen in %s in %s\n", atom->getDisplayName(), atom->getFile()->getPath()); // shrink page-zero and add pad segment to compensate - fPadSegmentInfo = new SegmentInfo(); + fPadSegmentInfo = new SegmentInfo(4096); strcpy(fPadSegmentInfo->fName, "__4GBFILL"); fPageZeroAtom->setSize(0x1000); return; @@ -6168,7 +7826,7 @@ void Writer::scanForAbsoluteReferences() } } - + template void Writer::insertDummyStubs() { @@ -6196,13 +7854,94 @@ void Writer::insertDummyStubs() fAllSynthesizedStubs.insert(fAllSynthesizedStubs.begin(), betterStubs.begin(), betterStubs.end()); } + +template +void Writer::synthesizeKextGOT() +{ + // walk every atom and reference + for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { + ObjectFile::Atom* atom = *it; + std::vector& references = atom->getReferences(); + for (std::vector::iterator rit=references.begin(); rit != references.end(); rit++) { + ObjectFile::Reference* ref = *rit; + switch ( ref->getTargetBinding()) { + case ObjectFile::Reference::kUnboundByName: + case ObjectFile::Reference::kDontBind: + break; + case ObjectFile::Reference::kBoundByName: + case ObjectFile::Reference::kBoundDirectly: + ObjectFile::Atom& target = ref->getTarget(); + // create GOT slots (non-lazy pointers) as needed + if ( this->GOTReferenceKind(ref->getKind()) ) { + bool useGOT = ( this->relocationNeededInFinalLinkedImage(ref->getTarget()) == kRelocExternal ); + // if this GOT usage cannot be optimized away then make a GOT enry + if ( ! this->optimizableGOTReferenceKind(ref->getKind()) ) + useGOT = true; + if ( useGOT ) { + ObjectFile::Atom* nlp = NULL; + std::map::iterator pos = fGOTMap.find(&target); + if ( pos == fGOTMap.end() ) { + nlp = new NonLazyPointerAtom(*this, target); + fGOTMap[&target] = nlp; + } + else { + nlp = pos->second; + } + // alter reference to use non lazy pointer instead + ref->setTarget(*nlp, ref->getTargetOffset()); + } + } + // build map of which symbols need weak importing + if ( (target.getDefinitionKind() == ObjectFile::Atom::kExternalDefinition) + || (target.getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition) ) { + if ( this->weakImportReferenceKind(ref->getKind()) ) { + fWeakImportMap[&target] = true; + } + } + break; + } + } + } + + // add non-lazy pointers to fAllAtoms + if ( fAllSynthesizedNonLazyPointers.size() != 0 ) { + ObjectFile::Section* curSection = NULL; + ObjectFile::Atom* prevAtom = NULL; + bool inserted = false; + for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { + ObjectFile::Atom* atom = *it; + ObjectFile::Section* nextSection = atom->getSection(); + if ( nextSection != curSection ) { + if ( (prevAtom != NULL) && (strcmp(prevAtom->getSectionName(), "__data") == 0) ) { + // found end of __data section, insert lazy pointers here + fAllAtoms->insert(it, fAllSynthesizedNonLazyPointers.begin(), fAllSynthesizedNonLazyPointers.end()); + inserted = true; + break; + } + curSection = nextSection; + } + prevAtom = atom; + } + if ( !inserted ) { + throw "can't insert non-lazy pointers, __data section not found"; + } + } + +} + + template void Writer::synthesizeStubs() { switch ( fOptions.outputKind() ) { case Options::kObjectFile: + case Options::kPreload: // these output kinds never have stubs return; + case Options::kKextBundle: + // new kext need a synthesized GOT only + synthesizeKextGOT(); + return; case Options::kStaticExecutable: case Options::kDyld: case Options::kDynamicLibrary: @@ -6240,6 +7979,12 @@ void Writer::synthesizeStubs() weakImport = true; } } + // -weak_library no longer forces uses to be weak_import + if ( fForcedWeakImportReaders.count(target.getFile()) != 0 ) { + fWeakImportMap[&target] = true; + weakImport = true; + } + std::map::iterator pos = fWeakImportMap.find(&target); if ( pos == fWeakImportMap.end() ) { // target not in fWeakImportMap, so add @@ -6287,6 +8032,12 @@ void Writer::synthesizeStubs() forLazyDylib = true; break; } + // just-in-time, create GOT slot to dyld_stub_binder + if ( fOptions.makeCompressedDyldInfo() && (fFastStubGOTAtom == NULL) ) { + if ( fDyldCompressedHelperAtom == NULL ) + throw "missing symbol dyld_stub_binder"; + fFastStubGOTAtom = new NonLazyPointerAtom(*this, *fDyldCompressedHelperAtom); + } stub = new StubAtom(*this, target, forLazyDylib); fStubsMap[&target] = stub; } @@ -6318,7 +8069,7 @@ void Writer::synthesizeStubs() // if this GOT usage cannot be optimized away then make a GOT enry if ( ! this->optimizableGOTReferenceKind(ref->getKind()) ) useGOT = true; - if ( useGOT ) { + if ( useGOT ) { ObjectFile::Atom* nlp = NULL; std::map::iterator pos = fGOTMap.find(&target); if ( pos == fGOTMap.end() ) { @@ -6338,9 +8089,10 @@ void Writer::synthesizeStubs() // sort stubs std::sort(fAllSynthesizedStubs.begin(), fAllSynthesizedStubs.end(), AtomByNameSorter()); + std::sort(fAllSynthesizedStubHelpers.begin(), fAllSynthesizedStubHelpers.end(), AtomByNameSorter()); - // add dummy fast stubs (x86 only) - if ( !fOptions.slowx86Stubs() ) + // add dummy self-modifying stubs (x86 only) + if ( ! fOptions.makeCompressedDyldInfo() ) this->insertDummyStubs(); // sort lazy pointers @@ -6399,18 +8151,19 @@ void Writer::synthesizeStubs() } - // add lazy dylib pointers to fAllAtoms - if ( fAllSynthesizedLazyDylibPointers.size() != 0 ) { + // add non-lazy pointers to fAllAtoms + if ( fAllSynthesizedNonLazyPointers.size() != 0 ) { ObjectFile::Section* curSection = NULL; ObjectFile::Atom* prevAtom = NULL; bool inserted = false; + // first try to insert at end of __nl_symbol_ptr for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { ObjectFile::Atom* atom = *it; ObjectFile::Section* nextSection = atom->getSection(); if ( nextSection != curSection ) { - if ( (prevAtom != NULL) && (strcmp(prevAtom->getSectionName(), "__dyld") == 0) ) { - // found end of __dyld section, insert lazy pointers here - fAllAtoms->insert(it, fAllSynthesizedLazyDylibPointers.begin(), fAllSynthesizedLazyDylibPointers.end()); + if ( (prevAtom != NULL) && (strcmp(prevAtom->getSectionName(), "__nl_symbol_ptr") == 0) ) { + // found end of __nl_symbol_ptr section, insert non-lazy pointers at end of it + fAllAtoms->insert(it, fAllSynthesizedNonLazyPointers.begin(), fAllSynthesizedNonLazyPointers.end()); inserted = true; break; } @@ -6419,12 +8172,49 @@ void Writer::synthesizeStubs() prevAtom = atom; } if ( !inserted ) { - throw "can't insert lazy pointers, __dyld section not found"; + // next try to insert after __dyld section + for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { + ObjectFile::Atom* atom = *it; + ObjectFile::Section* nextSection = atom->getSection(); + if ( nextSection != curSection ) { + if ( strcmp(atom->getSegment().getName(), "__DATA") == 0 ) { + const char* prevSectionName = (prevAtom != NULL) ? prevAtom->getSectionName() : ""; + if ( (strcmp(prevSectionName, "__dyld") != 0) + && (strcmp(prevSectionName, "__program_vars") != 0) + && (strcmp(prevSectionName, "__mod_init_func") != 0) ) { + // found end of __dyld section, insert non-lazy pointers here + fAllAtoms->insert(it, fAllSynthesizedNonLazyPointers.begin(), fAllSynthesizedNonLazyPointers.end()); + inserted = true; + break; + } + } + } + prevAtom = atom; + } + if ( !inserted ) { + // might not be any __DATA sections, insert after end of __TEXT + for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { + ObjectFile::Atom* atom = *it; + ObjectFile::Section* nextSection = atom->getSection(); + if ( nextSection != curSection ) { + if ( (prevAtom != NULL) && (strcmp(prevAtom->getSegment().getName(), "__TEXT") == 0) && (strcmp(atom->getSegment().getName(), "__TEXT") != 0)) { + // found end of __TEXT segment, insert non-lazy pointers at end of it + fAllAtoms->insert(it, fAllSynthesizedNonLazyPointers.begin(), fAllSynthesizedNonLazyPointers.end()); + inserted = true; + break; + } + curSection = nextSection; + } + prevAtom = atom; + } + } + if ( !inserted ) + throw "can't insert non-lazy pointers, __dyld section not found"; } } - // add lazy pointers to fAllAtoms - if ( fAllSynthesizedLazyPointers.size() != 0 ) { + // add lazy dylib pointers to fAllAtoms + if ( fAllSynthesizedLazyDylibPointers.size() != 0 ) { ObjectFile::Section* curSection = NULL; ObjectFile::Atom* prevAtom = NULL; bool inserted = false; @@ -6432,9 +8222,12 @@ void Writer::synthesizeStubs() ObjectFile::Atom* atom = *it; ObjectFile::Section* nextSection = atom->getSection(); if ( nextSection != curSection ) { - if ( (prevAtom != NULL) && (strcmp(prevAtom->getSectionName(), "__dyld") == 0) ) { + if ( (prevAtom != NULL) && + ( (strcmp(prevAtom->getSectionName(), "__dyld") == 0) + || (strcmp(prevAtom->getSectionName(), "__program_vars") == 0) + || (strcmp(prevAtom->getSectionName(), "__nl_symbol_ptr") == 0) ) ) { // found end of __dyld section, insert lazy pointers here - fAllAtoms->insert(it, fAllSynthesizedLazyPointers.begin(), fAllSynthesizedLazyPointers.end()); + fAllAtoms->insert(it, fAllSynthesizedLazyDylibPointers.begin(), fAllSynthesizedLazyDylibPointers.end()); inserted = true; break; } @@ -6446,9 +8239,9 @@ void Writer::synthesizeStubs() throw "can't insert lazy pointers, __dyld section not found"; } } - - // add non-lazy pointers to fAllAtoms - if ( fAllSynthesizedNonLazyPointers.size() != 0 ) { + + // add lazy pointers to fAllAtoms + if ( fAllSynthesizedLazyPointers.size() != 0 ) { ObjectFile::Section* curSection = NULL; ObjectFile::Atom* prevAtom = NULL; bool inserted = false; @@ -6456,12 +8249,12 @@ void Writer::synthesizeStubs() ObjectFile::Atom* atom = *it; ObjectFile::Section* nextSection = atom->getSection(); if ( nextSection != curSection ) { - if ( (prevAtom != NULL) - && ((strcmp(prevAtom->getSectionName(), "__dyld") == 0) - || ((strcmp(prevAtom->getSectionName(), "__data") == 0) && - ((fOptions.outputKind() == Options::kDyld) || (fOptions.outputKind() == Options::kStaticExecutable))) ) ) { + if ( (prevAtom != NULL) && + ( (strcmp(prevAtom->getSectionName(), "__dyld") == 0) + || (strcmp(prevAtom->getSectionName(), "__program_vars") == 0) + || (strcmp(prevAtom->getSectionName(), "__nl_symbol_ptr") == 0) ) ) { // found end of __dyld section, insert lazy pointers here - fAllAtoms->insert(it, fAllSynthesizedNonLazyPointers.begin(), fAllSynthesizedNonLazyPointers.end()); + fAllAtoms->insert(it, fAllSynthesizedLazyPointers.begin(), fAllSynthesizedLazyPointers.end()); inserted = true; break; } @@ -6470,11 +8263,17 @@ void Writer::synthesizeStubs() prevAtom = atom; } if ( !inserted ) { - throw "can't insert non-lazy pointers, __dyld section not found"; + throw "can't insert lazy pointers, __dyld section not found"; } } - // build LC_SEGMENT_SPLIT_INFO content now that all atoms exist + +} + +template +void Writer::createSplitSegContent() +{ + // build LC_SEGMENT_SPLIT_INFO once all atoms exist if ( fSplitCodeToDataContentAtom != NULL ) { for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { ObjectFile::Atom* atom = *it; @@ -6494,11 +8293,37 @@ void Writer::synthesizeStubs() } } } + // bad codegen may cause LC_SEGMENT_SPLIT_INFO to be removed + adjustLoadCommandsAndPadding(); } } +template +void Writer::synthesizeUnwindInfoTable() +{ + if ( fUnwindInfoAtom != NULL ) { + // walk every atom and gets its unwind info + for (std::vector::iterator it=fAllAtoms->begin(); it != fAllAtoms->end(); it++) { + ObjectFile::Atom* atom = *it; + if ( atom->beginUnwind() == atom->endUnwind() ) { + // be sure to mark that we have no unwind info for stuff in the TEXT segment without unwind info + if ( strcmp(atom->getSegment().getName(), "__TEXT") == 0 ) + fUnwindInfoAtom->addUnwindInfo(atom, 0, 0, NULL, NULL, NULL); + } + else { + // atom has unwind + for ( ObjectFile::UnwindInfo::iterator uit = atom->beginUnwind(); uit != atom->endUnwind(); ++uit ) { + fUnwindInfoAtom->addUnwindInfo(atom, uit->startOffset, uit->unwindInfo, atom->getFDE(), atom->getLSDA(), atom->getPersonalityPointer()); + } + } + } + } +} + + + template void Writer::partitionIntoSections() { @@ -6506,7 +8331,7 @@ void Writer::partitionIntoSections() // for every atom, set its sectionInfo object and section offset // build up fSegmentInfos along the way - ObjectFile::Section* curSection = NULL; + ObjectFile::Section* curSection = (ObjectFile::Section*)(-1); SectionInfo* currentSectionInfo = NULL; SegmentInfo* currentSegmentInfo = NULL; SectionInfo* cstringSectionInfo = NULL; @@ -6514,10 +8339,13 @@ void Writer::partitionIntoSections() fSegmentInfos.reserve(8); for (unsigned int i=0; i < fAllAtoms->size(); ++i) { ObjectFile::Atom* atom = (*fAllAtoms)[i]; - if ( (atom->getSection() != curSection) || ((curSection==NULL) && (strcmp(atom->getSectionName(),currentSectionInfo->fSectionName) != 0)) ) { + if ( ((atom->getSection() != curSection) || (curSection==NULL)) + && ((currentSectionInfo == NULL) + || (strcmp(atom->getSectionName(),currentSectionInfo->fSectionName) != 0) + || (strcmp(atom->getSegment().getName(),currentSectionInfo->fSegmentName) != 0)) ) { if ( oneSegmentCommand ) { if ( currentSegmentInfo == NULL ) { - currentSegmentInfo = new SegmentInfo(); + currentSegmentInfo = new SegmentInfo(fOptions.segmentAlignment()); currentSegmentInfo->fInitProtection = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE; currentSegmentInfo->fMaxProtection = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE; this->fSegmentInfos.push_back(currentSegmentInfo); @@ -6536,7 +8364,7 @@ void Writer::partitionIntoSections() } else { if ( (currentSegmentInfo == NULL) || (strcmp(currentSegmentInfo->fName, atom->getSegment().getName()) != 0) ) { - currentSegmentInfo = new SegmentInfo(); + currentSegmentInfo = new SegmentInfo(fOptions.segmentAlignment()); strcpy(currentSegmentInfo->fName, atom->getSegment().getName()); uint32_t initprot = 0; if ( atom->getSegment().isContentReadable() ) @@ -6565,6 +8393,10 @@ void Writer::partitionIntoSections() currentSegmentInfo->fFixedAddress = atom->getSegment().hasFixedAddress(); if ( currentSegmentInfo->fFixedAddress && (&(atom->getSegment()) == &Segment::fgStackSegment) ) currentSegmentInfo->fIndependentAddress = true; + if ( (fOptions.outputKind() == Options::kPreload) && (strcmp(currentSegmentInfo->fName, "__LINKEDIT")==0) ) + currentSegmentInfo->fHasLoadCommand = false; + if ( strcmp(currentSegmentInfo->fName, "__HEADER")==0 ) + currentSegmentInfo->fHasLoadCommand = false; this->fSegmentInfos.push_back(currentSegmentInfo); } currentSectionInfo = new SectionInfo(); @@ -6584,7 +8416,8 @@ void Writer::partitionIntoSections() currentSectionInfo->setIndex(sectionIndex++); currentSegmentInfo->fSections.push_back(currentSectionInfo); } - if ( (strcmp(currentSectionInfo->fSegmentName, "__TEXT") == 0) && (strcmp(currentSectionInfo->fSectionName, "._load_commands") == 0) ) { + //fprintf(stderr, "new section %s for atom %s\n", atom->getSectionName(), atom->getDisplayName()); + if ( strcmp(currentSectionInfo->fSectionName, "._load_commands") == 0 ) { fLoadCommandsSection = currentSectionInfo; fLoadCommandsSegment = currentSegmentInfo; } @@ -6616,13 +8449,15 @@ void Writer::partitionIntoSections() currentSectionInfo->fAllSelfModifyingStubs = true; currentSectionInfo->fAlignment = 6; // force x86 fast stubs to start on 64-byte boundary } + if ( (strcmp(currentSectionInfo->fSegmentName, "__TEXT") == 0) && (strcmp(currentSectionInfo->fSectionName, "__stub_helper") == 0) ) + currentSectionInfo->fAllStubHelpers = true; if ( (strcmp(currentSectionInfo->fSegmentName, "__TEXT") == 0) && (strcmp(currentSectionInfo->fSectionName, "__eh_frame") == 0) ) currentSectionInfo->fAlignment = __builtin_ctz(sizeof(pint_t)); // always start CFI info pointer aligned curSection = atom->getSection(); if ( currentSectionInfo->fAllNonLazyPointers || currentSectionInfo->fAllLazyPointers || currentSectionInfo->fAllLazyDylibPointers || currentSectionInfo->fAllStubs || currentSectionInfo->fAllSelfModifyingStubs ) { fSymbolTableCommands->needDynamicTable(); - } + } } // any non-zero fill atoms make whole section marked not-zero-fill if ( currentSectionInfo->fAllZeroFill && ! atom->isZeroFill() ) @@ -6649,6 +8484,8 @@ void Writer::partitionIntoSections() currentSectionInfo->fSize = offset + curAtomSize; // add atom to section vector currentSectionInfo->fAtoms.push_back(atom); + //fprintf(stderr, " adding atom %p %s size=0x%0llX to section %p %s from %s\n", atom, atom->getDisplayName(), atom->getSize(), + // currentSectionInfo, currentSectionInfo->fSectionName, atom->getFile()->getPath()); // update largest size if ( !currentSectionInfo->fAllZeroFill && (curAtomSize > fLargestAtomSize) ) fLargestAtomSize = curAtomSize; @@ -6745,7 +8582,7 @@ bool Writer::isBranch24Reference(uint8_t kind) // Branch Island Algorithm // // If the __TEXT segment < 16MB, then no branch islands needed -// Otherwise, every 15MB into the __TEXT segment is region is +// Otherwise, every 14MB into the __TEXT segment a region is // added which can contain branch islands. Every out of range // bl instruction is checked. If it crosses a region, an island // is added to that region with the same target and the bl is @@ -6766,7 +8603,7 @@ bool Writer::addPPCBranchIslands() // Can only possibly need branch islands if __TEXT segment > 16M if ( fLoadCommandsSegment->fSize > 16000000 ) { if ( log) fprintf(stderr, "ld: checking for branch islands, __TEXT segment size=%llu\n", fLoadCommandsSegment->fSize); - const uint32_t kBetweenRegions = 15*1024*1024; // place regions of islands every 15MB in __text section + const uint32_t kBetweenRegions = 14*1024*1024; // place regions of islands every 14MB in __text section SectionInfo* textSection = NULL; for (std::vector::iterator it=fLoadCommandsSegment->fSections.begin(); it != fLoadCommandsSegment->fSections.end(); it++) { if ( strcmp((*it)->fSectionName, "__text") == 0 ) { @@ -6867,7 +8704,7 @@ bool Writer::addPPCBranchIslands() uint64_t sectionOffset = 0; for (std::vector::iterator it=textSection->fAtoms.begin(); it != textSection->fAtoms.end(); it++) { ObjectFile::Atom* atom = *it; - if ( atom->getAddress() > islandRegionAddr ) { + if ( (atom->getAddress()+atom->getSize()) > islandRegionAddr ) { uint64_t islandStartOffset = atom->getSectionOffset() + atomSlide; sectionOffset = islandStartOffset; std::vector* regionIslands = ®ionsIslands[regionIndex]; @@ -6935,39 +8772,44 @@ void Writer::adjustLoadCommandsAndPadding() std::vector& sectionInfos = fLoadCommandsSegment->fSections; const int sectionCount = sectionInfos.size(); - uint32_t totalSizeOfHeaderAndLoadCommands = 0; + uint32_t totalSizeOfTEXTLessHeaderAndLoadCommands = 0; for(int j=0; j < sectionCount; ++j) { SectionInfo* curSection = sectionInfos[j]; - totalSizeOfHeaderAndLoadCommands += curSection->fSize; if ( strcmp(curSection->fSectionName, fHeaderPadding->getSectionName()) == 0 ) break; + totalSizeOfTEXTLessHeaderAndLoadCommands += curSection->fSize; } uint64_t paddingSize = 0; if ( fOptions.outputKind() == Options::kDyld ) { // dyld itself has special padding requirements. We want the beginning __text section to start at a stable address - paddingSize = 4096 - (totalSizeOfHeaderAndLoadCommands % 4096); + paddingSize = 4096 - (totalSizeOfTEXTLessHeaderAndLoadCommands % 4096); } else if ( fOptions.outputKind() == Options::kObjectFile ) { // mach-o .o files need no padding between load commands and first section + // but leave enough room that the object file could be signed + paddingSize = 32; + } + else if ( fOptions.outputKind() == Options::kPreload ) { + // mach-o MH_PRELOAD files need no padding between load commands and first section paddingSize = 0; } else if ( fOptions.makeEncryptable() ) { // want load commands to end on a page boundary, so __text starts on page boundary - paddingSize = 4096 - ((totalSizeOfHeaderAndLoadCommands+fOptions.minimumHeaderPad()) % 4096) + fOptions.minimumHeaderPad(); - fEncryptionLoadCommand->setStartEncryptionOffset(totalSizeOfHeaderAndLoadCommands+paddingSize); + paddingSize = 4096 - ((totalSizeOfTEXTLessHeaderAndLoadCommands+fOptions.minimumHeaderPad()) % 4096) + fOptions.minimumHeaderPad(); + fEncryptionLoadCommand->setStartEncryptionOffset(totalSizeOfTEXTLessHeaderAndLoadCommands+paddingSize); } else { // work backwards from end of segment and lay out sections so that extra room goes to padding atom uint64_t addr = 0; for(int j=sectionCount-1; j >=0; --j) { SectionInfo* curSection = sectionInfos[j]; - addr -= curSection->fSize; - addr = addr & (0 - (1 << curSection->fAlignment)); if ( strcmp(curSection->fSectionName, fHeaderPadding->getSectionName()) == 0 ) { - addr -= totalSizeOfHeaderAndLoadCommands; - paddingSize = addr % 4096; + addr -= (fLoadCommandsSection->fSize+fMachHeaderAtom->getSize()); + paddingSize = addr % fOptions.segmentAlignment(); break; } + addr -= curSection->fSize; + addr = addr & (0 - (1 << curSection->fAlignment)); } // if command line requires more padding than this @@ -6981,8 +8823,8 @@ void Writer::adjustLoadCommandsAndPadding() minPad = altMin; } if ( paddingSize < minPad ) { - int extraPages = (minPad - paddingSize + 4095)/4096; - paddingSize += extraPages * 4096; + int extraPages = (minPad - paddingSize + fOptions.segmentAlignment() - 1)/fOptions.segmentAlignment(); + paddingSize += extraPages * fOptions.segmentAlignment(); } } @@ -6995,11 +8837,17 @@ void Writer::adjustLoadCommandsAndPadding() } } +static uint64_t segmentAlign(uint64_t addr, uint64_t alignment) +{ + return ((addr+alignment-1) & (-alignment)); +} + // assign file offsets and logical address to all segments template void Writer::assignFileOffsets() { - bool finalLinkedImage = (fOptions.outputKind() != Options::kObjectFile); + const bool virtualSectionOccupyAddressSpace = ((fOptions.outputKind() != Options::kObjectFile) + && (fOptions.outputKind() != Options::kPreload)); bool haveFixedSegments = false; uint64_t fileOffset = 0; uint64_t nextContiguousAddress = fOptions.baseAddress(); @@ -7018,6 +8866,17 @@ void Writer::assignFileOffsets() } } + // process segments with fixed addresses (-seg_page_size) + for (std::vector::iterator it = fOptions.customSegmentSizes().begin(); it != fOptions.customSegmentSizes().end(); ++it) { + for (std::vector::iterator segit = fSegmentInfos.begin(); segit != fSegmentInfos.end(); ++segit) { + SegmentInfo* curSegment = *segit; + if ( strcmp(curSegment->fName, it->name) == 0 ) { + curSegment->fPageSize = it->size; + break; + } + } + } + // Run through the segments and each segment's sections to assign addresses for (std::vector::iterator segit = fSegmentInfos.begin(); segit != fSegmentInfos.end(); ++segit) { SegmentInfo* curSegment = *segit; @@ -7029,14 +8888,21 @@ void Writer::assignFileOffsets() nextContiguousAddress = nextReadOnlyAddress; } - fileOffset = (fileOffset+4095) & (-4096); + if ( fOptions.outputKind() == Options::kPreload ) { + if ( strcmp(curSegment->fName, "__HEADER") == 0 ) + nextContiguousAddress = 0; + else if ( strcmp(curSegment->fName, "__TEXT") == 0 ) + nextContiguousAddress = fOptions.baseAddress(); + } + + fileOffset = segmentAlign(fileOffset, curSegment->fPageSize); curSegment->fFileOffset = fileOffset; // Set the segment base address if ( curSegment->fFixedAddress ) haveFixedSegments = true; else - curSegment->fBaseAddress = nextContiguousAddress; + curSegment->fBaseAddress = segmentAlign(nextContiguousAddress, curSegment->fPageSize); // We've set the segment address, now run through each section. uint64_t address = curSegment->fBaseAddress; @@ -7050,11 +8916,25 @@ void Writer::assignFileOffsets() // adjust section address based on alignment uint64_t alignment = 1 << curSection->fAlignment; - address = ( (address+alignment-1) & (-alignment) ); + if ( curSection->fAtoms.size() == 1 ) { + // if there is only one atom in section, use modulus for even better layout + ObjectFile::Alignment atomAlign = curSection->fAtoms[0]->getAlignment(); + uint64_t atomAlignP2 = (1 << atomAlign.powerOf2); + uint64_t currentModulus = (address % atomAlignP2); + if ( currentModulus != atomAlign.modulus ) { + if ( atomAlign.modulus > currentModulus ) + address += atomAlign.modulus-currentModulus; + else + address += atomAlign.modulus+atomAlignP2-currentModulus; + } + } + else { + address = ( (address+alignment-1) & (-alignment) ); + } // adjust file offset to match address if ( prevSection != NULL ) { - if ( finalLinkedImage || !prevSection->fVirtualSection ) + if ( virtualSectionOccupyAddressSpace || !prevSection->fVirtualSection ) fileOffset = (address - prevSection->getBaseAddress()) + prevSection->fFileOffset; else fileOffset = ( (fileOffset+alignment-1) & (-alignment) ); @@ -7063,16 +8943,16 @@ void Writer::assignFileOffsets() // update section info curSection->fFileOffset = fileOffset; curSection->setBaseAddress(address); - //fprintf(stderr, "%s %s %llX\n", curSegment->fName, curSection->fSectionName, address); + //fprintf(stderr, "%s %s addr=0x%llX, fileoffset=0x%llX, size=0x%llX\n", curSegment->fName, curSection->fSectionName, address, fileOffset, curSection->fSize); // keep track of trailing zero fill sections if ( curSection->fAllZeroFill && (firstZeroFillSection == NULL) ) firstZeroFillSection = curSection; - if ( !curSection->fAllZeroFill && (firstZeroFillSection != NULL) && finalLinkedImage ) + if ( !curSection->fAllZeroFill && (firstZeroFillSection != NULL) && (fOptions.outputKind() != Options::kObjectFile) ) throwf("zero-fill section %s not at end of segment", curSection->fSectionName); // update running pointers - if ( finalLinkedImage || !curSection->fVirtualSection ) + if ( virtualSectionOccupyAddressSpace || !curSection->fVirtualSection ) address += curSection->fSize; fileOffset += curSection->fSize; @@ -7096,16 +8976,18 @@ void Writer::assignFileOffsets() fileOffset = firstZeroFillSection->fFileOffset; } // page align segment size - curSegment->fFileSize = (curSegment->fFileSize+4095) & (-4096); - curSegment->fSize = (curSegment->fSize+4095) & (-4096); + curSegment->fFileSize = segmentAlign(curSegment->fFileSize, curSegment->fPageSize); + curSegment->fSize = segmentAlign(curSegment->fSize, curSegment->fPageSize); if ( !curSegment->fIndependentAddress && (curSegment->fBaseAddress >= nextContiguousAddress) ) { - nextContiguousAddress = (curSegment->fBaseAddress+curSegment->fSize+4095) & (-4096); + nextContiguousAddress = segmentAlign(curSegment->fBaseAddress+curSegment->fSize, curSegment->fPageSize); + fileOffset = segmentAlign(fileOffset, curSegment->fPageSize); if ( curSegment->fInitProtection & VM_PROT_WRITE ) nextWritableAddress = nextContiguousAddress; else nextReadOnlyAddress = nextContiguousAddress; } } + //fprintf(stderr, "end of seg %s, fileoffset=0x%llX, nextContiguousAddress=0x%llX\n", curSegment->fName, fileOffset, nextContiguousAddress); } // check for segment overlaps caused by user specified fixed segments (e.g. __PAGEZERO, __UNIXSTACK) @@ -7239,6 +9121,8 @@ ObjectFile::Atom::Scope MachHeaderAtom::getScope() const case Options::kDynamicBundle: case Options::kDyld: case Options::kObjectFile: + case Options::kPreload: + case Options::kKextBundle: return ObjectFile::Atom::scopeLinkageUnit; } throw "unknown header type"; @@ -7257,6 +9141,8 @@ ObjectFile::Atom::SymbolTableInclusion MachHeaderAtom::getSymbolTableInclusio case Options::kDyld: return ObjectFile::Atom::kSymbolTableIn; case Options::kObjectFile: + case Options::kPreload: + case Options::kKextBundle: return ObjectFile::Atom::kSymbolTableNotIn; } throw "unknown header type"; @@ -7274,6 +9160,8 @@ const char* MachHeaderAtom::getName() const case Options::kDynamicBundle: return "__mh_bundle_header"; case Options::kObjectFile: + case Options::kPreload: + case Options::kKextBundle: return NULL; case Options::kDyld: return "__mh_dylinker_header"; @@ -7292,6 +9180,8 @@ const char* MachHeaderAtom::getDisplayName() const case Options::kDyld: return this->getName(); case Options::kObjectFile: + case Options::kPreload: + case Options::kKextBundle: return "mach header"; } throw "unknown header type"; @@ -7319,6 +9209,12 @@ void MachHeaderAtom::copyRawContent(uint8_t buffer[]) const case Options::kDyld: fileType = MH_DYLINKER; break; + case Options::kPreload: + fileType = MH_PRELOAD; + break; + case Options::kKextBundle: + fileType = MH_KEXT_BUNDLE; + break; } // get flags @@ -7331,6 +9227,11 @@ void MachHeaderAtom::copyRawContent(uint8_t buffer[]) const if ( fWriter.fOptions.outputKind() == Options::kStaticExecutable ) { flags |= MH_NOUNDEFS; } + else if ( fWriter.fOptions.outputKind() == Options::kPreload ) { + flags |= MH_NOUNDEFS; + if ( fWriter.fOptions.positionIndependentExecutable() ) + flags |= MH_PIE; + } else { flags = MH_DYLDLINK; if ( fWriter.fOptions.bindAtLoad() ) @@ -7345,7 +9246,17 @@ void MachHeaderAtom::copyRawContent(uint8_t buffer[]) const flags |= MH_FORCE_FLAT; break; } - if ( fWriter.fHasWeakExports ) + bool hasWeakDefines = fWriter.fHasWeakExports; + if ( fWriter.fRegularDefAtomsThatOverrideADylibsWeakDef->size() != 0 ) { + for(std::set::iterator it = fWriter.fRegularDefAtomsThatOverrideADylibsWeakDef->begin(); + it != fWriter.fRegularDefAtomsThatOverrideADylibsWeakDef->end(); ++it) { + if ( fWriter.shouldExport(**it) ) { + hasWeakDefines = true; + break; + } + } + } + if ( hasWeakDefines ) flags |= MH_WEAK_DEFINES; if ( fWriter.fReferencesWeakImports || fWriter.fHasWeakExports ) flags |= MH_BINDS_TO_WEAK; @@ -7357,6 +9268,8 @@ void MachHeaderAtom::copyRawContent(uint8_t buffer[]) const flags |= MH_NO_REEXPORTED_DYLIBS; if ( fWriter.fOptions.positionIndependentExecutable() ) flags |= MH_PIE; + if ( fWriter.fOptions.markAutoDeadStripDylib() ) + flags |= MH_DEAD_STRIPPABLE_DYLIB; } if ( fWriter.fOptions.hasExecutableStack() ) flags |= MH_ALLOW_STACK_EXECUTION; @@ -7462,14 +9375,18 @@ void SegmentLoadCommandsAtom::computeSize() { uint64_t size = 0; std::vector& segmentInfos = fWriter.fSegmentInfos; - const int segCount = segmentInfos.size(); - for(int i=0; i < segCount; ++i) { - size += sizeof(macho_segment_command

); - std::vector& sectionInfos = segmentInfos[i]->fSections; - const int sectionCount = sectionInfos.size(); - for(int j=0; j < sectionCount; ++j) { - if ( fWriter.fEmitVirtualSections || ! sectionInfos[j]->fVirtualSection ) - size += sizeof(macho_section

); + int segCount = 0; + for(std::vector::iterator it = segmentInfos.begin(); it != segmentInfos.end(); ++it) { + SegmentInfo* seg = *it; + if ( seg->fHasLoadCommand ) { + ++segCount; + size += sizeof(macho_segment_command

); + std::vector& sectionInfos = seg->fSections; + const int sectionCount = sectionInfos.size(); + for(int j=0; j < sectionCount; ++j) { + if ( fWriter.fEmitVirtualSections || ! sectionInfos[j]->fVirtualSection ) + size += sizeof(macho_section

); + } } } fSize = size; @@ -7518,17 +9435,18 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const bzero(buffer, size); uint8_t* p = buffer; typename std::vector& segmentInfos = fWriter.fSegmentInfos; - const int segCount = segmentInfos.size(); - for(int i=0; i < segCount; ++i) { - SegmentInfo* segInfo = segmentInfos[i]; + for(std::vector::iterator it = segmentInfos.begin(); it != segmentInfos.end(); ++it) { + SegmentInfo* segInfo = *it; + if ( ! segInfo->fHasLoadCommand ) + continue; const int sectionCount = segInfo->fSections.size(); macho_segment_command

* cmd = (macho_segment_command

*)p; cmd->set_cmd(macho_segment_command

::CMD); cmd->set_segname(segInfo->fName); cmd->set_vmaddr(segInfo->fBaseAddress); - cmd->set_vmsize(segInfo->fSize); + cmd->set_vmsize(oneSegment ? 0 : segInfo->fSize); cmd->set_fileoff(segInfo->fFileOffset); - cmd->set_filesize(segInfo->fFileSize); + cmd->set_filesize(oneSegment ? 0 : segInfo->fFileSize); cmd->set_maxprot(segInfo->fMaxProtection); cmd->set_initprot(segInfo->fInitProtection); // add sections array @@ -7577,21 +9495,31 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const sect->set_flags(S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS); sect->set_reserved1(sectInfo->fIndirectSymbolOffset); sect->set_reserved2(sectInfo->fSize / sectInfo->fAtoms.size()); + if ( sectInfo->fHasTextLocalRelocs ) + sect->set_flags(sect->flags() | S_ATTR_LOC_RELOC); } else if ( sectInfo->fAllSelfModifyingStubs ) { sect->set_flags(S_SYMBOL_STUBS | S_ATTR_SELF_MODIFYING_CODE); sect->set_reserved1(sectInfo->fIndirectSymbolOffset); sect->set_reserved2(sectInfo->fSize / sectInfo->fAtoms.size()); } + else if ( sectInfo->fAllStubHelpers ) { + sect->set_flags(S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS); + if ( sectInfo->fHasTextLocalRelocs ) + sect->set_flags(sect->flags() | S_ATTR_LOC_RELOC); + } + else if ( sectInfo->fAtoms.at(0)->getContentType() == ObjectFile::Atom::kCStringType ) { + sect->set_flags(S_CSTRING_LITERALS); + } + else if ( sectInfo->fAtoms.at(0)->getContentType() == ObjectFile::Atom::kCFIType ) { + sect->set_flags(S_COALESCED | S_ATTR_NO_TOC | S_ATTR_STRIP_STATIC_SYMS); + } else if ( (strcmp(sectInfo->fSectionName, "__mod_init_func") == 0) && (strcmp(sectInfo->fSegmentName, "__DATA") == 0) ) { sect->set_flags(S_MOD_INIT_FUNC_POINTERS); } else if ( (strcmp(sectInfo->fSectionName, "__mod_term_func") == 0) && (strcmp(sectInfo->fSegmentName, "__DATA") == 0) ) { sect->set_flags(S_MOD_TERM_FUNC_POINTERS); } - else if ( (strcmp(sectInfo->fSectionName, "__eh_frame") == 0) && (strcmp(sectInfo->fSegmentName, "__TEXT") == 0) ) { - sect->set_flags(S_COALESCED | S_ATTR_NO_TOC | S_ATTR_STRIP_STATIC_SYMS); - } else if ( (strcmp(sectInfo->fSectionName, "__textcoal_nt") == 0) && (strcmp(sectInfo->fSegmentName, "__TEXT") == 0) ) { sect->set_flags(S_COALESCED); } @@ -7601,9 +9529,6 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const else if ( (strcmp(sectInfo->fSectionName, "__interpose") == 0) && (strcmp(sectInfo->fSegmentName, "__DATA") == 0) ) { sect->set_flags(S_INTERPOSING); } - else if ( (strcmp(sectInfo->fSectionName, "__cstring") == 0) && (strcmp(sectInfo->fSegmentName, "__TEXT") == 0) ) { - sect->set_flags(S_CSTRING_LITERALS); - } else if ( (strcmp(sectInfo->fSectionName, "__literal4") == 0) && (strcmp(sectInfo->fSegmentName, "__TEXT") == 0) ) { sect->set_flags(S_4BYTE_LITERALS); } @@ -7616,6 +9541,9 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const else if ( (strcmp(sectInfo->fSectionName, "__message_refs") == 0) && (strcmp(sectInfo->fSegmentName, "__OBJC") == 0) ) { sect->set_flags(S_LITERAL_POINTERS); } + else if ( (strcmp(sectInfo->fSectionName, "__objc_selrefs") == 0) && (strcmp(sectInfo->fSegmentName, "__DATA") == 0) ) { + sect->set_flags(S_LITERAL_POINTERS); + } else if ( (strcmp(sectInfo->fSectionName, "__cls_refs") == 0) && (strcmp(sectInfo->fSegmentName, "__OBJC") == 0) ) { sect->set_flags(S_LITERAL_POINTERS); } @@ -7632,6 +9560,7 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const if ( sectInfo->fHasTextExternalRelocs ) sect->set_flags(sect->flags() | S_ATTR_EXT_RELOC); } + //fprintf(stderr, "section %s flags=0x%08X\n", sectInfo->fSectionName, sect->flags()); } } p = &p[sizeof(macho_segment_command

) + sectionsEmitted*sizeof(macho_section

)]; @@ -7643,7 +9572,7 @@ void SegmentLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const template SymbolTableLoadCommandsAtom::SymbolTableLoadCommandsAtom(Writer& writer) - : LoadCommandAtom(writer, Segment::fgTextSegment) + : LoadCommandAtom(writer), fNeedsDynamicSymbolTable(false) { bzero(&fSymbolTable, sizeof(macho_symtab_command

)); bzero(&fDynamicSymbolTable, sizeof(macho_dysymtab_command

)); @@ -7652,11 +9581,14 @@ SymbolTableLoadCommandsAtom::SymbolTableLoadCommandsAtom(Writer& writer) case Options::kDynamicLibrary: case Options::kDynamicBundle: case Options::kDyld: + case Options::kKextBundle: fNeedsDynamicSymbolTable = true; break; case Options::kObjectFile: case Options::kStaticExecutable: fNeedsDynamicSymbolTable = false; + case Options::kPreload: + fNeedsDynamicSymbolTable = fWriter.fOptions.positionIndependentExecutable(); break; } writer.fSymbolTableCommands = this; @@ -7683,14 +9615,14 @@ uint64_t SymbolTableLoadCommandsAtom::getSize() const template void SymbolTableLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const { - // build LC_DYSYMTAB command + // build LC_SYMTAB command macho_symtab_command

* symbolTableCmd = (macho_symtab_command

*)buffer; bzero(symbolTableCmd, sizeof(macho_symtab_command

)); symbolTableCmd->set_cmd(LC_SYMTAB); symbolTableCmd->set_cmdsize(sizeof(macho_symtab_command

)); symbolTableCmd->set_nsyms(fWriter.fSymbolTableCount); - symbolTableCmd->set_symoff(fWriter.fSymbolTableAtom->getFileOffset()); - symbolTableCmd->set_stroff(fWriter.fStringsAtom->getFileOffset()); + symbolTableCmd->set_symoff(fWriter.fSymbolTableCount == 0 ? 0 : fWriter.fSymbolTableAtom->getFileOffset()); + symbolTableCmd->set_stroff(fWriter.fStringsAtom->getSize() == 0 ? 0 : fWriter.fStringsAtom->getFileOffset()); symbolTableCmd->set_strsize(fWriter.fStringsAtom->getSize()); // build LC_DYSYMTAB command @@ -7713,13 +9645,17 @@ void SymbolTableLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const dynamicSymbolTableCmd->set_extrefsymoff(fWriter.fModuleInfoAtom->getReferencesFileOffset()); dynamicSymbolTableCmd->set_nextrefsyms(fWriter.fModuleInfoAtom->getReferencesCount()); } - dynamicSymbolTableCmd->set_indirectsymoff(fWriter.fIndirectTableAtom->getFileOffset()); - dynamicSymbolTableCmd->set_nindirectsyms(fWriter.fIndirectTableAtom->fTable.size()); + dynamicSymbolTableCmd->set_indirectsymoff((fWriter.fIndirectTableAtom == NULL) ? 0 : fWriter.fIndirectTableAtom->getFileOffset()); + dynamicSymbolTableCmd->set_nindirectsyms((fWriter.fIndirectTableAtom == NULL) ? 0 : fWriter.fIndirectTableAtom->fTable.size()); if ( fWriter.fOptions.outputKind() != Options::kObjectFile ) { - dynamicSymbolTableCmd->set_extreloff((fWriter.fExternalRelocs.size()==0) ? 0 : fWriter.fExternalRelocationsAtom->getFileOffset()); - dynamicSymbolTableCmd->set_nextrel(fWriter.fExternalRelocs.size()); - dynamicSymbolTableCmd->set_locreloff((fWriter.fInternalRelocs.size()==0) ? 0 : fWriter.fLocalRelocationsAtom->getFileOffset()); - dynamicSymbolTableCmd->set_nlocrel(fWriter.fInternalRelocs.size()); + if ( fWriter.fExternalRelocationsAtom != 0 ) { + dynamicSymbolTableCmd->set_extreloff((fWriter.fExternalRelocs.size()==0) ? 0 : fWriter.fExternalRelocationsAtom->getFileOffset()); + dynamicSymbolTableCmd->set_nextrel(fWriter.fExternalRelocs.size()); + } + if ( fWriter.fLocalRelocationsAtom != 0 ) { + dynamicSymbolTableCmd->set_locreloff((fWriter.fInternalRelocs.size()==0) ? 0 : fWriter.fLocalRelocationsAtom->getFileOffset()); + dynamicSymbolTableCmd->set_nlocrel(fWriter.fInternalRelocs.size()); + } } } } @@ -7840,8 +9776,8 @@ template void RoutinesLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const { uint64_t initAddr = fWriter.getAtomLoadAddress(fWriter.fEntryPoint); - if (fWriter.fEntryPoint->isThumb()) - initAddr |= 1ULL; + if (fWriter.fEntryPoint->isThumb()) + initAddr |= 1ULL; bzero(buffer, sizeof(macho_routines_command

)); macho_routines_command

* cmd = (macho_routines_command

*)buffer; cmd->set_cmd(macho_routines_command

::CMD); @@ -8044,6 +9980,8 @@ void ThreadsLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const { uint64_t size = this->getSize(); uint64_t start = fWriter.getAtomLoadAddress(fWriter.fEntryPoint); + if ( fWriter.fEntryPoint->isThumb() ) + start |= 1ULL; bzero(buffer, size); macho_thread_command* cmd = (macho_thread_command*)buffer; cmd->set_cmd(LC_UNIXTHREAD); @@ -8106,9 +10044,479 @@ void LoadCommandsPaddingAtom::setSize(uint64_t newSize) } template -uint64_t LinkEditAtom::getFileOffset() const -{ - return ((SectionInfo*)this->getSection())->fFileOffset + this->getSectionOffset(); +void UnwindInfoAtom::addUnwindInfo(ObjectFile::Atom* func, uint32_t offset, uint32_t encoding, + ObjectFile::Reference* fdeRef, ObjectFile::Reference* lsdaRef, + ObjectFile::Atom* personalityPointer) +{ + Info info; + info.func = func; + if ( fdeRef != NULL ) + info.fde = &fdeRef->getTarget(); + else + info.fde = NULL; + if ( lsdaRef != NULL ) { + info.lsda = &lsdaRef->getTarget(); + info.lsdaOffset = lsdaRef->getTargetOffset(); + } + else { + info.lsda = NULL; + info.lsdaOffset = 0; + } + info.personalityPointer = personalityPointer; + info.encoding = encoding; + fInfos.push_back(info); + //fprintf(stderr, "addUnwindInfo() encoding=0x%08X, lsda=%p, lsdaOffset=%d, person=%p, func=%s\n", + // encoding, info.lsda, info.lsdaOffset, personalityPointer, func->getDisplayName()); +} + +template <> +bool UnwindInfoAtom::encodingMeansUseDwarf(compact_unwind_encoding_t encoding) +{ + return ( (encoding & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_DWARF); +} + +template <> +bool UnwindInfoAtom::encodingMeansUseDwarf(compact_unwind_encoding_t encoding) +{ + return ( (encoding & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_DWARF); +} + +template +bool UnwindInfoAtom::encodingMeansUseDwarf(compact_unwind_encoding_t encoding) +{ + return false; +} + + +template +void UnwindInfoAtom::compressDuplicates(std::vector& uniqueInfos) +{ + // build new list removing entries where next function has same encoding + uniqueInfos.reserve(fInfos.size()); + Info last; + last.func = NULL; + last.lsda = NULL; + last.lsdaOffset = 0; + last.personalityPointer = NULL; + last.encoding = 0xFFFFFFFF; + for(typename std::vector::iterator it=fInfos.begin(); it != fInfos.end(); ++it) { + Info& newInfo = *it; + bool newNeedsDwarf = encodingMeansUseDwarf(newInfo.encoding); + // remove infos which have same encoding and personalityPointer as last one + if ( newNeedsDwarf || (newInfo.encoding != last.encoding) || (newInfo.personalityPointer != last.personalityPointer) + || (newInfo.lsda != NULL) || (last.lsda != NULL) ) { + uniqueInfos.push_back(newInfo); + } + last = newInfo; + } + //fprintf(stderr, "compressDuplicates() fInfos.size()=%lu, uniqueInfos.size()=%lu\n", fInfos.size(), uniqueInfos.size()); +} + +template +void UnwindInfoAtom::findCommonEncoding(const std::vector& uniqueInfos, std::map& commonEncodings) +{ + // scan infos to get frequency counts for each encoding + std::map encodingsUsed; + unsigned int mostCommonEncodingUsageCount = 0; + for(typename std::vector::const_iterator it=uniqueInfos.begin(); it != uniqueInfos.end(); ++it) { + // never put dwarf into common table + if ( encodingMeansUseDwarf(it->encoding) ) + continue; + std::map::iterator pos = encodingsUsed.find(it->encoding); + if ( pos == encodingsUsed.end() ) { + encodingsUsed[it->encoding] = 1; + } + else { + encodingsUsed[it->encoding] += 1; + if ( mostCommonEncodingUsageCount < encodingsUsed[it->encoding] ) + mostCommonEncodingUsageCount = encodingsUsed[it->encoding]; + } + } + // put the most common encodings into the common table, but at most 127 of them + for(unsigned int usages=mostCommonEncodingUsageCount; usages > 1; --usages) { + for (std::map::iterator euit=encodingsUsed.begin(); euit != encodingsUsed.end(); ++euit) { + if ( euit->second == usages ) { + unsigned int size = commonEncodings.size(); + if ( size < 127 ) { + commonEncodings[euit->first] = size; + } + } + } + } +} + +template +void UnwindInfoAtom::makeLsdaIndex(const std::vector& uniqueInfos, std::map& lsdaIndexOffsetMap) +{ + for(typename std::vector::const_iterator it=uniqueInfos.begin(); it != uniqueInfos.end(); ++it) { + lsdaIndexOffsetMap[it->func] = fLSDAIndex.size() * sizeof(macho_unwind_info_section_header_lsda_index_entry

); + if ( it->lsda != NULL ) { + LSDAEntry entry; + entry.func = it->func; + entry.lsda = it->lsda; + entry.lsdaOffset = it->lsdaOffset; + fLSDAIndex.push_back(entry); + } + } +} + +template +void UnwindInfoAtom::makePersonalityIndex(std::vector& uniqueInfos) +{ + for(typename std::vector::iterator it=uniqueInfos.begin(); it != uniqueInfos.end(); ++it) { + if ( it->personalityPointer != NULL ) { + std::map::iterator pos = fPersonalityIndexMap.find(it->personalityPointer); + if ( pos == fPersonalityIndexMap.end() ) { + const uint32_t nextIndex = fPersonalityIndexMap.size() + 1; + fPersonalityIndexMap[it->personalityPointer] = nextIndex; + } + uint32_t personalityIndex = fPersonalityIndexMap[it->personalityPointer]; + it->encoding |= (personalityIndex << (__builtin_ctz(UNWIND_PERSONALITY_MASK)) ); + } + } +} + +template +unsigned int UnwindInfoAtom::makeRegularSecondLevelPage(const std::vector& uniqueInfos, uint32_t pageSize, + unsigned int endIndex, uint8_t*& pageEnd) +{ + const unsigned int maxEntriesPerPage = (pageSize - sizeof(unwind_info_regular_second_level_page_header))/sizeof(unwind_info_regular_second_level_entry); + const unsigned int entriesToAdd = ((endIndex > maxEntriesPerPage) ? maxEntriesPerPage : endIndex); + uint8_t* pageStart = pageEnd + - entriesToAdd*sizeof(unwind_info_regular_second_level_entry) + - sizeof(unwind_info_regular_second_level_page_header); + macho_unwind_info_regular_second_level_page_header

* page = (macho_unwind_info_regular_second_level_page_header

*)pageStart; + page->set_kind(UNWIND_SECOND_LEVEL_REGULAR); + page->set_entryPageOffset(sizeof(macho_unwind_info_regular_second_level_page_header

)); + page->set_entryCount(entriesToAdd); + macho_unwind_info_regular_second_level_entry

* entryTable = (macho_unwind_info_regular_second_level_entry

*)(pageStart + page->entryPageOffset()); + for (unsigned int i=0; i < entriesToAdd; ++i) { + const Info& info = uniqueInfos[endIndex-entriesToAdd+i]; + entryTable[i].set_functionOffset(0); + entryTable[i].set_encoding(info.encoding); + RegFixUp fixup; + fixup.contentPointer = (uint8_t*)(&entryTable[i]); + fixup.func = info.func; + fixup.fde = ( encodingMeansUseDwarf(info.encoding) ? info.fde : NULL ); + fRegFixUps.push_back(fixup); + } + //fprintf(stderr, "regular page with %u entries\n", entriesToAdd); + pageEnd = pageStart; + return endIndex - entriesToAdd; +} + + +template +unsigned int UnwindInfoAtom::makeCompressedSecondLevelPage(const std::vector& uniqueInfos, + const std::map commonEncodings, + uint32_t pageSize, unsigned int endIndex, uint8_t*& pageEnd) +{ + const bool log = false; + if (log) fprintf(stderr, "makeCompressedSecondLevelPage(pageSize=%u, endIndex=%u)\n", pageSize, endIndex); + // first pass calculates how many compressed entries we could fit in this sized page + // keep adding entries to page until: + // 1) encoding table plus entry table plus header exceed page size + // 2) the file offset delta from the first to last function > 24 bits + // 3) custom encoding index reachs 255 + // 4) run out of uniqueInfos to encode + std::map pageSpecificEncodings; + uint32_t space4 = (pageSize - sizeof(unwind_info_compressed_second_level_page_header))/sizeof(uint32_t); + std::vector encodingIndexes; + int index = endIndex-1; + int entryCount = 0; + uint64_t lastEntryAddress = uniqueInfos[index].func->getAddress(); + bool canDo = true; + while ( canDo && (index >= 0) ) { + const Info& info = uniqueInfos[index--]; + // compute encoding index + unsigned int encodingIndex; + std::map::const_iterator pos = commonEncodings.find(info.encoding); + if ( pos != commonEncodings.end() ) { + encodingIndex = pos->second; + } + else { + // no commmon entry, so add one on this page + uint32_t encoding = info.encoding; + if ( encodingMeansUseDwarf(encoding) ) { + // make unique pseudo encoding so this dwarf will gets is own encoding entry slot + encoding += (index+1); + } + std::map::iterator ppos = pageSpecificEncodings.find(encoding); + if ( ppos != pageSpecificEncodings.end() ) { + encodingIndex = pos->second; + } + else { + encodingIndex = commonEncodings.size() + pageSpecificEncodings.size(); + if ( encodingIndex <= 255 ) { + pageSpecificEncodings[encoding] = encodingIndex; + } + else { + canDo = false; // case 3) + if (log) fprintf(stderr, "end of compressed page with %u entries, %lu custom encodings because too many custom encodings\n", + entryCount, pageSpecificEncodings.size()); + } + } + } + if ( canDo ) + encodingIndexes.push_back(encodingIndex); + // compute function offset + uint32_t funcOffsetWithInPage = lastEntryAddress - info.func->getAddress(); + if ( funcOffsetWithInPage > 0x00FFFF00 ) { + // don't use 0x00FFFFFF because addresses may vary after atoms are laid out again + canDo = false; // case 2) + if (log) fprintf(stderr, "can't use compressed page with %u entries because function offset too big\n", entryCount); + } + else { + ++entryCount; + } + // check room for entry + if ( (pageSpecificEncodings.size()+entryCount) >= space4 ) { + canDo = false; // case 1) + --entryCount; + if (log) fprintf(stderr, "end of compressed page with %u entries because full\n", entryCount); + } + //if (log) fprintf(stderr, "space4=%d, pageSpecificEncodings.size()=%ld, entryCount=%d\n", space4, pageSpecificEncodings.size(), entryCount); + } + + // check for cases where it would be better to use a regular (non-compressed) page + const unsigned int compressPageUsed = sizeof(unwind_info_compressed_second_level_page_header) + + pageSpecificEncodings.size()*sizeof(uint32_t) + + entryCount*sizeof(uint32_t); + if ( (compressPageUsed < (pageSize-4) && (index >= 0) ) ) { + const int regularEntriesPerPage = (pageSize - sizeof(unwind_info_regular_second_level_page_header))/sizeof(unwind_info_regular_second_level_entry); + if ( entryCount < regularEntriesPerPage ) { + return makeRegularSecondLevelPage(uniqueInfos, pageSize, endIndex, pageEnd); + } + } + + // check if we need any padding because adding another entry would take 8 bytes but only have room for 4 + uint32_t pad = 0; + if ( compressPageUsed == (pageSize-4) ) + pad = 4; + + // second pass fills in page + uint8_t* pageStart = pageEnd - compressPageUsed - pad; + macho_unwind_info_compressed_second_level_page_header

* page = (macho_unwind_info_compressed_second_level_page_header

*)pageStart; + page->set_kind(UNWIND_SECOND_LEVEL_COMPRESSED); + page->set_entryPageOffset(sizeof(macho_unwind_info_compressed_second_level_page_header

)); + page->set_entryCount(entryCount); + page->set_encodingsPageOffset(page->entryPageOffset()+entryCount*sizeof(uint32_t)); + page->set_encodingsCount(pageSpecificEncodings.size()); + uint32_t* const encodingsArray = (uint32_t*)&pageStart[page->encodingsPageOffset()]; + // fill in entry table + uint32_t* const entiresArray = (uint32_t*)&pageStart[page->entryPageOffset()]; + ObjectFile::Atom* firstFunc = uniqueInfos[endIndex-entryCount].func; + for(unsigned int i=endIndex-entryCount; i < endIndex; ++i) { + const Info& info = uniqueInfos[i]; + uint8_t encodingIndex; + if ( encodingMeansUseDwarf(info.encoding) ) { + // dwarf entries are always in page specific encodings + encodingIndex = pageSpecificEncodings[info.encoding+i]; + } + else { + std::map::const_iterator pos = commonEncodings.find(info.encoding); + if ( pos != commonEncodings.end() ) + encodingIndex = pos->second; + else + encodingIndex = pageSpecificEncodings[info.encoding]; + } + uint32_t entryIndex = i - endIndex + entryCount; + A::P::E::set32(entiresArray[entryIndex], encodingIndex << 24); + CompressedFixUp funcStartFixUp; + funcStartFixUp.contentPointer = (uint8_t*)(&entiresArray[entryIndex]); + funcStartFixUp.func = info.func; + funcStartFixUp.fromFunc = firstFunc; + fCompressedFixUps.push_back(funcStartFixUp); + if ( encodingMeansUseDwarf(info.encoding) ) { + CompressedEncodingFixUp dwarfStartFixup; + dwarfStartFixup.contentPointer = (uint8_t*)(&encodingsArray[encodingIndex-commonEncodings.size()]); + dwarfStartFixup.fde = info.fde; + fCompressedEncodingFixUps.push_back(dwarfStartFixup); + } + } + // fill in encodings table + for(std::map::const_iterator it = pageSpecificEncodings.begin(); it != pageSpecificEncodings.end(); ++it) { + A::P::E::set32(encodingsArray[it->second-commonEncodings.size()], it->first); + } + + if (log) fprintf(stderr, "compressed page with %u entries, %lu custom encodings\n", entryCount, pageSpecificEncodings.size()); + + // update pageEnd; + pageEnd = pageStart; + return endIndex-entryCount; // endIndex for next page +} + +template <> void UnwindInfoAtom::generate() { } +template <> void UnwindInfoAtom::generate() { } +template <> void UnwindInfoAtom::generate() { } + + +template +void UnwindInfoAtom::generate() +{ + // only generate table if there are functions with unwind info + if ( fInfos.size() > 0 ) { + // find offset of end of __unwind_info section + SectionInfo* unwindSectionInfo = (SectionInfo*)this->getSection(); + + // build new list that has proper offsetInImage and remove entries where next function has same encoding + std::vector uniqueInfos; + this->compressDuplicates(uniqueInfos); + + // build personality index, update encodings with personality index + this->makePersonalityIndex(uniqueInfos); + if ( fPersonalityIndexMap.size() > 3 ) + throw "too many personality routines for compact unwind to encode"; + + // put the most common encodings into the common table, but at most 127 of them + std::map commonEncodings; + this->findCommonEncoding(uniqueInfos, commonEncodings); + + // build lsda index + std::map lsdaIndexOffsetMap; + this->makeLsdaIndex(uniqueInfos, lsdaIndexOffsetMap); + + // calculate worst case size for all unwind info pages when allocating buffer + const unsigned int entriesPerRegularPage = (4096-sizeof(unwind_info_regular_second_level_page_header))/sizeof(unwind_info_regular_second_level_entry); + const unsigned int pageCount = ((uniqueInfos.size() - 1)/entriesPerRegularPage) + 1; + fPagesContentForDelete = (uint8_t*)calloc(pageCount,4096); + fPagesSize = 0; + if ( fPagesContentForDelete == NULL ) + throw "could not allocate space for compact unwind info"; + ObjectFile::Atom* secondLevelFirstFuncs[pageCount*3]; + uint8_t* secondLevelPagesStarts[pageCount*3]; + + // make last second level page smaller so that all other second level pages can be page aligned + uint32_t maxLastPageSize = unwindSectionInfo->fFileOffset % 4096; + uint32_t tailPad = 0; + if ( maxLastPageSize < 128 ) { + tailPad = maxLastPageSize; + maxLastPageSize = 4096; + } + + // fill in pages in reverse order + unsigned int endIndex = uniqueInfos.size(); + unsigned int secondLevelPageCount = 0; + uint8_t* pageEnd = &fPagesContentForDelete[pageCount*4096]; + uint32_t pageSize = maxLastPageSize; + while ( endIndex > 0 ) { + endIndex = makeCompressedSecondLevelPage(uniqueInfos, commonEncodings, pageSize, endIndex, pageEnd); + secondLevelPagesStarts[secondLevelPageCount] = pageEnd; + secondLevelFirstFuncs[secondLevelPageCount] = uniqueInfos[endIndex].func; + ++secondLevelPageCount; + pageSize = 4096; // last page can be odd size, make rest up to 4096 bytes in size + } + fPagesContent = pageEnd; + fPagesSize = &fPagesContentForDelete[pageCount*4096] - pageEnd; + + // calculate section layout + const uint32_t commonEncodingsArraySectionOffset = sizeof(macho_unwind_info_section_header

); + const uint32_t commonEncodingsArrayCount = commonEncodings.size(); + const uint32_t commonEncodingsArraySize = commonEncodingsArrayCount * sizeof(compact_unwind_encoding_t); + const uint32_t personalityArraySectionOffset = commonEncodingsArraySectionOffset + commonEncodingsArraySize; + const uint32_t personalityArrayCount = fPersonalityIndexMap.size(); + const uint32_t personalityArraySize = personalityArrayCount * sizeof(uint32_t); + const uint32_t indexSectionOffset = personalityArraySectionOffset + personalityArraySize; + const uint32_t indexCount = secondLevelPageCount+1; + const uint32_t indexSize = indexCount * sizeof(macho_unwind_info_section_header_index_entry

); + const uint32_t lsdaIndexArraySectionOffset = indexSectionOffset + indexSize; + const uint32_t lsdaIndexArrayCount = fLSDAIndex.size(); + const uint32_t lsdaIndexArraySize = lsdaIndexArrayCount * sizeof(macho_unwind_info_section_header_lsda_index_entry

); + const uint32_t headerEndSectionOffset = lsdaIndexArraySectionOffset + lsdaIndexArraySize; + + + // allocate and fill in section header + fHeaderSize = headerEndSectionOffset; + fHeaderContent = new uint8_t[fHeaderSize]; + bzero(fHeaderContent, fHeaderSize); + macho_unwind_info_section_header

* sectionHeader = (macho_unwind_info_section_header

*)fHeaderContent; + sectionHeader->set_version(UNWIND_SECTION_VERSION); + sectionHeader->set_commonEncodingsArraySectionOffset(commonEncodingsArraySectionOffset); + sectionHeader->set_commonEncodingsArrayCount(commonEncodingsArrayCount); + sectionHeader->set_personalityArraySectionOffset(personalityArraySectionOffset); + sectionHeader->set_personalityArrayCount(personalityArrayCount); + sectionHeader->set_indexSectionOffset(indexSectionOffset); + sectionHeader->set_indexCount(indexCount); + + // copy common encodings + uint32_t* commonEncodingsTable = (uint32_t*)&fHeaderContent[commonEncodingsArraySectionOffset]; + for (std::map::iterator it=commonEncodings.begin(); it != commonEncodings.end(); ++it) + A::P::E::set32(commonEncodingsTable[it->second], it->first); + + // make references for personality entries + uint32_t* personalityArray = (uint32_t*)&fHeaderContent[sectionHeader->personalityArraySectionOffset()]; + for (std::map::iterator it=fPersonalityIndexMap.begin(); it != fPersonalityIndexMap.end(); ++it) { + uint32_t offset = (uint8_t*)&personalityArray[it->second-1] - fHeaderContent; + fReferences.push_back(new WriterReference(offset, A::kImageOffset32, it->first)); + } + + // build first level index and references + macho_unwind_info_section_header_index_entry

* indexTable = (macho_unwind_info_section_header_index_entry

*)&fHeaderContent[indexSectionOffset]; + for (unsigned int i=0; i < secondLevelPageCount; ++i) { + unsigned int reverseIndex = secondLevelPageCount - 1 - i; + indexTable[i].set_functionOffset(0); + indexTable[i].set_secondLevelPagesSectionOffset(secondLevelPagesStarts[reverseIndex]-fPagesContent+headerEndSectionOffset); + indexTable[i].set_lsdaIndexArraySectionOffset(lsdaIndexOffsetMap[secondLevelFirstFuncs[reverseIndex]]+lsdaIndexArraySectionOffset); + uint32_t refOffset = (uint8_t*)&indexTable[i] - fHeaderContent; + fReferences.push_back(new WriterReference(refOffset, A::kImageOffset32, secondLevelFirstFuncs[reverseIndex])); + } + indexTable[secondLevelPageCount].set_functionOffset(0); + indexTable[secondLevelPageCount].set_secondLevelPagesSectionOffset(0); + indexTable[secondLevelPageCount].set_lsdaIndexArraySectionOffset(lsdaIndexArraySectionOffset+lsdaIndexArraySize); + fReferences.push_back(new WriterReference((uint8_t*)&indexTable[secondLevelPageCount] - fHeaderContent, A::kImageOffset32, + fInfos.back().func, fInfos.back().func->getSize()+1)); + + // build lsda references + uint32_t lsdaEntrySectionOffset = lsdaIndexArraySectionOffset; + for (typename std::vector::iterator it = fLSDAIndex.begin(); it != fLSDAIndex.end(); ++it) { + fReferences.push_back(new WriterReference(lsdaEntrySectionOffset, A::kImageOffset32, it->func)); + fReferences.push_back(new WriterReference(lsdaEntrySectionOffset+4, A::kImageOffset32, it->lsda, it->lsdaOffset)); + lsdaEntrySectionOffset += sizeof(unwind_info_section_header_lsda_index_entry); + } + + // make references for regular second level entries + for (typename std::vector::iterator it = fRegFixUps.begin(); it != fRegFixUps.end(); ++it) { + uint32_t offset = (it->contentPointer - fPagesContent) + fHeaderSize; + fReferences.push_back(new WriterReference(offset, A::kImageOffset32, it->func)); + if ( it->fde != NULL ) + fReferences.push_back(new WriterReference(offset+4, A::kSectionOffset24, it->fde)); + } + // make references for compressed second level entries + for (typename std::vector::iterator it = fCompressedFixUps.begin(); it != fCompressedFixUps.end(); ++it) { + uint32_t offset = (it->contentPointer - fPagesContent) + fHeaderSize; + fReferences.push_back(new WriterReference(offset, A::kPointerDiff24, it->func, 0, it->fromFunc, 0)); + } + for (typename std::vector::iterator it = fCompressedEncodingFixUps.begin(); it != fCompressedEncodingFixUps.end(); ++it) { + uint32_t offset = (it->contentPointer - fPagesContent) + fHeaderSize; + fReferences.push_back(new WriterReference(offset, A::kSectionOffset24, it->fde)); + } + + // update section record with new size + unwindSectionInfo->fSize = this->getSize(); + + // alter alignment so this section lays out so second level tables are page aligned + if ( secondLevelPageCount > 2 ) + fAlignment = ObjectFile::Alignment(12, (unwindSectionInfo->fFileOffset - this->getSize()) % 4096); + } + +} + + + + +template +void UnwindInfoAtom::copyRawContent(uint8_t buffer[]) const +{ + memcpy(buffer, fHeaderContent, fHeaderSize); + memcpy(&buffer[fHeaderSize], fPagesContent, fPagesSize); +} + + + +template +uint64_t LinkEditAtom::getFileOffset() const +{ + return ((SectionInfo*)this->getSection())->fFileOffset + this->getSectionOffset(); } @@ -8180,12 +10588,10 @@ void IndirectTableLinkEditAtom::copyRawContent(uint8_t buffer[]) const const uint32_t indirectTableSize = fTable.size(); uint32_t* indirectTable = (uint32_t*)buffer; for(std::vector::const_iterator it = fTable.begin(); it != fTable.end(); ++it) { - if ( it->indirectIndex < indirectTableSize ) { + if ( it->indirectIndex < indirectTableSize ) A::P::E::set32(indirectTable[it->indirectIndex], it->symbolIndex); - } - else { + else throwf("malformed indirect table. size=%d, index=%d", indirectTableSize, it->indirectIndex); - } } } @@ -8235,12 +10641,14 @@ void ModuleInfoLinkEditAtom::copyRawContent(uint8_t buffer[]) const p->set_module_index(0); } // create module table (one entry) + pint_t objcModuleSectionStart = 0; + pint_t objcModuleSectionSize = 0; uint16_t numInits = 0; uint16_t numTerms = 0; std::vector& segmentInfos = fWriter.fSegmentInfos; for (std::vector::iterator segit = segmentInfos.begin(); segit != segmentInfos.end(); ++segit) { + std::vector& sectionInfos = (*segit)->fSections; if ( strcmp((*segit)->fName, "__DATA") == 0 ) { - std::vector& sectionInfos = (*segit)->fSections; for (std::vector::iterator sectit = sectionInfos.begin(); sectit != sectionInfos.end(); ++sectit) { if ( strcmp((*sectit)->fSectionName, "__mod_init_func") == 0 ) numInits = (*sectit)->fSize / sizeof(typename A::P::uint_t); @@ -8248,6 +10656,15 @@ void ModuleInfoLinkEditAtom::copyRawContent(uint8_t buffer[]) const numTerms = (*sectit)->fSize / sizeof(typename A::P::uint_t); } } + else if ( strcmp((*segit)->fName, "__OBJC") == 0 ) { + for (std::vector::iterator sectit = sectionInfos.begin(); sectit != sectionInfos.end(); ++sectit) { + SectionInfo* sectInfo = (*sectit); + if ( strcmp(sectInfo->fSectionName, "__module_info") == 0 ) { + objcModuleSectionStart = sectInfo->getBaseAddress(); + objcModuleSectionSize = sectInfo->fSize; + } + } + } } macho_dylib_module

* module = (macho_dylib_module

*)&buffer[fWriter.fSymbolTableExportCount*sizeof(macho_dylib_table_of_contents

)]; module->set_module_name(fModuleNameOffset); @@ -8261,8 +10678,8 @@ void ModuleInfoLinkEditAtom::copyRawContent(uint8_t buffer[]) const module->set_nextrel(fWriter.fExternalRelocs.size()); module->set_iinit_iterm(0,0); module->set_ninit_nterm(numInits,numTerms); - module->set_objc_module_info_addr(0); // Not used by ld_classic, and not used by objc runtime for many years - module->set_objc_module_info_size(0); // Not used by ld_classic, and not used by objc runtime for many years + module->set_objc_module_info_addr(objcModuleSectionStart); + module->set_objc_module_info_size(objcModuleSectionSize); // create reference table macho_dylib_reference

* ref = (macho_dylib_reference

*)((uint8_t*)module + sizeof(macho_dylib_module

)); for(uint32_t i=0; i < fWriter.fSymbolTableExportCount; ++i, ++ref) { @@ -8431,12 +10848,14 @@ template void SegmentSplitInfoLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const { uint64_t size = this->getSize(); - bzero(buffer, size); - macho_linkedit_data_command

* cmd = (macho_linkedit_data_command

*)buffer; - cmd->set_cmd(LC_SEGMENT_SPLIT_INFO); - cmd->set_cmdsize(size); - cmd->set_dataoff(fWriter.fSplitCodeToDataContentAtom->getFileOffset()); - cmd->set_datasize(fWriter.fSplitCodeToDataContentAtom->getSize()); + if ( size > 0 ) { + bzero(buffer, size); + macho_linkedit_data_command

* cmd = (macho_linkedit_data_command

*)buffer; + cmd->set_cmd(LC_SEGMENT_SPLIT_INFO); + cmd->set_cmdsize(size); + cmd->set_dataoff(fWriter.fSplitCodeToDataContentAtom->getFileOffset()); + cmd->set_datasize(fWriter.fSplitCodeToDataContentAtom->getSize()); + } } @@ -8572,6 +10991,783 @@ template <> Segment& ObjCInfoAtom::getInfoSegment() const { return Segme template <> Segment& ObjCInfoAtom::getInfoSegment() const { return Segment::fgDataSegment; } + + +template +void DyldInfoLoadCommandsAtom::copyRawContent(uint8_t buffer[]) const +{ + // build LC_DYLD_INFO command + macho_dyld_info_command

* cmd = (macho_dyld_info_command

*)buffer; + bzero(cmd, sizeof(macho_dyld_info_command

)); + + cmd->set_cmd( fWriter.fOptions.makeClassicDyldInfo() ? LC_DYLD_INFO : LC_DYLD_INFO_ONLY); + cmd->set_cmdsize(sizeof(macho_dyld_info_command

)); + if ( (fWriter.fCompressedRebaseInfoAtom != NULL) && (fWriter.fCompressedRebaseInfoAtom->getSize() != 0) ) { + cmd->set_rebase_off(fWriter.fCompressedRebaseInfoAtom->getFileOffset()); + cmd->set_rebase_size(fWriter.fCompressedRebaseInfoAtom->getSize()); + } + if ( (fWriter.fCompressedBindingInfoAtom != NULL) && (fWriter.fCompressedBindingInfoAtom->getSize() != 0) ) { + cmd->set_bind_off(fWriter.fCompressedBindingInfoAtom->getFileOffset()); + cmd->set_bind_size(fWriter.fCompressedBindingInfoAtom->getSize()); + } + if ( (fWriter.fCompressedWeakBindingInfoAtom != NULL) && (fWriter.fCompressedWeakBindingInfoAtom->getSize() != 0) ) { + cmd->set_weak_bind_off(fWriter.fCompressedWeakBindingInfoAtom->getFileOffset()); + cmd->set_weak_bind_size(fWriter.fCompressedWeakBindingInfoAtom->getSize()); + } + if ( (fWriter.fCompressedLazyBindingInfoAtom != NULL) && (fWriter.fCompressedLazyBindingInfoAtom->getSize() != 0) ) { + cmd->set_lazy_bind_off(fWriter.fCompressedLazyBindingInfoAtom->getFileOffset()); + cmd->set_lazy_bind_size(fWriter.fCompressedLazyBindingInfoAtom->getSize()); + } + if ( (fWriter.fCompressedExportInfoAtom != NULL) && (fWriter.fCompressedExportInfoAtom->getSize() != 0) ) { + cmd->set_export_off(fWriter.fCompressedExportInfoAtom->getFileOffset()); + cmd->set_export_size(fWriter.fCompressedExportInfoAtom->getSize()); + } +} + + +struct rebase_tmp +{ + rebase_tmp(uint8_t op, uint64_t p1, uint64_t p2=0) : opcode(op), operand1(p1), operand2(p2) {} + uint8_t opcode; + uint64_t operand1; + uint64_t operand2; +}; + + +template +void CompressedRebaseInfoLinkEditAtom::encode() +{ + // sort rebase info by type, then address + const std::vector& segments = fWriter.fSegmentInfos; + std::vector& info = fWriter.fRebaseInfo; + std::sort(info.begin(), info.end()); + + // convert to temp encoding that can be more easily optimized + std::vector mid; + const SegmentInfo* currentSegment = NULL; + unsigned int segIndex = 0; + uint8_t type = 0; + uint64_t address = (uint64_t)(-1); + for (std::vector::iterator it = info.begin(); it != info.end(); ++it) { + if ( type != it->fType ) { + mid.push_back(rebase_tmp(REBASE_OPCODE_SET_TYPE_IMM, it->fType)); + type = it->fType; + } + if ( address != it->fAddress ) { + if ( (currentSegment == NULL) || (it->fAddress < currentSegment->fBaseAddress) + || ((currentSegment->fBaseAddress+currentSegment->fSize) <= it->fAddress) ) { + segIndex = 0; + for (std::vector::const_iterator segit = segments.begin(); segit != segments.end(); ++segit) { + if ( ((*segit)->fBaseAddress <= it->fAddress) && (it->fAddress < ((*segit)->fBaseAddress+(*segit)->fSize)) ) { + currentSegment = *segit; + break; + } + ++segIndex; + } + mid.push_back(rebase_tmp(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, segIndex, it->fAddress - currentSegment->fBaseAddress)); + } + else { + mid.push_back(rebase_tmp(REBASE_OPCODE_ADD_ADDR_ULEB, it->fAddress-address)); + } + address = it->fAddress; + } + mid.push_back(rebase_tmp(REBASE_OPCODE_DO_REBASE_ULEB_TIMES, 1)); + address += sizeof(pint_t); + } + mid.push_back(rebase_tmp(REBASE_OPCODE_DONE, 0)); + + // optimize phase 1, compress packed runs of pointers + rebase_tmp* dst = &mid[0]; + for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) { + if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES) && (src->operand1 == 1) ) { + *dst = *src++; + while (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES ) { + dst->operand1 += src->operand1; + ++src; + } + --src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = REBASE_OPCODE_DONE; + + // optimize phase 2, combine rebase/add pairs + dst = &mid[0]; + for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) { + if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES) + && (src->operand1 == 1) + && (src[1].opcode == REBASE_OPCODE_ADD_ADDR_ULEB)) { + dst->opcode = REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB; + dst->operand1 = src[1].operand1; + ++src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = REBASE_OPCODE_DONE; + + // optimize phase 3, compress packed runs of REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB with + // same addr delta into one REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB + dst = &mid[0]; + for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) { + uint64_t delta = src->operand1; + if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB) + && (src[1].opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB) + && (src[2].opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB) + && (src[1].operand1 == delta) + && (src[2].operand1 == delta) ) { + // found at least three in a row, this is worth compressing + dst->opcode = REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB; + dst->operand1 = 1; + dst->operand2 = delta; + ++src; + while ( (src->opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB) + && (src->operand1 == delta) ) { + dst->operand1++; + ++src; + } + --src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = REBASE_OPCODE_DONE; + + // optimize phase 4, use immediate encodings + for (rebase_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) { + if ( (p->opcode == REBASE_OPCODE_ADD_ADDR_ULEB) + && (p->operand1 < (15*sizeof(pint_t))) + && ((p->operand1 % sizeof(pint_t)) == 0) ) { + p->opcode = REBASE_OPCODE_ADD_ADDR_IMM_SCALED; + p->operand1 = p->operand1/sizeof(pint_t); + } + else if ( (p->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES) && (p->operand1 < 15) ) { + p->opcode = REBASE_OPCODE_DO_REBASE_IMM_TIMES; + } + } + + // convert to compressed encoding + const static bool log = false; + fEncodedData.reserve(info.size()*2); + bool done = false; + for (std::vector::iterator it = mid.begin(); !done && it != mid.end() ; ++it) { + switch ( it->opcode ) { + case REBASE_OPCODE_DONE: + if ( log ) fprintf(stderr, "REBASE_OPCODE_DONE()\n"); + done = true; + break; + case REBASE_OPCODE_SET_TYPE_IMM: + if ( log ) fprintf(stderr, "REBASE_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(REBASE_OPCODE_SET_TYPE_IMM | it->operand1); + break; + case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + if ( log ) fprintf(stderr, "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2); + fEncodedData.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + case REBASE_OPCODE_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "REBASE_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(REBASE_OPCODE_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: + if ( log ) fprintf(stderr, "REBASE_OPCODE_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t)); + fEncodedData.append_byte(REBASE_OPCODE_ADD_ADDR_IMM_SCALED | it->operand1 ); + break; + case REBASE_OPCODE_DO_REBASE_IMM_TIMES: + if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_IMM_TIMES(%lld)\n", it->operand1); + fEncodedData.append_byte(REBASE_OPCODE_DO_REBASE_IMM_TIMES | it->operand1); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: + if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ULEB_TIMES(%lld)\n", it->operand1); + fEncodedData.append_byte(REBASE_OPCODE_DO_REBASE_ULEB_TIMES); + fEncodedData.append_uleb128(it->operand1); + break; + case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: + if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2); + fEncodedData.append_byte(REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB); + fEncodedData.append_uleb128(it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + } + } + + + // align to pointer size + fEncodedData.pad_to_size(sizeof(pint_t)); + + if (log) fprintf(stderr, "total rebase info size = %ld\n", fEncodedData.size()); +} + + +struct binding_tmp +{ + binding_tmp(uint8_t op, uint64_t p1, uint64_t p2=0, const char* s=NULL) + : opcode(op), operand1(p1), operand2(p2), name(s) {} + uint8_t opcode; + uint64_t operand1; + uint64_t operand2; + const char* name; +}; + + + +template +void CompressedBindingInfoLinkEditAtom::encode() +{ + // sort by library, symbol, type, then address + const std::vector& segments = fWriter.fSegmentInfos; + std::vector& info = fWriter.fBindingInfo; + std::sort(info.begin(), info.end()); + + // convert to temp encoding that can be more easily optimized + std::vector mid; + const SegmentInfo* currentSegment = NULL; + unsigned int segIndex = 0; + int ordinal = 0x80000000; + const char* symbolName = NULL; + uint8_t type = 0; + uint64_t address = (uint64_t)(-1); + int64_t addend = 0; + for (std::vector::iterator it = info.begin(); it != info.end(); ++it) { + if ( ordinal != it->fLibraryOrdinal ) { + if ( it->fLibraryOrdinal <= 0 ) { + // special lookups are encoded as negative numbers in BindingInfo + mid.push_back(binding_tmp(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, it->fLibraryOrdinal)); + } + else { + mid.push_back(binding_tmp(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB, it->fLibraryOrdinal)); + } + ordinal = it->fLibraryOrdinal; + } + if ( symbolName != it->fSymbolName ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, it->fFlags, 0, it->fSymbolName)); + symbolName = it->fSymbolName; + } + if ( type != it->fType ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_TYPE_IMM, it->fType)); + type = it->fType; + } + if ( address != it->fAddress ) { + if ( (currentSegment == NULL) || (it->fAddress < currentSegment->fBaseAddress) + || ((currentSegment->fBaseAddress+currentSegment->fSize) <=it->fAddress) + || (it->fAddress < address) ) { + segIndex = 0; + for (std::vector::const_iterator segit = segments.begin(); segit != segments.end(); ++segit) { + if ( ((*segit)->fBaseAddress <= it->fAddress) && (it->fAddress < ((*segit)->fBaseAddress+(*segit)->fSize)) ) { + currentSegment = *segit; + break; + } + ++segIndex; + } + mid.push_back(binding_tmp(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, segIndex, it->fAddress - currentSegment->fBaseAddress)); + } + else { + mid.push_back(binding_tmp(BIND_OPCODE_ADD_ADDR_ULEB, it->fAddress-address)); + } + address = it->fAddress; + } + if ( addend != it->fAddend ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_ADDEND_SLEB, it->fAddend)); + addend = it->fAddend; + } + mid.push_back(binding_tmp(BIND_OPCODE_DO_BIND, 0)); + address += sizeof(pint_t); + } + mid.push_back(binding_tmp(BIND_OPCODE_DONE, 0)); + + + // optimize phase 1, combine bind/add pairs + binding_tmp* dst = &mid[0]; + for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) { + if ( (src->opcode == BIND_OPCODE_DO_BIND) + && (src[1].opcode == BIND_OPCODE_ADD_ADDR_ULEB) ) { + dst->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB; + dst->operand1 = src[1].operand1; + ++src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = BIND_OPCODE_DONE; + + // optimize phase 2, compress packed runs of BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB with + // same addr delta into one BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB + dst = &mid[0]; + for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) { + uint64_t delta = src->operand1; + if ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src[1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src[1].operand1 == delta) ) { + // found at least two in a row, this is worth compressing + dst->opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB; + dst->operand1 = 1; + dst->operand2 = delta; + ++src; + while ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src->operand1 == delta) ) { + dst->operand1++; + ++src; + } + --src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = BIND_OPCODE_DONE; + + // optimize phase 3, use immediate encodings + for (binding_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) { + if ( (p->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (p->operand1 < (15*sizeof(pint_t))) + && ((p->operand1 % sizeof(pint_t)) == 0) ) { + p->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED; + p->operand1 = p->operand1/sizeof(pint_t); + } + else if ( (p->opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB) && (p->operand1 <= 15) ) { + p->opcode = BIND_OPCODE_SET_DYLIB_ORDINAL_IMM; + } + } + dst->opcode = BIND_OPCODE_DONE; + + // convert to compressed encoding + const static bool log = false; + fEncodedData.reserve(info.size()*2); + bool done = false; + for (std::vector::iterator it = mid.begin(); !done && it != mid.end() ; ++it) { + switch ( it->opcode ) { + case BIND_OPCODE_DONE: + if ( log ) fprintf(stderr, "BIND_OPCODE_DONE()\n"); + done = true; + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | it->operand1); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (it->operand1 & BIND_IMMEDIATE_MASK)); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%0llX, %s)\n", it->operand1, it->name); + fEncodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | it->operand1); + fEncodedData.append_string(it->name); + break; + case BIND_OPCODE_SET_TYPE_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_TYPE_IMM | it->operand1); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_ADDEND_SLEB); + fEncodedData.append_sleb128(it->operand1); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2); + fEncodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_DO_BIND: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND()\n"); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t)); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED | it->operand1 ); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB); + fEncodedData.append_uleb128(it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + } + } + + // align to pointer size + fEncodedData.pad_to_size(sizeof(pint_t)); + + if (log) fprintf(stderr, "total binding info size = %ld\n", fEncodedData.size()); + +} + + + +struct WeakBindingSorter +{ + bool operator()(const BindingInfo& left, const BindingInfo& right) + { + // sort by symbol, type, address + if ( left.fSymbolName != right.fSymbolName ) + return ( strcmp(left.fSymbolName, right.fSymbolName) < 0 ); + if ( left.fType != right.fType ) + return (left.fType < right.fType); + return (left.fAddress < right.fAddress); + } +}; + + + +template +void CompressedWeakBindingInfoLinkEditAtom::encode() +{ + // add regular atoms that override a dylib's weak definitions + for(std::set::iterator it = fWriter.fRegularDefAtomsThatOverrideADylibsWeakDef->begin(); + it != fWriter.fRegularDefAtomsThatOverrideADylibsWeakDef->end(); ++it) { + if ( fWriter.shouldExport(**it) ) + fWriter.fWeakBindingInfo.push_back(BindingInfo(0, (*it)->getName(), true, 0, 0)); + } + + // add all exported weak definitions + for(std::vector::iterator it = fWriter.fAllAtoms->begin(); it != fWriter.fAllAtoms->end(); ++it) { + ObjectFile::Atom* atom = *it; + if ( (atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition) && fWriter.shouldExport(*atom) ) { + fWriter.fWeakBindingInfo.push_back(BindingInfo(0, atom->getName(), false, 0, 0)); + } + } + + // sort by symbol, type, address + const std::vector& segments = fWriter.fSegmentInfos; + std::vector& info = fWriter.fWeakBindingInfo; + if ( info.size() == 0 ) + return; + std::sort(info.begin(), info.end(), WeakBindingSorter()); + + // convert to temp encoding that can be more easily optimized + std::vector mid; + mid.reserve(info.size()); + const SegmentInfo* currentSegment = NULL; + unsigned int segIndex = 0; + const char* symbolName = NULL; + uint8_t type = 0; + uint64_t address = (uint64_t)(-1); + int64_t addend = 0; + for (std::vector::iterator it = info.begin(); it != info.end(); ++it) { + if ( symbolName != it->fSymbolName ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, it->fFlags, 0, it->fSymbolName)); + symbolName = it->fSymbolName; + } + if ( it->fType != 0 ) { + if ( type != it->fType ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_TYPE_IMM, it->fType)); + type = it->fType; + } + if ( address != it->fAddress ) { + // non weak symbols just have BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM + // weak symbols have SET_SEG, ADD_ADDR, SET_ADDED, DO_BIND + if ( (currentSegment == NULL) || (it->fAddress < currentSegment->fBaseAddress) + || ((currentSegment->fBaseAddress+currentSegment->fSize) <=it->fAddress) ) { + segIndex = 0; + for (std::vector::const_iterator segit = segments.begin(); segit != segments.end(); ++segit) { + if ( ((*segit)->fBaseAddress <= it->fAddress) && (it->fAddress < ((*segit)->fBaseAddress+(*segit)->fSize)) ) { + currentSegment = *segit; + break; + } + ++segIndex; + } + mid.push_back(binding_tmp(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, segIndex, it->fAddress - currentSegment->fBaseAddress)); + } + else { + mid.push_back(binding_tmp(BIND_OPCODE_ADD_ADDR_ULEB, it->fAddress-address)); + } + address = it->fAddress; + } + if ( addend != it->fAddend ) { + mid.push_back(binding_tmp(BIND_OPCODE_SET_ADDEND_SLEB, it->fAddend)); + addend = it->fAddend; + } + mid.push_back(binding_tmp(BIND_OPCODE_DO_BIND, 0)); + address += sizeof(pint_t); + } + } + mid.push_back(binding_tmp(BIND_OPCODE_DONE, 0)); + + + // optimize phase 1, combine bind/add pairs + binding_tmp* dst = &mid[0]; + for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) { + if ( (src->opcode == BIND_OPCODE_DO_BIND) + && (src[1].opcode == BIND_OPCODE_ADD_ADDR_ULEB) ) { + dst->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB; + dst->operand1 = src[1].operand1; + ++src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = BIND_OPCODE_DONE; + + // optimize phase 2, compress packed runs of BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB with + // same addr delta into one BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB + dst = &mid[0]; + for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) { + uint64_t delta = src->operand1; + if ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src[1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src[1].operand1 == delta) ) { + // found at least two in a row, this is worth compressing + dst->opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB; + dst->operand1 = 1; + dst->operand2 = delta; + ++src; + while ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (src->operand1 == delta) ) { + dst->operand1++; + ++src; + } + --src; + ++dst; + } + else { + *dst++ = *src; + } + } + dst->opcode = BIND_OPCODE_DONE; + + // optimize phase 3, use immediate encodings + for (binding_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) { + if ( (p->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) + && (p->operand1 < (15*sizeof(pint_t))) + && ((p->operand1 % sizeof(pint_t)) == 0) ) { + p->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED; + p->operand1 = p->operand1/sizeof(pint_t); + } + } + dst->opcode = BIND_OPCODE_DONE; + + + // convert to compressed encoding + const static bool log = false; + fEncodedData.reserve(info.size()*2); + bool done = false; + for (std::vector::iterator it = mid.begin(); !done && it != mid.end() ; ++it) { + switch ( it->opcode ) { + case BIND_OPCODE_DONE: + if ( log ) fprintf(stderr, "BIND_OPCODE_DONE()\n"); + fEncodedData.append_byte(BIND_OPCODE_DONE); + done = true; + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | it->operand1); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (it->operand1 & BIND_IMMEDIATE_MASK)); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%0llX, %s)\n", it->operand1, it->name); + fEncodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | it->operand1); + fEncodedData.append_string(it->name); + break; + case BIND_OPCODE_SET_TYPE_IMM: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_TYPE_IMM | it->operand1); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_SET_ADDEND_SLEB); + fEncodedData.append_sleb128(it->operand1); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2); + fEncodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_DO_BIND: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND()\n"); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%llX)\n", it->operand1); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB); + fEncodedData.append_uleb128(it->operand1); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t)); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED | it->operand1 ); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2); + fEncodedData.append_byte(BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB); + fEncodedData.append_uleb128(it->operand1); + fEncodedData.append_uleb128(it->operand2); + break; + } + } + + // align to pointer size + fEncodedData.pad_to_size(sizeof(pint_t)); + + if (log) fprintf(stderr, "total weak binding info size = %ld\n", fEncodedData.size()); + +} + +template +void CompressedLazyBindingInfoLinkEditAtom::encode() +{ + // stream all lazy bindings and record start offsets + const SegmentInfo* currentSegment = NULL; + uint8_t segIndex = 0; + const std::vector& segments = fWriter.fSegmentInfos; + std::vector*>& allLazys = fWriter.fAllSynthesizedLazyPointers; + for (typename std::vector*>::iterator it = allLazys.begin(); it != allLazys.end(); ++it) { + LazyPointerAtom* lazyPointerAtom = *it; + ObjectFile::Atom* lazyPointerTargetAtom = lazyPointerAtom->getTarget(); + + // skip lazy pointers that are bound non-lazily because they are coalesced + if ( ! fWriter.targetRequiresWeakBinding(*lazyPointerTargetAtom) ) { + // record start offset for use by stub helper + lazyPointerAtom->setLazyBindingInfoOffset(fEncodedData.size()); + + // write address to bind + pint_t address = lazyPointerAtom->getAddress(); + if ( (currentSegment == NULL) || (address < currentSegment->fBaseAddress) + || ((currentSegment->fBaseAddress+currentSegment->fSize) <= address) ) { + segIndex = 0; + for (std::vector::const_iterator segit = segments.begin(); segit != segments.end(); ++segit) { + if ( ((*segit)->fBaseAddress <= address) && (address < ((*segit)->fBaseAddress+(*segit)->fSize)) ) { + currentSegment = *segit; + break; + } + ++segIndex; + } + } + fEncodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | segIndex); + fEncodedData.append_uleb128(lazyPointerAtom->getAddress() - currentSegment->fBaseAddress); + + // write ordinal + int ordinal = fWriter.compressedOrdinalForImortedAtom(lazyPointerTargetAtom); + if ( ordinal <= 0 ) { + // special lookups are encoded as negative numbers in BindingInfo + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (ordinal & BIND_IMMEDIATE_MASK) ); + } + else if ( ordinal <= 15 ) { + // small ordinals are encoded in opcode + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal); + } + else { + fEncodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); + fEncodedData.append_uleb128(ordinal); + } + // write symbol name + bool weak_import = fWriter.fWeakImportMap[lazyPointerTargetAtom]; + if ( weak_import ) + fEncodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | BIND_SYMBOL_FLAGS_WEAK_IMPORT); + else + fEncodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM); + fEncodedData.append_string(lazyPointerTargetAtom->getName()); + // write do bind + fEncodedData.append_byte(BIND_OPCODE_DO_BIND); + fEncodedData.append_byte(BIND_OPCODE_DONE); + } + } + // align to pointer size + fEncodedData.pad_to_size(sizeof(pint_t)); + + //fprintf(stderr, "lazy binding info size = %ld, for %ld entries\n", fEncodedData.size(), allLazys.size()); +} + +struct TrieEntriesSorter +{ + TrieEntriesSorter(Options& o) : fOptions(o) {} + + bool operator()(const mach_o::trie::Entry& left, const mach_o::trie::Entry& right) + { + unsigned int leftOrder; + unsigned int rightOrder; + fOptions.exportedSymbolOrder(left.name, &leftOrder); + fOptions.exportedSymbolOrder(right.name, &rightOrder); + if ( leftOrder != rightOrder ) + return (leftOrder < rightOrder); + else + return (left.address < right.address); + } +private: + Options& fOptions; +}; + + +template +void CompressedExportInfoLinkEditAtom::encode() +{ + // make vector of mach_o::trie::Entry for all exported symbols + std::vector& exports = fWriter.fExportedAtoms; + uint64_t imageBaseAddress = fWriter.fMachHeaderAtom->getAddress(); + std::vector entries; + entries.reserve(exports.size()); + for (std::vector::iterator it = exports.begin(); it != exports.end(); ++it) { + ObjectFile::Atom* atom = *it; + uint64_t flags = 0; + if ( atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) + flags |= EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; + uint64_t address = atom->getAddress() - imageBaseAddress; + if ( atom->isThumb() ) + address |= 1; + mach_o::trie::Entry entry; + entry.name = atom->getName(); + entry.flags = flags; + entry.address = address; + entries.push_back(entry); + } + + // sort vector by -exported_symbols_order, and any others by address + std::sort(entries.begin(), entries.end(), TrieEntriesSorter(fWriter.fOptions)); + + // create trie + mach_o::trie::makeTrie(entries, fEncodedData.bytes()); + + // align to pointer size + fEncodedData.pad_to_size(sizeof(pint_t)); +} + + + + + }; // namespace executable }; // namespace mach_o diff --git a/src/ObjectFile.h b/src/ld/ObjectFile.h old mode 100755 new mode 100644 similarity index 85% rename from src/ObjectFile.h rename to src/ld/ObjectFile.h index 37a2892..8b9a2d3 --- a/src/ObjectFile.h +++ b/src/ld/ObjectFile.h @@ -29,6 +29,7 @@ #include #include #include +#include @@ -61,14 +62,21 @@ class ReaderOptions { public: ReaderOptions() : fFullyLoadArchives(false), fLoadAllObjcObjectsFromArchives(false), fFlatNamespace(false), - fLinkingMainExecutable(false), fSlowx86Stubs(false), - fForFinalLinkedImage(false), fForStatic(false), fForDyld(false), fMakeTentativeDefinitionsReal(false), + fLinkingMainExecutable(false), + fForFinalLinkedImage(false), fNoEHLabels(false), fForStatic(false), fForDyld(false), fMakeTentativeDefinitionsReal(false), fWhyLoad(false), fRootSafe(false), fSetuidSafe(false),fDebugInfoStripping(kDebugInfoFull), - fImplicitlyLinkPublicDylibs(true), fLogObjectFiles(false), fLogAllFiles(false), + fImplicitlyLinkPublicDylibs(true), + fAddCompactUnwindEncoding(true), + fWarnCompactUnwind(false), + fRemoveDwarfUnwindIfCompactExists(false), + fMakeCompressedDyldInfo(false), + fAutoOrderInitializers(true), + fLogObjectFiles(false), fLogAllFiles(false), fTraceDylibs(false), fTraceIndirectDylibs(false), fTraceArchives(false), - fTraceOutputFile(NULL), fVersionMin(kMinUnset) {} + fTraceOutputFile(NULL), fMacVersionMin(kMinMacVersionUnset), fIPhoneVersionMin(kMinIPhoneVersionUnset) {} enum DebugInfoStripping { kDebugInfoNone, kDebugInfoMinimal, kDebugInfoFull }; - enum VersionMin { kMinUnset, k10_1, k10_2, k10_3, k10_4, k10_5, k10_6 }; + enum MacVersionMin { kMinMacVersionUnset, k10_1, k10_2, k10_3, k10_4, k10_5, k10_6 }; + enum IPhoneVersionMin { kMinIPhoneVersionUnset, k2_0, k2_1, k2_2, k3_0 }; struct AliasPair { const char* realName; @@ -79,8 +87,8 @@ public: bool fLoadAllObjcObjectsFromArchives; bool fFlatNamespace; bool fLinkingMainExecutable; - bool fSlowx86Stubs; bool fForFinalLinkedImage; + bool fNoEHLabels; bool fForStatic; bool fForDyld; bool fMakeTentativeDefinitionsReal; @@ -89,13 +97,19 @@ public: bool fSetuidSafe; DebugInfoStripping fDebugInfoStripping; bool fImplicitlyLinkPublicDylibs; + bool fAddCompactUnwindEncoding; + bool fWarnCompactUnwind; + bool fRemoveDwarfUnwindIfCompactExists; + bool fMakeCompressedDyldInfo; + bool fAutoOrderInitializers; bool fLogObjectFiles; bool fLogAllFiles; bool fTraceDylibs; bool fTraceIndirectDylibs; bool fTraceArchives; const char* fTraceOutputFile; - VersionMin fVersionMin; + MacVersionMin fMacVersionMin; + IPhoneVersionMin fIPhoneVersionMin; std::vector fAliases; }; @@ -138,11 +152,15 @@ public: // For relocatable object files only virtual bool canScatterAtoms() { return true; } - virtual void optimize(std::vector&, std::vector&, - std::vector&, uint32_t, ObjectFile::Reader* writer, + virtual bool optimize(const std::vector&, std::vector&, + std::vector&, const std::set&, + std::vector&, + uint32_t, ObjectFile::Reader* writer, + ObjectFile::Atom* entryPointAtom, + const std::vector& llvmOptions, bool allGlobalsAReDeadStripRoots, int okind, bool verbose, bool saveTemps, const char* outputFilePath, - bool pie, bool allowTextRelocs) { } + bool pie, bool allowTextRelocs) { return false; } virtual bool hasLongBranchStubs() { return false; } // For Dynamic Libraries only @@ -158,6 +176,7 @@ public: virtual const char* parentUmbrella() { return NULL; } virtual std::vector* getAllowableClients() { return NULL; } virtual bool hasWeakExternals() { return false; } + virtual bool deadStrippable() { return false; } virtual bool isLazyLoadedDylib() { return false; } protected: @@ -208,6 +227,16 @@ struct Alignment uint16_t modulus; }; +struct UnwindInfo +{ + uint32_t startOffset; + uint32_t unwindInfo; + + typedef UnwindInfo* iterator; + +}; + + // // An atom is the fundamental unit of linking. A C function or global variable is an atom. // An atom has content and some attributes. The content of a function atom is the instructions @@ -251,6 +280,7 @@ class Atom public: enum Scope { scopeTranslationUnit, scopeLinkageUnit, scopeGlobal }; enum DefinitionKind { kRegularDefinition, kWeakDefinition, kTentativeDefinition, kExternalDefinition, kExternalWeakDefinition, kAbsoluteSymbol }; + enum ContentType { kUnclassifiedType, kCStringType, kCFIType, kLSDAType }; enum SymbolTableInclusion { kSymbolTableNotIn, kSymbolTableIn, kSymbolTableInAndNeverStrip, kSymbolTableInAsAbsolute }; virtual Reader* getFile() const = 0; @@ -259,6 +289,7 @@ public: virtual const char* getDisplayName() const = 0; virtual Scope getScope() const = 0; virtual DefinitionKind getDefinitionKind() const = 0; + virtual ContentType getContentType() const { return kUnclassifiedType; } virtual SymbolTableInclusion getSymbolTableInclusion() const = 0; virtual bool dontDeadStrip() const = 0; virtual bool isZeroFill() const = 0; @@ -274,7 +305,11 @@ public: virtual Alignment getAlignment() const = 0; virtual void copyRawContent(uint8_t buffer[]) const = 0; virtual void setScope(Scope) = 0; - + virtual UnwindInfo::iterator beginUnwind() { return NULL; } + virtual UnwindInfo::iterator endUnwind() { return NULL; } + virtual Reference* getLSDA() { return NULL; } + virtual Reference* getFDE() { return NULL; } + virtual Atom* getPersonalityPointer() { return NULL; } uint64_t getSectionOffset() const { return fSectionOffset; } uint64_t getAddress() const { return fSection->getBaseAddress() + fSectionOffset; } @@ -333,6 +368,7 @@ public: virtual void setTarget(Atom&, uint64_t offset) = 0; virtual void setFromTarget(Atom&) = 0; virtual const char* getDescription() const = 0; + virtual bool isBranch() const { return false; } protected: Reference() {} diff --git a/src/OpaqueSection.hpp b/src/ld/OpaqueSection.hpp old mode 100755 new mode 100644 similarity index 100% rename from src/OpaqueSection.hpp rename to src/ld/OpaqueSection.hpp diff --git a/src/Options.cpp b/src/ld/Options.cpp old mode 100755 new mode 100644 similarity index 83% rename from src/Options.cpp rename to src/ld/Options.cpp index d0a2d15..03969cd --- a/src/Options.cpp +++ b/src/ld/Options.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include @@ -36,6 +37,10 @@ extern void printLTOVersion(Options &opts); +// magic to place command line in crash reports +extern "C" char* __crashreporter_info__; +static char crashreporterBuffer[1000]; +char* __crashreporter_info__ = crashreporterBuffer; static bool sEmitWarnings = true; static const char* sWarningsSideFilePath = NULL; @@ -50,11 +55,11 @@ void warning(const char* format, ...) sWarningsSideFile = fopen(sWarningsSideFilePath, "a"); } va_start(list, format); - fprintf(stderr, "ld warning: "); + fprintf(stderr, "ld: warning: "); vfprintf(stderr, format, list); fprintf(stderr, "\n"); if ( sWarningsSideFile != NULL ) { - fprintf(sWarningsSideFile, "ld warning: "); + fprintf(sWarningsSideFile, "ld: warning: "); vfprintf(sWarningsSideFile, format, list); fprintf(sWarningsSideFile, "\n"); fflush(sWarningsSideFile); @@ -78,7 +83,7 @@ void throwf(const char* format, ...) Options::Options(int argc, const char* argv[]) : fOutputFile("a.out"), fArchitecture(0), fSubArchitecture(0), fOutputKind(kDynamicExecutable), fHasPreferredSubType(false), fPrebind(false), fBindAtLoad(false), fKeepPrivateExterns(false), - fNeedsModuleTable(false), fIgnoreOtherArchFiles(false), fForceSubtypeAll(false), + fNeedsModuleTable(false), fIgnoreOtherArchFiles(false), fErrorOnOtherArchFiles(false), fForceSubtypeAll(false), fInterposeMode(kInterposeNone), fDeadStrip(kDeadStripOff), fNameSpace(kTwoLevelNameSpace), fDylibCompatVersion(0), fDylibCurrentVersion(0), fDylibInstallName(NULL), fFinalName(NULL), fEntryName("start"), fBaseAddress(0), fBaseWritableAddress(0), fSplitSegs(false), @@ -88,14 +93,16 @@ Options::Options(int argc, const char* argv[]) fClientName(NULL), fUmbrellaName(NULL), fInitFunctionName(NULL), fDotOutputFile(NULL), fExecutablePath(NULL), fBundleLoader(NULL), fDtraceScriptName(NULL), fSegAddrTablePath(NULL), fMapPath(NULL), - fZeroPageSize(ULLONG_MAX), fStackSize(0), fStackAddr(0), fExecutableStack(false), fMinimumHeaderPad(32), + fZeroPageSize(ULLONG_MAX), fStackSize(0), fStackAddr(0), fExecutableStack(false), + fMinimumHeaderPad(32), fSegmentAlignment(4096), fCommonsMode(kCommonsIgnoreDylibs), fUUIDMode(kUUIDContent), fLocalSymbolHandling(kLocalSymbolsAll), fWarnCommons(false), fVerbose(false), fKeepRelocations(false), fWarnStabs(false), fTraceDylibSearching(false), fPause(false), fStatistics(false), fPrintOptions(false), fSharedRegionEligible(false), fPrintOrderFileStatistics(false), fReadOnlyx86Stubs(false), fPositionIndependentExecutable(false), fMaxMinimumHeaderPad(false), fDeadStripDylibs(false), fAllowTextRelocs(false), fWarnTextRelocs(false), - fUsingLazyDylibLinking(false), fEncryptable(true), fSaveTempFiles(false) + fUsingLazyDylibLinking(false), fEncryptable(true), fOrderData(true), fMarkDeadStrippableDylib(false), + fMakeClassicDyldInfo(true), fMakeCompressedDyldInfo(true), fAllowCpuSubtypeMismatches(false), fSaveTempFiles(false) { this->checkForClassic(argc, argv); this->parsePreCommandLineEnvironmentSettings(); @@ -228,11 +235,6 @@ Options::UndefinedTreatment Options::undefinedTreatment() return fUndefinedTreatment; } -ObjectFile::ReaderOptions::VersionMin Options::macosxVersionMin() -{ - return fReaderOptions.fVersionMin; -} - Options::WeakReferenceMismatchTreatment Options::weakReferenceMismatchTreatment() { return fWeakReferenceMismatchTreatment; @@ -326,12 +328,14 @@ bool Options::allGlobalsAreDeadStripRoots() switch ( fOutputKind ) { case Options::kDynamicExecutable: case Options::kStaticExecutable: + case Options::kPreload: // by default unused globals in a main executable are stripped return false; case Options::kDynamicLibrary: case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kKextBundle: return true; } return false; @@ -382,6 +386,96 @@ Options::DeadStripMode Options::deadStrip() return fDeadStrip; } +bool Options::hasExportedSymbolOrder() +{ + return (fExportSymbolsOrder.size() > 0); +} + +bool Options::exportedSymbolOrder(const char* sym, unsigned int* order) +{ + NameToOrder::iterator pos = fExportSymbolsOrder.find(sym); + if ( pos != fExportSymbolsOrder.end() ) { + *order = pos->second; + return true; + } + else { + *order = 0xFFFFFFFF; + return false; + } +} + +void Options::loadSymbolOrderFile(const char* fileOfExports, NameToOrder& orderMapping) +{ + // read in whole file + int fd = ::open(fileOfExports, O_RDONLY, 0); + if ( fd == -1 ) + throwf("can't open -exported_symbols_order file: %s", fileOfExports); + struct stat stat_buf; + ::fstat(fd, &stat_buf); + char* p = (char*)malloc(stat_buf.st_size); + if ( p == NULL ) + throwf("can't process -exported_symbols_order file: %s", fileOfExports); + + if ( read(fd, p, stat_buf.st_size) != stat_buf.st_size ) + throwf("can't read -exported_symbols_order file: %s", fileOfExports); + + ::close(fd); + + // parse into symbols and add to hash_set + unsigned int count = 0; + char * const end = &p[stat_buf.st_size]; + enum { lineStart, inSymbol, inComment } state = lineStart; + char* symbolStart = NULL; + for (char* s = p; s < end; ++s ) { + switch ( state ) { + case lineStart: + if ( *s =='#' ) { + state = inComment; + } + else if ( !isspace(*s) ) { + state = inSymbol; + symbolStart = s; + } + break; + case inSymbol: + if ( (*s == '\n') || (*s == '\r') ) { + *s = '\0'; + // removing any trailing spaces + char* last = s-1; + while ( isspace(*last) ) { + *last = '\0'; + --last; + } + orderMapping[symbolStart] = ++count; + symbolStart = NULL; + state = lineStart; + } + break; + case inComment: + if ( (*s == '\n') || (*s == '\r') ) + state = lineStart; + break; + } + } + if ( state == inSymbol ) { + warning("missing line-end at end of file \"%s\"", fileOfExports); + int len = end-symbolStart+1; + char* temp = new char[len]; + strlcpy(temp, symbolStart, len); + + // remove any trailing spaces + char* last = &temp[len-2]; + while ( isspace(*last) ) { + *last = '\0'; + --last; + } + orderMapping[temp] = ++count; + } + + // Note: we do not free() the malloc buffer, because the strings are used by the export-set hash table +} + + bool Options::shouldExport(const char* symbolName) { switch (fExportMode) { @@ -803,14 +897,18 @@ void Options::loadFileList(const char* fileOfPaths) const char* comma = strrchr(fileOfPaths, ','); const char* prefix = NULL; if ( comma != NULL ) { - prefix = comma+1; - int realFileOfPathsLen = comma-fileOfPaths; - char realFileOfPaths[realFileOfPathsLen+1]; - strncpy(realFileOfPaths,fileOfPaths, realFileOfPathsLen); - realFileOfPaths[realFileOfPathsLen] = '\0'; - file = fopen(realFileOfPaths, "r"); - if ( file == NULL ) - throwf("-filelist file not found: %s\n", realFileOfPaths); + // -filelist fails with comma in path + file = fopen(fileOfPaths, "r"); + if ( file == NULL ) { + prefix = comma+1; + int realFileOfPathsLen = comma-fileOfPaths; + char realFileOfPaths[realFileOfPathsLen+1]; + strncpy(realFileOfPaths,fileOfPaths, realFileOfPathsLen); + realFileOfPaths[realFileOfPathsLen] = '\0'; + file = fopen(realFileOfPaths, "r"); + if ( file == NULL ) + throwf("-filelist file not found: %s\n", realFileOfPaths); + } } else { file = fopen(fileOfPaths, "r"); @@ -1131,25 +1229,25 @@ void Options::setMacOSXVersionMin(const char* version) switch ( num ) { case 0: case 1: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_1; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_1; break; case 2: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_2; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_2; break; case 3: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_3; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_3; break; case 4: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_4; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_4; break; case 5: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_5; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_5; break; case 6: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_6; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_6; break; default: - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_6; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_6; break; } } @@ -1163,21 +1261,54 @@ void Options::setIPhoneVersionMin(const char* version) if ( version == NULL ) throw "-iphoneos_version_min argument missing"; - if ( ((strncmp(version, "1.", 2) == 0) || (strncmp(version, "2.", 2) == 0)) && isdigit(version[2]) ) { + if ( strncmp(version, "1.", 2) == 0 ) { + warning("pre-2.0 iPhone OS version not supported"); + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_0; + } + else if ( strncmp(version, "2.", 2) == 0 ) { int num = version[2] - '0'; switch ( num ) { + case 0: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_0; + break; + case 1: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_1; + break; case 2: - // TODO: store deployment version + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_2; + break; + default: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_2; + break; + } + } + else if ( strncmp(version, "3.", 2) == 0 ) { + int num = version[2] - '0'; + switch ( num ) { + case 0: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k3_0; break; default: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k3_0; break; } } else { - warning("unknown option to -iphoneos_version_min, not 1.x or 2.x"); + warning("unknown option to -iphoneos_version_min, not 2.x or 3.x"); + } +} + +bool Options::minOS(ObjectFile::ReaderOptions::MacVersionMin requiredMacMin, ObjectFile::ReaderOptions::IPhoneVersionMin requirediPhoneOSMin) +{ + if ( fReaderOptions.fMacVersionMin != ObjectFile::ReaderOptions::kMinMacVersionUnset ) { + return ( fReaderOptions.fMacVersionMin >= requiredMacMin ); + } + else { + return ( fReaderOptions.fIPhoneVersionMin >= requirediPhoneOSMin); } } + void Options::setWeakReferenceMismatchTreatment(const char* treatment) { if ( treatment == NULL ) @@ -1361,6 +1492,9 @@ static const char* cstringSymbolName(const char* orderFileString) void Options::parseOrderFile(const char* path, bool cstring) { + // order files override auto-ordering + fReaderOptions.fAutoOrderInitializers = false; + // read in whole file int fd = ::open(path, O_RDONLY, 0); if ( fd == -1 ) @@ -1608,9 +1742,10 @@ void Options::parse(int argc, const char* argv[]) // default } else if ( strcmp(arg, "-static") == 0 ) { - if ( fOutputKind != kObjectFile ) - fOutputKind = kStaticExecutable; fReaderOptions.fForStatic = true; + if ( fOutputKind != kObjectFile ) { + fOutputKind = kStaticExecutable; + } } else if ( strcmp(arg, "-dylib") == 0 ) { fOutputKind = kDynamicLibrary; @@ -1625,9 +1760,15 @@ void Options::parse(int argc, const char* argv[]) if ( fOutputKind != kStaticExecutable ) fOutputKind = kDynamicExecutable; } + else if ( strcmp(arg, "-preload") == 0 ) { + fOutputKind = kPreload; + } else if ( strcmp(arg, "-r") == 0 ) { fOutputKind = kObjectFile; } + else if ( strcmp(arg, "-kext") == 0 ) { + fOutputKind = kKextBundle; + } else if ( strcmp(arg, "-o") == 0 ) { fOutputFile = argv[++i]; } @@ -1675,6 +1816,12 @@ void Options::parse(int argc, const char* argv[]) else if ( strcmp(arg, "-ObjC") == 0 ) { fReaderOptions.fLoadAllObjcObjectsFromArchives = true; } + // Similar to -all_load, but for the following archive only. + else if ( strcmp(arg, "-force_load") == 0 ) { + FileInfo info = findFile(argv[++i]); + info.options.fForceLoad = true; + addLibrary(info); + } // Library versioning. else if ( (strcmp(arg, "-dylib_compatibility_version") == 0) || (strcmp(arg, "-compatibility_version") == 0)) { @@ -1724,9 +1871,9 @@ void Options::parse(int argc, const char* argv[]) if ( address == NULL ) throwf("%s missing

", arg); fBaseAddress = parseAddress(address); - uint64_t temp = (fBaseAddress+4095) & (-4096); // page align + uint64_t temp = ((fBaseAddress+fSegmentAlignment-1) & (-fSegmentAlignment)); if ( fBaseAddress != temp ) { - warning("-seg1addr not page aligned, rounding up"); + warning("-seg1addr not %lld byte aligned, rounding up", fSegmentAlignment); fBaseAddress = temp; } } @@ -1925,8 +2072,16 @@ void Options::parse(int argc, const char* argv[]) } // Aligns all segments to the power of 2 boundary specified. else if ( strcmp(arg, "-segalign") == 0 ) { - warnObsolete(arg); - ++i; + const char* size = argv[++i]; + if ( size == NULL ) + throw "-segalign missing "; + fSegmentAlignment = parseAddress(size); + uint8_t alignment = (uint8_t)__builtin_ctz(fSegmentAlignment); + uint32_t p2aligned = (1 << alignment); + if ( p2aligned != fSegmentAlignment ) { + warning("alignment for -segalign %s is not a power of two, using 0x%X", size, p2aligned); + fSegmentAlignment = p2aligned; + } } // Puts a specified segment at a particular address that must // be a multiple of the segment alignment. @@ -2029,7 +2184,7 @@ void Options::parse(int argc, const char* argv[]) else if ( strcmp(arg, "-macosx_version_min") == 0 ) { setMacOSXVersionMin(argv[++i]); } - else if ( (strcmp(arg, "-aspen_version_min") == 0) || (strcmp(arg, "-iphone_version_min") == 0) || (strcmp(arg, "-iphoneos_version_min") == 0) ) { + else if ( strcmp(arg, "-iphoneos_version_min") == 0 ) { setIPhoneVersionMin(argv[++i]); } else if ( strcmp(arg, "-multiply_defined") == 0 ) { @@ -2117,7 +2272,7 @@ void Options::parse(int argc, const char* argv[]) // previously handled by buildSearchPaths() } else if ( strcmp(arg, "-arch_errors_fatal") == 0 ) { - // FIX FIX + fErrorOnOtherArchFiles = true; } else if ( strcmp(arg, "-M") == 0 ) { // FIX FIX @@ -2274,7 +2429,7 @@ void Options::parse(int argc, const char* argv[]) fReadOnlyx86Stubs = true; } else if ( strcmp(arg, "-slow_stubs") == 0 ) { - fReaderOptions.fSlowx86Stubs = true; + warnObsolete(arg); } else if ( strcmp(arg, "-map") == 0 ) { fMapPath = argv[++i]; @@ -2311,6 +2466,50 @@ void Options::parse(int argc, const char* argv[]) else if ( strcmp(arg, "-no_encryption") == 0 ) { fEncryptable = false; } + else if ( strcmp(arg, "-no_compact_unwind") == 0 ) { + fReaderOptions.fAddCompactUnwindEncoding = false; + } + else if ( strcmp(arg, "-mllvm") == 0 ) { + const char* opts = argv[++i]; + if ( opts == NULL ) + throw "missing argument to -mllvm"; + fLLVMOptions.push_back(opts); + } + else if ( strcmp(arg, "-no_order_inits") == 0 ) { + fReaderOptions.fAutoOrderInitializers = false; + } + else if ( strcmp(arg, "-no_order_data") == 0 ) { + fOrderData = false; + } + else if ( strcmp(arg, "-seg_page_size") == 0 ) { + SegmentSize seg; + seg.name = argv[++i]; + if ( (seg.name == NULL) || (argv[i+1] == NULL) ) + throw "-seg_page_size missing segName Adddress"; + seg.size = parseAddress(argv[++i]); + uint64_t temp = seg.size & (-4096); // page align + if ( (seg.size != temp) ) + warning("-seg_page_size %s not 4K aligned, rounding down", seg.name); + fCustomSegmentSizes.push_back(seg); + } + else if ( strcmp(arg, "-mark_dead_strippable_dylib") == 0 ) { + fMarkDeadStrippableDylib = true; + } + else if ( strcmp(arg, "-exported_symbols_order") == 0 ) { + loadSymbolOrderFile(argv[++i], fExportSymbolsOrder); + } + else if ( strcmp(arg, "-no_compact_linkedit") == 0 ) { + fMakeCompressedDyldInfo = false; + } + else if ( strcmp(arg, "-no_eh_labels") == 0 ) { + fReaderOptions.fNoEHLabels = true; + } + else if ( strcmp(arg, "-warn_compact_unwind") == 0 ) { + fReaderOptions.fWarnCompactUnwind = true; + } + else if ( strcmp(arg, "-allow_sub_type_mismatches") == 0 ) { + fAllowCpuSubtypeMismatches = true; + } else { throwf("unknown option: %s", arg); } @@ -2382,14 +2581,15 @@ void Options::buildSearchPaths(int argc, const char* argv[]) sEmitWarnings = false; } } + int standardLibraryPathsStartIndex = libraryPaths.size(); + int standardFrameworkPathsStartIndex = frameworkPaths.size(); if ( addStandardLibraryDirectories ) { libraryPaths.push_back("/usr/lib"); libraryPaths.push_back("/usr/local/lib"); frameworkPaths.push_back("/Library/Frameworks/"); frameworkPaths.push_back("/System/Library/Frameworks/"); - // remove /Network from default search path - //frameworkPaths.push_back("/Network/Library/Frameworks/"); + // remove /Network/Library/Frameworks from default search path } // Support for configure based hacks @@ -2402,7 +2602,8 @@ void Options::buildSearchPaths(int argc, const char* argv[]) // now merge sdk and library paths to make real search paths fLibrarySearchPaths.reserve(libraryPaths.size()*(fSDKPaths.size()+1)); - for (std::vector::iterator it = libraryPaths.begin(); it != libraryPaths.end(); it++) { + int libIndex = 0; + for (std::vector::iterator it = libraryPaths.begin(); it != libraryPaths.end(); ++it, ++libIndex) { const char* libDir = *it; bool sdkOverride = false; if ( libDir[0] == '/' ) { @@ -2413,7 +2614,6 @@ void Options::buildSearchPaths(int argc, const char* argv[]) } const int libDirLen = strlen(libDir); for (std::vector::iterator sdkit = fSDKPaths.begin(); sdkit != fSDKPaths.end(); sdkit++) { - // ??? Should be using string here. const char* sdkDir = *sdkit; const int sdkDirLen = strlen(sdkDir); char newPath[libDirLen + sdkDirLen+4]; @@ -2428,13 +2628,21 @@ void Options::buildSearchPaths(int argc, const char* argv[]) } } } - if ( !sdkOverride ) - fLibrarySearchPaths.push_back(libDir); + if ( !sdkOverride ) { + if ( (libIndex >= standardLibraryPathsStartIndex) && (fSDKPaths.size() == 1) ) { + // -syslibroot should skip standard search paths not in the SDK + // if one SDK is specified and a standard library path is not in the SDK, don't use it + } + else { + fLibrarySearchPaths.push_back(libDir); + } + } } // now merge sdk and framework paths to make real search paths fFrameworkSearchPaths.reserve(frameworkPaths.size()*(fSDKPaths.size()+1)); - for (std::vector::iterator it = frameworkPaths.begin(); it != frameworkPaths.end(); it++) { + int frameIndex = 0; + for (std::vector::iterator it = frameworkPaths.begin(); it != frameworkPaths.end(); ++it, ++frameIndex) { const char* frameworkDir = *it; bool sdkOverride = false; if ( frameworkDir[0] == '/' ) { @@ -2445,7 +2653,6 @@ void Options::buildSearchPaths(int argc, const char* argv[]) } const int frameworkDirLen = strlen(frameworkDir); for (std::vector::iterator sdkit = fSDKPaths.begin(); sdkit != fSDKPaths.end(); sdkit++) { - // ??? Should be using string here const char* sdkDir = *sdkit; const int sdkDirLen = strlen(sdkDir); char newPath[frameworkDirLen + sdkDirLen+4]; @@ -2460,8 +2667,15 @@ void Options::buildSearchPaths(int argc, const char* argv[]) } } } - if ( !sdkOverride ) - fFrameworkSearchPaths.push_back(frameworkDir); + if ( !sdkOverride ) { + if ( (frameIndex >= standardFrameworkPathsStartIndex) && (fSDKPaths.size() == 1) ) { + // -syslibroot should skip standard search paths not in the SDK + // if one SDK is specified and a standard library path is not in the SDK, don't use it + } + else { + fFrameworkSearchPaths.push_back(frameworkDir); + } + } } if ( fVerbose ) { @@ -2509,7 +2723,16 @@ void Options::parsePreCommandLineEnvironmentSettings() if (getenv("LD_NO_ENCRYPT") != NULL) fEncryptable = false; - + + if (getenv("LD_ALLOW_CPU_SUBTYPE_MISMATCHES") != NULL) + fAllowCpuSubtypeMismatches = true; + + // for now disable compressed linkedit functionality + if ( getenv("LD_NO_COMPACT_LINKEDIT") != NULL ) { + fMakeCompressedDyldInfo = false; + fMakeClassicDyldInfo = true; + } + sWarningsSideFilePath = getenv("LD_WARN_FILE"); } @@ -2540,9 +2763,11 @@ void Options::parsePostCommandLineEnvironmentSettings() case Options::kDynamicBundle: fDeadStrip = kDeadStripOn; break; + case Options::kPreload: case Options::kObjectFile: case Options::kDyld: case Options::kStaticExecutable: + case Options::kKextBundle: break; } } @@ -2563,65 +2788,101 @@ void Options::reconfigureDefaults() case Options::kDyld: fReaderOptions.fForDyld = true; fReaderOptions.fForFinalLinkedImage = true; + fReaderOptions.fNoEHLabels = true; break; case Options::kDynamicLibrary: case Options::kDynamicBundle: + case Options::kKextBundle: fReaderOptions.fForFinalLinkedImage = true; + fReaderOptions.fNoEHLabels = true; break; case Options::kDynamicExecutable: case Options::kStaticExecutable: + case Options::kPreload: fReaderOptions.fLinkingMainExecutable = true; fReaderOptions.fForFinalLinkedImage = true; + fReaderOptions.fNoEHLabels = true; break; } // set default min OS version - if ( fReaderOptions.fVersionMin == ObjectFile::ReaderOptions::kMinUnset ) { - // if -macosx_version_min not used, try environment variable - const char* envVers = getenv("MACOSX_DEPLOYMENT_TARGET"); - if ( envVers != NULL ) - setMacOSXVersionMin(envVers); - // if -macosx_version_min and environment variable not used assume current OS version - if ( fReaderOptions.fVersionMin == ObjectFile::ReaderOptions::kMinUnset ) - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_5; // FIX FIX, this really should be a check of the OS version the linker is running on + if ( (fReaderOptions.fMacVersionMin == ObjectFile::ReaderOptions::kMinMacVersionUnset) + && (fReaderOptions.fIPhoneVersionMin == ObjectFile::ReaderOptions::kMinIPhoneVersionUnset) ) { + // if neither -macosx_version_min nor -iphoneos_version_min used, try environment variables + const char* macVers = getenv("MACOSX_DEPLOYMENT_TARGET"); + const char* iPhoneVers = getenv("IPHONEOS_DEPLOYMENT_TARGET"); + if ( macVers != NULL ) + setMacOSXVersionMin(macVers); + else if ( iPhoneVers != NULL ) + setIPhoneVersionMin(iPhoneVers); + else { + // if still nothing, set default based on architecture + switch ( fArchitecture ) { + case CPU_TYPE_I386: + case CPU_TYPE_X86_64: + case CPU_TYPE_POWERPC: + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_6; // FIX FIX, this really should be a check of the OS version the linker is running o + break; + case CPU_TYPE_ARM: + fReaderOptions.fIPhoneVersionMin = ObjectFile::ReaderOptions::k2_0; + break; + } + } } + // adjust min based on architecture switch ( fArchitecture ) { case CPU_TYPE_I386: - if ( fReaderOptions.fVersionMin < ObjectFile::ReaderOptions::k10_4 ) { + if ( fReaderOptions.fMacVersionMin < ObjectFile::ReaderOptions::k10_4 ) { //warning("-macosx_version_min should be 10.4 or later for i386"); - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_4; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_4; } break; case CPU_TYPE_POWERPC64: - if ( fReaderOptions.fVersionMin < ObjectFile::ReaderOptions::k10_4 ) { + if ( fReaderOptions.fMacVersionMin < ObjectFile::ReaderOptions::k10_4 ) { //warning("-macosx_version_min should be 10.4 or later for ppc64"); - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_4; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_4; } break; case CPU_TYPE_X86_64: - if ( fReaderOptions.fVersionMin < ObjectFile::ReaderOptions::k10_4 ) { + if ( fReaderOptions.fMacVersionMin < ObjectFile::ReaderOptions::k10_4 ) { //warning("-macosx_version_min should be 10.4 or later for x86_64"); - fReaderOptions.fVersionMin = ObjectFile::ReaderOptions::k10_4; + fReaderOptions.fMacVersionMin = ObjectFile::ReaderOptions::k10_4; } break; } + + // adjust kext type based on architecture + if ( fOutputKind == kKextBundle ) { + switch ( fArchitecture ) { + case CPU_TYPE_X86_64: + // x86_64 uses new MH_KEXT_BUNDLE type + fMakeClassicDyldInfo = true; + fMakeCompressedDyldInfo = false; + fAllowTextRelocs = true; + fUndefinedTreatment = kUndefinedDynamicLookup; + break; + case CPU_TYPE_POWERPC: + case CPU_TYPE_I386: + case CPU_TYPE_ARM: + // use .o files + fOutputKind = kObjectFile; + break; + } + } - // disable implicit dylibs when targetting 10.3 + // disable implicit dylibs when targeting 10.3 // add option to disable implicit load commands for indirectly used public dylibs - if ( fReaderOptions.fVersionMin <= ObjectFile::ReaderOptions::k10_3 ) + if ( !minOS(ObjectFile::ReaderOptions::k10_4, ObjectFile::ReaderOptions::k2_0) ) fReaderOptions.fImplicitlyLinkPublicDylibs = false; - // determine if info for shared region should be added - if ( fOutputKind == Options::kDynamicLibrary ) { - if ( fReaderOptions.fVersionMin >= ObjectFile::ReaderOptions::k10_5 ) - if ( fArchitecture != CPU_TYPE_ARM ) - fSharedRegionEligible = true; - } + // allow build system to force linker to ignore -prebind + if ( getenv("LD_FORCE_NO_PREBIND") != NULL ) + fPrebind = false; - // allow build system to force linker to ignore seg_addr_table + // allow build system to force linker to ignore -seg_addr_table if ( getenv("LD_FORCE_NO_SEG_ADDR_TABLE") != NULL ) fSegAddrTablePath = NULL; @@ -2630,8 +2891,11 @@ void Options::reconfigureDefaults() parseSegAddrTable(fSegAddrTablePath, this->installPath()); // HACK to support seg_addr_table entries that are physical paths instead of install paths if ( fBaseAddress == 0 ) { - if ( strcmp(this->installPath(), "/usr/lib/libstdc++.6.dylib") == 0 ) + if ( strcmp(this->installPath(), "/usr/lib/libstdc++.6.dylib") == 0 ) { parseSegAddrTable(fSegAddrTablePath, "/usr/lib/libstdc++.6.0.4.dylib"); + if ( fBaseAddress == 0 ) + parseSegAddrTable(fSegAddrTablePath, "/usr/lib/libstdc++.6.0.9.dylib"); + } else if ( strcmp(this->installPath(), "/usr/lib/libz.1.dylib") == 0 ) parseSegAddrTable(fSegAddrTablePath, "/usr/lib/libz.1.2.3.dylib"); @@ -2670,17 +2934,21 @@ void Options::reconfigureDefaults() } } + // -r implies no prebinding for all architectures + if ( fOutputKind == Options::kObjectFile ) + fPrebind = false; + // disable prebinding depending on arch and min OS version if ( fPrebind ) { switch ( fArchitecture ) { case CPU_TYPE_POWERPC: case CPU_TYPE_I386: - if ( fReaderOptions.fVersionMin == ObjectFile::ReaderOptions::k10_4 ) { + if ( fReaderOptions.fMacVersionMin == ObjectFile::ReaderOptions::k10_4 ) { // in 10.4 only split seg dylibs are prebound if ( (fOutputKind != Options::kDynamicLibrary) || ! fSplitSegs ) fPrebind = false; } - else if ( fReaderOptions.fVersionMin >= ObjectFile::ReaderOptions::k10_5 ) { + else if ( fReaderOptions.fMacVersionMin >= ObjectFile::ReaderOptions::k10_5 ) { // in 10.5 nothing is prebound fPrebind = false; } @@ -2695,6 +2963,8 @@ void Options::reconfigureDefaults() case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: // disable prebinding for everything else fPrebind = false; break; @@ -2715,6 +2985,8 @@ void Options::reconfigureDefaults() case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: // disable prebinding for everything else fPrebind = false; break; @@ -2727,29 +2999,132 @@ void Options::reconfigureDefaults() if ( fSplitSegs && !fPrebind ) fSplitSegs = false; + // determine if info for shared region should be added + if ( fOutputKind == Options::kDynamicLibrary ) { + if ( minOS(ObjectFile::ReaderOptions::k10_5, ObjectFile::ReaderOptions::k3_0) ) + if ( !fPrebind ) + if ( (strncmp(this->installPath(), "/usr/lib/", 9) == 0) + || (strncmp(this->installPath(), "/System/Library/", 16) == 0) ) + fSharedRegionEligible = true; + } + // figure out if module table is needed for compatibility with old ld/dyld if ( fOutputKind == Options::kDynamicLibrary ) { switch ( fArchitecture ) { case CPU_TYPE_POWERPC: // 10.3 and earlier dyld requires a module table case CPU_TYPE_I386: // ld_classic for 10.4.x requires a module table - if ( fReaderOptions.fVersionMin <= ObjectFile::ReaderOptions::k10_5 ) + if ( fReaderOptions.fMacVersionMin <= ObjectFile::ReaderOptions::k10_5 ) fNeedsModuleTable = true; break; case CPU_TYPE_ARM: - fNeedsModuleTable = true; // redo_prebinding requires a module table + if ( fPrebind ) + fNeedsModuleTable = true; // redo_prebinding requires a module table break; } } // -r -x implies -S if ( (fOutputKind == Options::kObjectFile) && (fLocalSymbolHandling == kLocalSymbolsNone) ) - fReaderOptions.fDebugInfoStripping = ObjectFile::ReaderOptions::kDebugInfoNone; - + fReaderOptions.fDebugInfoStripping = ObjectFile::ReaderOptions::kDebugInfoNone; + + // choose how to process unwind info + switch ( fArchitecture ) { + case CPU_TYPE_I386: + case CPU_TYPE_X86_64: + switch ( fOutputKind ) { + case Options::kObjectFile: + case Options::kStaticExecutable: + case Options::kPreload: + case Options::kKextBundle: + fReaderOptions.fAddCompactUnwindEncoding = false; + break; + case Options::kDyld: + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + case Options::kDynamicExecutable: + //if ( fReaderOptions.fAddCompactUnwindEncoding && (fReaderOptions.fVersionMin >= ObjectFile::ReaderOptions::k10_6) ) + // fReaderOptions.fRemoveDwarfUnwindIfCompactExists = true; + break; + } + break; + case CPU_TYPE_POWERPC: + case CPU_TYPE_POWERPC64: + case CPU_TYPE_ARM: + fReaderOptions.fAddCompactUnwindEncoding = false; + fReaderOptions.fRemoveDwarfUnwindIfCompactExists = false; + break; + case 0: + // if -arch is missing, assume we don't want compact unwind info + fReaderOptions.fAddCompactUnwindEncoding = false; + break; + } + // only ARM main executables can be encrypted if ( fOutputKind != Options::kDynamicExecutable ) fEncryptable = false; if ( fArchitecture != CPU_TYPE_ARM ) fEncryptable = false; + + // don't move inits in dyld because dyld wants certain + // entries point at stable locations at the start of __text + if ( fOutputKind == Options::kDyld ) + fReaderOptions.fAutoOrderInitializers = false; + + + // disable __data ordering for some output kinds + switch ( fOutputKind ) { + case Options::kObjectFile: + case Options::kDyld: + case Options::kStaticExecutable: + case Options::kPreload: + case Options::kKextBundle: + fOrderData = false; + break; + case Options::kDynamicExecutable: + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + break; + } + + // only use compressed LINKEDIT for x86_64 and i386 + if ( fMakeCompressedDyldInfo ) { + switch (fArchitecture) { + case CPU_TYPE_I386: + case CPU_TYPE_X86_64: + if ( fReaderOptions.fMacVersionMin >= ObjectFile::ReaderOptions::k10_6 ) + fMakeClassicDyldInfo = false; + else if ( fReaderOptions.fMacVersionMin < ObjectFile::ReaderOptions::k10_5 ) + fMakeCompressedDyldInfo = false; + break; + case CPU_TYPE_POWERPC: + case CPU_TYPE_ARM: + case CPU_TYPE_POWERPC64: + default: + fMakeCompressedDyldInfo = false; + } + } + + // only use compressed LINKEDIT for final linked images + if ( fMakeCompressedDyldInfo ) { + switch ( fOutputKind ) { + case Options::kDynamicExecutable: + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + break; + case Options::kPreload: + case Options::kStaticExecutable: + case Options::kObjectFile: + case Options::kDyld: + case Options::kKextBundle: + fMakeCompressedDyldInfo = false; + break; + } + } + fReaderOptions.fMakeCompressedDyldInfo = fMakeCompressedDyldInfo; + + // only ARM enforces that cpu-sub-types must match + if ( fArchitecture != CPU_TYPE_ARM ) + fAllowCpuSubtypeMismatches = true; } void Options::checkIllegalOptionCombinations() @@ -2870,6 +3245,8 @@ void Options::checkIllegalOptionCombinations() case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: throw "-stack_size option can only be used when linking a main executable"; } } @@ -2885,6 +3262,8 @@ void Options::checkIllegalOptionCombinations() case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: throw "-allow_stack_execute option can only be used when linking a main executable"; } } @@ -2899,6 +3278,8 @@ void Options::checkIllegalOptionCombinations() case Options::kDynamicLibrary: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: throw "-client_name can only be used with -bundle"; } } @@ -2994,7 +3375,7 @@ void Options::checkIllegalOptionCombinations() break; case CPU_TYPE_POWERPC64: // first 4GB for ppc64 on 10.5 - if ( fReaderOptions.fVersionMin >= ObjectFile::ReaderOptions::k10_5 ) + if ( fReaderOptions.fMacVersionMin >= ObjectFile::ReaderOptions::k10_5 ) fZeroPageSize = 0x100000000ULL; else fZeroPageSize = 0x1000; // 10.4 dyld may not be able to handle >4GB zero page @@ -3018,6 +3399,8 @@ void Options::checkIllegalOptionCombinations() case Options::kDynamicBundle: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: if ( fZeroPageSize != 0 ) throw "-pagezero_size option can only be used when linking a main executable"; } @@ -3029,7 +3412,7 @@ void Options::checkIllegalOptionCombinations() // can't use -rpath unless targeting 10.5 or later if ( fRPaths.size() > 0 ) { - if ( fReaderOptions.fVersionMin < ObjectFile::ReaderOptions::k10_5 ) + if ( !minOS(ObjectFile::ReaderOptions::k10_5, ObjectFile::ReaderOptions::k2_0) ) throw "-rpath can only be used when targeting Mac OS X 10.5 or later"; switch ( fOutputKind ) { case Options::kDynamicExecutable: @@ -3039,19 +3422,49 @@ void Options::checkIllegalOptionCombinations() case Options::kStaticExecutable: case Options::kObjectFile: case Options::kDyld: + case Options::kPreload: + case Options::kKextBundle: throw "-rpath can only be used when creating a dynamic final linked image"; } } // check -pie is only used when building a dynamic main executable for 10.5 if ( fPositionIndependentExecutable ) { - if ( fOutputKind != Options::kDynamicExecutable ) - throw "-pie can only be used when linking a main executable"; - if ( fReaderOptions.fVersionMin < ObjectFile::ReaderOptions::k10_5 ) + switch ( fOutputKind ) { + case Options::kDynamicExecutable: + case Options::kPreload: + break; + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + warning("-pie being ignored. It is only used when linking a main executable"); + break; + case Options::kStaticExecutable: + case Options::kObjectFile: + case Options::kDyld: + case Options::kKextBundle: + throw "-pie can only be used when linking a main executable"; + } + if ( !minOS(ObjectFile::ReaderOptions::k10_5, ObjectFile::ReaderOptions::k2_0) ) throw "-pie can only be used when targeting Mac OS X 10.5 or later"; } -} - + + // check -read_only_relocs is not used with x86_64 + if ( fAllowTextRelocs ) { + if ( (fArchitecture == CPU_TYPE_X86_64) && (fOutputKind != kKextBundle) ) { + warning("-read_only_relocs cannot be used with x86_64"); + fAllowTextRelocs = false; + } + } + + // check -mark_auto_dead_strip is only used with dylibs + if ( fMarkDeadStrippableDylib ) { + if ( fOutputKind != Options::kDynamicLibrary ) { + warning("-mark_auto_dead_strip can only be used when creating a dylib"); + fMarkDeadStrippableDylib = false; + } + } + +} void Options::checkForClassic(int argc, const char* argv[]) @@ -3060,9 +3473,16 @@ void Options::checkForClassic(int argc, const char* argv[]) bool archFound = false; bool staticFound = false; bool dtraceFound = false; + bool kextFound = false; bool rFound = false; bool creatingMachKernel = false; bool newLinker = false; + + // build command line buffer in case ld crashes + for(int i=1; i < argc; ++i) { + strlcat(crashreporterBuffer, argv[i], 1000); + strlcat(crashreporterBuffer, " ", 1000); + } for(int i=0; i < argc; ++i) { const char* arg = argv[i]; @@ -3074,6 +3494,9 @@ void Options::checkForClassic(int argc, const char* argv[]) else if ( strcmp(arg, "-static") == 0 ) { staticFound = true; } + else if ( strcmp(arg, "-kext") == 0 ) { + kextFound = true; + } else if ( strcmp(arg, "-dtrace") == 0 ) { dtraceFound = true; } @@ -3107,20 +3530,27 @@ void Options::checkForClassic(int argc, const char* argv[]) case CPU_TYPE_I386: case CPU_TYPE_ARM: // if ( staticFound && (rFound || !creatingMachKernel) ) { - if ( staticFound && !newLinker ) { + if ( (staticFound || kextFound) && !newLinker ) { // this environment variable will disable use of ld_classic for -static links if ( getenv("LD_NO_CLASSIC_LINKER_STATIC") == NULL ) { - // ld_classic does not support -aspen_version_min, so change + // ld_classic does not support -iphoneos_version_min, so change for(int j=0; j < argc; ++j) { - if ( (strcmp(argv[j], "-aspen_version_min") == 0) - || (strcmp(argv[j], "-iphone_version_min") == 0) - || (strcmp(argv[j], "-iphoneos_version_min") == 0) ) { + if ( strcmp(argv[j], "-iphoneos_version_min") == 0) { argv[j] = "-macosx_version_min"; if ( j < argc-1 ) argv[j+1] = "10.5"; break; } } + // ld classic does not understand -kext (change to -static -r) + if ( kextFound ) { + for(int j=0; j < argc; ++j) { + if ( strcmp(argv[j], "-kext") == 0) + argv[j] = "-r"; + else if ( strcmp(argv[j], "-dynamic") == 0) + argv[j] = "-static"; + } + } this->gotoClassicLinker(argc, argv); } } @@ -3138,6 +3568,16 @@ void Options::checkForClassic(int argc, const char* argv[]) void Options::gotoClassicLinker(int argc, const char* argv[]) { argv[0] = "ld_classic"; + char path[PATH_MAX]; + uint32_t bufSize = PATH_MAX; + if ( _NSGetExecutablePath(path, &bufSize) != -1 ) { + char* lastSlash = strrchr(path, '/'); + if ( lastSlash != NULL ) { + strcpy(lastSlash+1, "ld_classic"); + execvp(path, (char**)argv); + } + } + // in case of error in above, try searching for ld_classic via PATH execvp(argv[0], (char**)argv); fprintf(stderr, "can't exec ld_classic\n"); exit(1); diff --git a/src/Options.h b/src/ld/Options.h old mode 100755 new mode 100644 similarity index 85% rename from src/Options.h rename to src/ld/Options.h index d185848..9b8890e --- a/src/Options.h +++ b/src/ld/Options.h @@ -31,23 +31,28 @@ #include #include +#include #include "ObjectFile.h" extern void throwf (const char* format, ...) __attribute__ ((noreturn)); extern void warning(const char* format, ...); -class DynamicLibraryOptions +class LibraryOptions { public: - DynamicLibraryOptions() : fWeakImport(false), fReExport(false), fBundleLoader(false), fLazyLoad(false) {} - + LibraryOptions() : fWeakImport(false), fReExport(false), fBundleLoader(false), fLazyLoad(false), fForceLoad(false) {} + // for dynamic libraries bool fWeakImport; bool fReExport; bool fBundleLoader; bool fLazyLoad; + // for static libraries + bool fForceLoad; }; + + // // The public interface to the Options class is the abstract representation of what work the linker // should do. @@ -63,7 +68,7 @@ public: Options(int argc, const char* argv[]); ~Options(); - enum OutputKind { kDynamicExecutable, kStaticExecutable, kDynamicLibrary, kDynamicBundle, kObjectFile, kDyld }; + enum OutputKind { kDynamicExecutable, kStaticExecutable, kDynamicLibrary, kDynamicBundle, kObjectFile, kDyld, kPreload, kKextBundle }; enum NameSpace { kTwoLevelNameSpace, kFlatNameSpace, kForceFlatNameSpace }; // Standard treatment for many options. enum Treatment { kError, kWarning, kSuppress, kNULL, kInvalid }; @@ -79,7 +84,7 @@ public: const char* path; uint64_t fileLen; time_t modTime; - DynamicLibraryOptions options; + LibraryOptions options; }; struct ExtraSection { @@ -106,6 +111,11 @@ public: uint64_t address; }; + struct SegmentSize { + const char* name; + uint64_t size; + }; + struct SegmentProtect { const char* name; uint32_t max; @@ -125,6 +135,7 @@ public: cpu_type_t architecture() { return fArchitecture; } bool preferSubArchitecture() { return fHasPreferredSubType; } cpu_subtype_t subArchitecture() { return fSubArchitecture; } + bool allowSubArchitectureMismatches() { return fAllowCpuSubtypeMismatches; } OutputKind outputKind(); bool prebind(); bool bindAtLoad(); @@ -139,8 +150,8 @@ public: bool keepPrivateExterns(); // only for kObjectFile bool needsModuleTable(); // only for kDynamicLibrary bool interposable(const char* name); - bool hasExportRestrictList(); - bool hasExportMaskList(); + bool hasExportRestrictList(); // -exported_symbol or -unexported_symbol + bool hasExportMaskList(); // just -exported_symbol bool hasWildCardExportRestrictList(); bool allGlobalsAreDeadStripRoots(); bool shouldExport(const char*); @@ -150,7 +161,9 @@ public: bool traceArchives(); DeadStripMode deadStrip(); UndefinedTreatment undefinedTreatment(); - ObjectFile::ReaderOptions::VersionMin macosxVersionMin(); + ObjectFile::ReaderOptions::MacVersionMin macosxVersionMin() { return fReaderOptions.fMacVersionMin; } + ObjectFile::ReaderOptions::IPhoneVersionMin iphoneOSVersionMin() { return fReaderOptions.fIPhoneVersionMin; } + bool minOS(ObjectFile::ReaderOptions::MacVersionMin mac, ObjectFile::ReaderOptions::IPhoneVersionMin iPhoneOS); bool messagesPrefixedWithArchitecture(); Treatment picTreatment(); WeakReferenceMismatchTreatment weakReferenceMismatchTreatment(); @@ -167,6 +180,7 @@ public: std::vector& initialUndefines(); bool printWhyLive(const char* name); uint32_t minimumHeaderPad(); + uint64_t segmentAlignment() { return fSegmentAlignment; } bool maxMminimumHeaderPad() { return fMaxMinimumHeaderPad; } std::vector& extraSections(); std::vector& sectionAlignments(); @@ -188,11 +202,11 @@ public: bool splitSeg() { return fSplitSegs; } uint64_t baseWritableAddress() { return fBaseWritableAddress; } std::vector& customSegmentAddresses() { return fCustomSegmentAddresses; } + std::vector& customSegmentSizes() { return fCustomSegmentSizes; } std::vector& customSegmentProtections() { return fCustomSegmentProtections; } bool saveTempFiles() { return fSaveTempFiles; } const std::vector& rpaths() { return fRPaths; } bool readOnlyx86Stubs() { return fReadOnlyx86Stubs; } - bool slowx86Stubs() { return fReaderOptions.fSlowx86Stubs; } std::vector& dylibOverrides() { return fDylibOverrides; } const char* generatedMapPath() { return fMapPath; } bool positionIndependentExecutable() { return fPositionIndependentExecutable; } @@ -207,6 +221,16 @@ public: bool usingLazyDylibLinking() { return fUsingLazyDylibLinking; } bool verbose() { return fVerbose; } bool makeEncryptable() { return fEncryptable; } + bool needsUnwindInfoSection() { return fReaderOptions.fAddCompactUnwindEncoding; } + std::vector& llvmOptions() { return fLLVMOptions; } + bool makeClassicDyldInfo() { return fMakeClassicDyldInfo; } + bool makeCompressedDyldInfo() { return fMakeCompressedDyldInfo; } + bool hasExportedSymbolOrder(); + bool exportedSymbolOrder(const char* sym, unsigned int* order); + bool orderData() { return fOrderData; } + bool errorOnOtherArchFiles() { return fErrorOnOtherArchFiles; } + bool markAutoDeadStripDylib() { return fMarkDeadStrippableDylib; } + bool removeEHLabels() { return fReaderOptions.fNoEHLabels; } private: class CStringEquals @@ -214,7 +238,7 @@ private: public: bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); } }; - + typedef __gnu_cxx::hash_map, CStringEquals> NameToOrder; typedef __gnu_cxx::hash_set, CStringEquals> NameSet; enum ExportMode { kExportDefault, kExportSome, kDontExportSome }; enum LibrarySearchMode { kSearchDylibAndArchiveInEachDir, kSearchAllDirsForDylibsThenAllDirsForArchives }; @@ -271,6 +295,7 @@ private: void addLibrary(const FileInfo& info); void warnObsolete(const char* arg); uint32_t parseProtection(const char* prot); + void loadSymbolOrderFile(const char* fileOfExports, NameToOrder& orderMapping); ObjectFile::ReaderOptions fReaderOptions; @@ -285,6 +310,7 @@ private: bool fKeepPrivateExterns; bool fNeedsModuleTable; bool fIgnoreOtherArchFiles; + bool fErrorOnOtherArchFiles; bool fForceSubtypeAll; InterposeMode fInterposeMode; DeadStripMode fDeadStrip; @@ -300,6 +326,7 @@ private: SetWithWildcards fExportSymbols; SetWithWildcards fDontExportSymbols; SetWithWildcards fInterposeList; + NameToOrder fExportSymbolsOrder; ExportMode fExportMode; LibrarySearchMode fLibrarySearchMode; UndefinedTreatment fUndefinedTreatment; @@ -323,6 +350,7 @@ private: uint64_t fStackAddr; bool fExecutableStack; uint32_t fMinimumHeaderPad; + uint64_t fSegmentAlignment; CommonsMode fCommonsMode; UUIDMode fUUIDMode; SetWithWildcards fLocalSymbolsIncluded; @@ -346,6 +374,12 @@ private: bool fWarnTextRelocs; bool fUsingLazyDylibLinking; bool fEncryptable; + bool fOrderData; + bool fMarkDeadStrippableDylib; + bool fMakeClassicDyldInfo; + bool fMakeCompressedDyldInfo; + bool fNoEHLabels; + bool fAllowCpuSubtypeMismatches; std::vector fInitialUndefines; NameSet fAllowedUndefined; NameSet fWhyLive; @@ -353,9 +387,10 @@ private: std::vector fSectionAlignments; std::vector fOrderedSymbols; std::vector fCustomSegmentAddresses; + std::vector fCustomSegmentSizes; std::vector fCustomSegmentProtections; std::vector fDylibOverrides; - + std::vector fLLVMOptions; std::vector fLibrarySearchPaths; std::vector fFrameworkSearchPaths; std::vector fSDKPaths; diff --git a/src/SectCreate.h b/src/ld/SectCreate.h old mode 100755 new mode 100644 similarity index 100% rename from src/SectCreate.h rename to src/ld/SectCreate.h diff --git a/src/debugline.c b/src/ld/debugline.c old mode 100755 new mode 100644 similarity index 99% rename from src/debugline.c rename to src/ld/debugline.c index ff0e1d9..971e616 --- a/src/debugline.c +++ b/src/ld/debugline.c @@ -206,7 +206,8 @@ line_open (const uint8_t * debug_line, size_t debug_line_size, lnd = malloc (sizeof (struct line_reader_data)); if (! lnd) - goto error; + return NULL; + bzero(lnd, sizeof(struct line_reader_data)); lnd->little_endian = little_endian; lnd->cpos = debug_line; diff --git a/src/debugline.h b/src/ld/debugline.h old mode 100755 new mode 100644 similarity index 100% rename from src/debugline.h rename to src/ld/debugline.h diff --git a/src/dwarf2.h b/src/ld/dwarf2.h old mode 100755 new mode 100644 similarity index 97% rename from src/dwarf2.h rename to src/ld/dwarf2.h index 530b465..7a7b4f2 --- a/src/dwarf2.h +++ b/src/ld/dwarf2.h @@ -24,6 +24,9 @@ which is Copyright (c) 2005 Free Standards Group, and Copyright (c) 1992, 1993 UNIX International, Inc. */ +#ifndef __DWARF2_H__ +#define __DWARF2_H__ + /* This is not a complete list. */ enum { DW_TAG_compile_unit = 17, @@ -83,3 +86,5 @@ enum { DW_LNE_set_address, DW_LNE_define_file }; + +#endif diff --git a/src/ld.cpp b/src/ld/ld.cpp old mode 100755 new mode 100644 similarity index 80% rename from src/ld.cpp rename to src/ld/ld.cpp index be90999..ded2a19 --- a/src/ld.cpp +++ b/src/ld/ld.cpp @@ -1,5 +1,5 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-* - * Copyright (c) 2005-2007 Apple Inc. All rights reserved. + * Copyright (c) 2005-2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -68,7 +68,6 @@ extern "C" double log2 ( double ); #include "LTOReader.hpp" #endif - #include "OpaqueSection.hpp" @@ -87,7 +86,7 @@ public: class Section : public ObjectFile::Section { public: - static Section* find(const char* sectionName, const char* segmentName, bool zeroFill); + static Section* find(const char* sectionName, const char* segmentName, bool zeroFill, bool createIfNeeded=true); static void assignIndexes(); const char* getName() { return fSectionName; } private: @@ -102,8 +101,8 @@ private: typedef __gnu_cxx::hash_map, CStringEquals> NameToSection; //typedef std::map NameToSection; - const char* fSectionName; - const char* fSegmentName; + char fSectionName[18]; + char fSegmentName[18]; bool fZeroFill; static NameToSection fgMapping; @@ -116,13 +115,71 @@ std::vector Section::fgSections; Section::NameToOrdinal Section::fgSegmentDiscoverOrder; Section::Section(const char* sectionName, const char* segmentName, bool zeroFill) - : fSectionName(sectionName), fSegmentName(segmentName), fZeroFill(zeroFill) + : fZeroFill(zeroFill) { - this->fIndex = fgSections.size(); + strlcpy(fSectionName, sectionName, sizeof(fSectionName)); + strlcpy(fSegmentName, segmentName, sizeof(fSegmentName)); + + this->fIndex = fgSections.size() + 20; // room for 20 standard sections + // special placement of some sections + if ( strcmp(segmentName, "__TEXT") == 0 ) { + // sort unwind info to end of segment + if ( strcmp(sectionName, "__eh_frame") == 0 ) + this->fIndex = INT_MAX; + else if ( strcmp(sectionName, "__unwind_info") == 0 ) + this->fIndex = INT_MAX-1; + else if ( strcmp(sectionName, "__gcc_except_tab") == 0 ) + this->fIndex = INT_MAX-2; + } + else if ( strcmp(segmentName, "__DATA") == 0 ) { + // sort sections dyld will touch to start of segment + if ( strcmp(sectionName, "__dyld") == 0 ) + this->fIndex = 1; + else if ( strcmp(sectionName, "__program_vars") == 0 ) + this->fIndex = 1; + else if ( strcmp(sectionName, "__mod_init_func") == 0 ) + this->fIndex = 2; + else if ( strcmp(sectionName, "__nl_symbol_ptr") == 0 ) + this->fIndex = 3; + else if ( strcmp(sectionName, "__la_symbol_ptr") == 0 ) + this->fIndex = 4; + else if ( strcmp(sectionName, "__const") == 0 ) + this->fIndex = 5; + else if ( strcmp(sectionName, "__cfstring") == 0 ) + this->fIndex = 6; + else if ( strcmp(sectionName, "__gcc_except_tab") == 0 ) + this->fIndex = 7; + else if ( strcmp(sectionName, "__objc_data") == 0 ) + this->fIndex = 8; + else if ( strcmp(sectionName, "__objc_msgrefs") == 0 ) + this->fIndex = 9; + else if ( strcmp(sectionName, "__objc_protorefs") == 0 ) + this->fIndex = 10; + else if ( strcmp(sectionName, "__objc_selrefs") == 0 ) + this->fIndex = 11; + else if ( strcmp(sectionName, "__objc_classrefs") == 0 ) + this->fIndex = 12; + else if ( strcmp(sectionName, "__objc_superrefs") == 0 ) + this->fIndex = 13; + else if ( strcmp(sectionName, "__objc_const") == 0 ) + this->fIndex = 14; + else if ( strcmp(sectionName, "__objc_classlist") == 0 ) + this->fIndex = 15; + else if ( strcmp(sectionName, "__objc_nlclslist") == 0 ) + this->fIndex = 16; + else if ( strcmp(sectionName, "__objc_catlist") == 0 ) + this->fIndex = 17; + else if ( strcmp(sectionName, "__objc_protolist") == 0 ) + this->fIndex = 18; + else if ( strcmp(sectionName, "__objc_imageinfo") == 0 ) + this->fIndex = 19; + + } + //fprintf(stderr, "new Section(%s, %s) => %p, %u\n", sectionName, segmentName, this, this->getIndex()); } -Section* Section::find(const char* sectionName, const char* segmentName, bool zeroFill) +Section* Section::find(const char* sectionName, const char* segmentName, bool zeroFill, bool createIfNeeded) { NameToSection::iterator pos = fgMapping.find(sectionName); if ( pos != fgMapping.end() ) { @@ -135,14 +192,17 @@ Section* Section::find(const char* sectionName, const char* segmentName, bool ze } } + if ( !createIfNeeded ) + return NULL; + // does not exist, so make a new one Section* sect = new Section(sectionName, segmentName, zeroFill); fgMapping[sectionName] = sect; fgSections.push_back(sect); if ( (strcmp(sectionName, "__text") == 0) && (strcmp(segmentName, "__TEXT") == 0) ) { - // special case __textcoal_nt to be right after __text - find("__textcoal_nt", "__TEXT", false); + // special case __StaticInit to be right after __text + find("__StaticInit", "__TEXT", false); } // remember segment discovery order @@ -154,6 +214,8 @@ Section* Section::find(const char* sectionName, const char* segmentName, bool ze int Section::Sorter::segmentOrdinal(const char* segName) { + if ( strcmp(segName, "__HEADER") == 0 ) + return 1; if ( strcmp(segName, "__PAGEZERO") == 0 ) return 1; if ( strcmp(segName, "__TEXT") == 0 ) @@ -234,13 +296,14 @@ private: struct WhyLiveBackChain { WhyLiveBackChain* previous; - const char* name; + ObjectFile::Atom* referer; }; ObjectFile::Reader* createReader(const Options::FileInfo&); void addAtom(ObjectFile::Atom& atom); void addAtoms(std::vector& atoms); void buildAtomList(); + void adjustScope(); void processDylibs(); void markDead(ObjectFile::Atom* atom); void updateConstraints(ObjectFile::Reader* reader); @@ -249,10 +312,10 @@ private: void checkObjC(); void loadUndefines(); void checkUndefines(); - void addWeakAtomOverrides(); void resolveReferences(); void deadStripResolve(); void addLiveRoot(const char* name); + void moveToFrontOfSection(ObjectFile::Atom* atom); ObjectFile::Atom* findAtom(const Options::OrderedSymbol& pair); void logArchive(ObjectFile::Reader* reader); void sortSections(); @@ -264,7 +327,8 @@ private: void collectDebugInfo(); void writeOutput(); ObjectFile::Atom* entryPoint(bool orInit); - ObjectFile::Atom* dyldHelper(); + ObjectFile::Atom* dyldClassicHelper(); + ObjectFile::Atom* dyldCompressedHelper(); ObjectFile::Atom* dyldLazyLibraryHelper(); const char* assureFullPath(const char* path); void markLive(ObjectFile::Atom& atom, Linker::WhyLiveBackChain* previous); @@ -275,13 +339,12 @@ private: char* commatize(uint64_t in, char* out); void getVMInfo(vm_statistics_data_t& info); cpu_type_t inferArchitecture(); - void addDtraceProbe(ObjectFile::Atom& atom, uint32_t offsetInAtom, const char* probeName); void checkDylibClientRestrictions(ObjectFile::Reader* reader); void logDylib(ObjectFile::Reader* reader, bool indirect); void resolve(ObjectFile::Reference* reference); void resolveFrom(ObjectFile::Reference* reference); - std::vector* addJustInTimeAtoms(const char* name, bool dylibsOnly=false); + std::vector* addJustInTimeAtoms(const char* name, bool searchDylibs, bool searchArchives, bool okToMakeProxy); void addJustInTimeAtomsAndMarkLive(const char* name); ObjectFile::Reader* addDylib(ObjectFile::Reader* reader, const Options::FileInfo& info, uint64_t mappedLen); @@ -301,10 +364,11 @@ private: bool add(ObjectFile::Atom& atom); ObjectFile::Atom* find(const char* name); unsigned int getRequireCount() { return fRequireCount; } - void getNeededNames(bool andWeakDefintions, std::vector& undefines); + void getUndefinesNames(std::vector& undefines); + void getTentativesNames(std::vector& tents); bool hasExternalTentativeDefinitions() { return fHasExternalTentativeDefinitions; } bool hasExternalWeakDefinitions() { return fHasExternalWeakDefinitions; } - void setHasExternalWeakDefinitions() { fHasExternalWeakDefinitions = true; } + void setHasExternalWeakDefinitions(bool value) { fHasExternalWeakDefinitions = value; } Mapper::iterator begin() { return fTable.begin(); } Mapper::iterator end() { return fTable.end(); } @@ -319,10 +383,14 @@ private: class AtomSorter { public: - AtomSorter(std::map* map) : fOverriddenOrdinalMap(map) {} + AtomSorter(std::map* map, std::set& inits, + std::set& terms) : + fOverriddenOrdinalMap(map), fInitializerSet(inits), fTerminatorSet(terms) {} bool operator()(const ObjectFile::Atom* left, const ObjectFile::Atom* right); private: std::map* fOverriddenOrdinalMap; + std::set& fInitializerSet; + std::set& fTerminatorSet; }; typedef std::map SectionOrder; @@ -353,7 +421,7 @@ private: std::vector fInputFiles; ExecutableFile::Writer* fOutputFile; InstallNameToReader fDylibMap; - std::map fDylibOptionsMap; + std::map fDylibOptionsMap; std::set fDylibsProcessed; ObjectFile::Reader* fBundleLoaderReader; std::vector fReadersThatHaveSuppliedAtoms; @@ -363,12 +431,13 @@ private: std::set fDeadAtoms; std::set fLiveAtoms; std::set fLiveRootAtoms; + std::set fInitializerAtoms; + std::set fTerminatorAtoms; + std::set fRegularDefAtomsThatOverrideADylibsWeakDef; std::vector fStabs; std::vector fAtomsWithUnresolvedReferences; - std::vector fDtraceProbes; - std::vector fDtraceProbeSites; - std::vector fDtraceIsEnabledSites; - std::map fDtraceAtomToTypes; + std::set fAtomsOverriddenByLateLoads; + bool fInitialLoadsDone; bool fCreateUUID; bool fCanScatter; SectionOrder fSectionOrder; @@ -404,7 +473,7 @@ private: Linker::Linker(int argc, const char* argv[]) : fOptions(argc, argv), fGlobalSymbolTable(*this), fNextInputOrdinal(1), fOutputFile(NULL), fBundleLoaderReader(NULL), - fCreateUUID(fOptions.outputKind() != Options::kObjectFile), fCanScatter(true), + fInitialLoadsDone(false), fCreateUUID(fOptions.outputKind() != Options::kObjectFile), fCanScatter(true), fArchitecture(0), fArchitectureInferred(false), fDirectLibrariesComplete(false), fBiggerThanTwoGigOutput(false), fOutputFileSize(0), fTotalZeroFillSize(0), fTotalSize(0), fTotalObjectSize(0), fTotalArchiveSize(0), fTotalObjectLoaded(0), fTotalArchivesLoaded(0), fTotalDylibsLoaded(0), @@ -562,46 +631,108 @@ void Linker::loadAndResolve() void Linker::optimize() { // give each reader a chance to do any optimizations + bool didSomething = false; std::vector newAtoms; std::vector additionalUndefines; + std::vector newlyDeadAtoms; for (std::vector::iterator it=fInputFiles.begin(); it != fInputFiles.end(); it++) { - (*it)->optimize(fAllAtoms, newAtoms, additionalUndefines, fNextInputOrdinal, fOutputFile, + didSomething |= (*it)->optimize(fAllAtoms, newAtoms, additionalUndefines, fDeadAtoms, newlyDeadAtoms, fNextInputOrdinal, + fOutputFile, entryPoint(true), fOptions.llvmOptions(), fOptions.allGlobalsAreDeadStripRoots(), (int)fOptions.outputKind(), fOptions.verbose(), fOptions.saveTempFiles(), fOptions.getOutputFilePath(), fOptions.positionIndependentExecutable(), fOptions.allowTextRelocs()); } - // add all newly created atoms to fAllAtoms and update symbol table - this->addAtoms(newAtoms); + // only do next steps if some optimization was actually done + if ( didSomething ) { + // add all newly created atoms to fAllAtoms and update symbol table + this->addAtoms(newAtoms); + + // add dead atoms to dead list and remove from fAllAtoms + for(std::vector::iterator itr = newlyDeadAtoms.begin(); itr != newlyDeadAtoms.end(); ++itr) + markDead(*itr); + fAllAtoms.erase(std::remove_if(fAllAtoms.begin(), fAllAtoms.end(), InSet(fDeadAtoms)), fAllAtoms.end()); - // Make sure all atoms have a section. Atoms that were not originally in a mach-o file could - // not have their section set until now. - for(std::vector::iterator itr = fAllAtoms.begin(); itr != fAllAtoms.end(); ++itr) { - ObjectFile::Atom *atom = *itr; - if ( atom->getSection() == NULL ) - atom->setSection(Section::find(atom->getSectionName(), atom->getSegment().getName(), atom->isZeroFill())); - } + // Make sure all atoms have a section. Atoms that were not originally in a mach-o file could + // not have their section set until now. + for(std::vector::iterator itr = fAllAtoms.begin(); itr != fAllAtoms.end(); ++itr) { + ObjectFile::Atom *atom = *itr; + if ( atom->getSection() == NULL ) + atom->setSection(Section::find(atom->getSectionName(), atom->getSegment().getName(), atom->isZeroFill())); + } - // resolve new undefines - for(std::vector::iterator riter = additionalUndefines.begin(); riter != additionalUndefines.end(); ++riter) { - const char *targetName = *riter; - //fprintf(stderr, "LTO additional undefine: %s\n", targetName); - ObjectFile::Atom* target = fGlobalSymbolTable.find(targetName); - if ( target == NULL) { - // mark that this symbol is needed - fGlobalSymbolTable.require(targetName); - // try to find it in some library - this->addJustInTimeAtoms(targetName); + // resolve new undefines + for(std::vector::iterator riter = additionalUndefines.begin(); riter != additionalUndefines.end(); ++riter) { + const char *targetName = *riter; + //fprintf(stderr, "LTO additional undefine: %s\n", targetName); + ObjectFile::Atom* target = fGlobalSymbolTable.find(targetName); + if ( target == NULL) { + // mark that this symbol is needed + fGlobalSymbolTable.require(targetName); + // try to find it in some library + this->addJustInTimeAtoms(targetName, true, true, true); + } + } + + if ( fOptions.deadStrip() != Options::kDeadStripOff ) { + // LTO may optimize away some atoms, so dead stripping must be redone + fLiveAtoms.clear(); + this->deadStripResolve(); + } + else { + // LTO may require new library symbols to be loaded, so redo + this->checkUndefines(); + this->resolveReferences(); } } +} - if ( fOptions.deadStrip() != Options::kDeadStripOff ) { - fLiveAtoms.clear(); - this->deadStripResolve(); + +void Linker::adjustScope() +{ + // if -exported_symbols_list is used, demoted to hidden, symbols that are not in it + if ( fOptions.hasExportRestrictList() ) { + // The use of an -export file means the previous computation of fHasExternalWeakDefinitions could change + fGlobalSymbolTable.setHasExternalWeakDefinitions(false); + for(std::vector::iterator itr = fAllAtoms.begin(); itr != fAllAtoms.end(); ++itr) { + ObjectFile::Atom *atom = *itr; + ObjectFile::Atom::Scope scope = atom->getScope(); + const char* name = atom->getName(); + if ( name != NULL ) { + if ( scope == ObjectFile::Atom::scopeGlobal ) { + // check for globals that are downgraded to hidden + if ( !fOptions.shouldExport(name) ) { + atom->setScope(ObjectFile::Atom::scopeLinkageUnit); + //fprintf(stderr, "demote %s to hidden\n", name); + } + else if ( atom->getDefinitionKind() == ObjectFile::Atom::kWeakDefinition ) { + // we do have an exported weak symbol, turn WEAK_DEFINES back on + fGlobalSymbolTable.setHasExternalWeakDefinitions(true); + } + } + else if ( scope == ObjectFile::Atom::scopeLinkageUnit ) { + // check for hiddens that were requested to be exported + if ( fOptions.hasExportMaskList() && fOptions.shouldExport(name) ) { + warning("cannot export hidden symbol %s from %s", name, atom->getFile()->getPath()); + } + } + } + } + } + + // linking is done, so demote hidden symbols to static + if ( (fOptions.outputKind() == Options::kObjectFile) && fOptions.keepPrivateExterns() ) { + // ld -r -keep_private_externs does not move hidden symbols to static } else { - this->checkUndefines(); - this->resolveReferences(); + for(std::vector::iterator itr = fAllAtoms.begin(); itr != fAllAtoms.end(); ++itr) { + ObjectFile::Atom *atom = *itr; + // hidden common symbols cannot be demoted to static + if ( (atom->getScope() == ObjectFile::Atom::scopeLinkageUnit) && (atom->getDefinitionKind() != ObjectFile::Atom::kTentativeDefinition) ) { + atom->setScope(ObjectFile::Atom::scopeTranslationUnit); + //fprintf(stderr, "demote %s to static\n", atom->getDisplayName()); + } + } } } @@ -610,6 +741,7 @@ void Linker::link() this->buildAtomList(); this->loadAndResolve(); this->optimize(); + this->adjustScope(); this->checkObjC(); this->processDTrace(); this->tweakLayout(); @@ -717,8 +849,6 @@ inline void Linker::addAtom(ObjectFile::Atom& atom) fGlobalSymbolTable.require(reference->getTargetName()); if ( reference->getFromTargetBinding() == ObjectFile::Reference::kUnboundByName ) fGlobalSymbolTable.require(reference->getFromTargetName()); - if ( reference->getTargetBinding() == ObjectFile::Reference::kDontBind ) - addDtraceProbe(atom, reference->getFixUpOffset(), reference->getTargetName()); } // update total size info (except for __ZEROPAGE atom) if ( atom.getSegment().isContentReadable() ) { @@ -736,34 +866,8 @@ inline void Linker::addAtom(ObjectFile::Atom& atom) ObjectFile::Atom::Scope scope = atom.getScope(); const char* name = atom.getName(); if ( (scope != ObjectFile::Atom::scopeTranslationUnit) && (name != NULL) ) { - // update scope based on export list - if ( fOptions.hasExportRestrictList() ) { - if ( scope == ObjectFile::Atom::scopeGlobal ) { - // check for globals that are downgraded to hidden - bool doExport = fOptions.shouldExport(name); - if ( !doExport ) { - atom.setScope(ObjectFile::Atom::scopeLinkageUnit); - } - } - else if ( scope == ObjectFile::Atom::scopeLinkageUnit ) { - // check for hiddens that were requested to be exported - if ( fOptions.hasExportMaskList() && fOptions.shouldExport(name) ) { - warning("cannot export hidden symbol %s from %s", name, atom.getFile()->getPath()); - } - } - } // add to symbol table - if ( fOptions.outputKind() == Options::kObjectFile ) { - // in ld -r mode don't add .eh symbols to symbol table - // instead kGroupSubordinate references will keep them paired - // with their functions. - const char* sectionName = atom.getSectionName(); - if ( (sectionName != NULL) && (strcmp(sectionName, "__eh_frame") != 0) ) - fGlobalSymbolTable.add(atom); - } - else { - fGlobalSymbolTable.add(atom); - } + fGlobalSymbolTable.add(atom); } // record section orders so output file can have same order @@ -774,7 +878,14 @@ inline void Linker::addAtom(ObjectFile::Atom& atom) void Linker::markDead(ObjectFile::Atom* atom) { + //fprintf(stderr, "markDead(%p) %s from %s\n", atom, atom->getDisplayName(), atom->getFile()->getPath()); fDeadAtoms.insert(atom); + + // -dead_strip inhibits weak coalescing in no_dead_strip section + if ( fLiveRootAtoms.count(atom) != 0 ) { + fLiveRootAtoms.erase(atom); + } + // // The kGroupSubordinate reference kind is used to model group comdat. // The "signature" atom in the group has a kGroupSubordinate reference to @@ -786,6 +897,7 @@ void Linker::markDead(ObjectFile::Atom* atom) ObjectFile::Reference* ref = *rit; if ( ref->getKind() == 2 /*kGroupSubordinate*/ ) { // FIX FIX ObjectFile::Atom* targetAtom = &(ref->getTarget()); + //fprintf(stderr, " markDead(%p) subordinate %s\n", targetAtom, targetAtom->getDisplayName()); if ( targetAtom == NULL ) { warning("%s has a group reference to %s but is not bound", atom->getDisplayName(), ref->getTargetName()); } @@ -895,6 +1007,10 @@ void Linker::buildAtomList() this->addAtoms((new opaque_section::Reader(it->segmentName, it->sectionName, it->path, it->data, it->dataLen, fNextInputOrdinal))->getAtoms()); fNextInputOrdinal += it->dataLen; } + + // done with all .o files on command line + // everything loaded from now on is a just-in-time atom + fInitialLoadsDone = true; } static const char* pathLeafName(const char* path) @@ -906,6 +1022,7 @@ static const char* pathLeafName(const char* path) return &shortPath[1]; } + void Linker::loadUndefines() { // keep looping until no more undefines were added in last loop @@ -913,19 +1030,30 @@ void Linker::loadUndefines() while ( undefineCount != fGlobalSymbolTable.getRequireCount() ) { undefineCount = fGlobalSymbolTable.getRequireCount(); std::vector undefineNames; - fGlobalSymbolTable.getNeededNames(false, undefineNames); + fGlobalSymbolTable.getUndefinesNames(undefineNames); for(std::vector::iterator it = undefineNames.begin(); it != undefineNames.end(); ++it) { - const char* name = *it; - ObjectFile::Atom* possibleAtom = fGlobalSymbolTable.find(name); - if ( (possibleAtom == NULL) - || ((possibleAtom->getDefinitionKind()==ObjectFile::Atom::kWeakDefinition) - && (fOptions.outputKind() != Options::kObjectFile) - && (possibleAtom->getScope() == ObjectFile::Atom::scopeGlobal)) ) { - std::vector* atoms = this->addJustInTimeAtoms(name); + // load for previous undefine may also have loaded this undefine, so check again + if ( fGlobalSymbolTable.find(*it) == NULL ) { + std::vector* atoms = this->addJustInTimeAtoms(*it, true, true, true); if ( atoms != NULL ) delete atoms; } } + // need to search archives for overrides of common symbols + if ( fGlobalSymbolTable.hasExternalTentativeDefinitions() ) { + bool searchDylibs = (fOptions.commonsMode() == Options::kCommonsOverriddenByDylibs); + std::vector tentativeDefinitionNames; + fGlobalSymbolTable.getTentativesNames(tentativeDefinitionNames); + for(std::vector::iterator it = tentativeDefinitionNames.begin(); it != tentativeDefinitionNames.end(); ++it) { + // load for previous tentative may also have overridden this tentative, so check again + ObjectFile::Atom* tent = fGlobalSymbolTable.find(*it); + if ( (tent != NULL) && (tent->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) ) { + std::vector* atoms = this->addJustInTimeAtoms(*it, searchDylibs, true, false); + if ( atoms != NULL ) + delete atoms; + } + } + } } } @@ -972,7 +1100,7 @@ void Linker::checkUndefines() break; } std::vector unresolvableUndefines; - fGlobalSymbolTable.getNeededNames(false, unresolvableUndefines); + fGlobalSymbolTable.getUndefinesNames(unresolvableUndefines); // temp hack for rdar://problem/4718189 map ObjC class names to new runtime names // ignore unresolved references to Objc class names that are listed in -exported_symbols_list @@ -1029,33 +1157,29 @@ void Linker::checkUndefines() if ( (atom != NULL) && (atom->getDefinitionKind()==ObjectFile::Atom::kTentativeDefinition) && (atom->getScope() == ObjectFile::Atom::scopeGlobal) ) { // look for dylibs that export same name as used by global tentative definition - addJustInTimeAtoms(atom->getName(), true); + addJustInTimeAtoms(atom->getName(), true, false, false); } } } - // if we have no weak symbols, see if we override some weak symbol in some dylib - if ( !fGlobalSymbolTable.hasExternalWeakDefinitions() ) { - bool done = false; - for (SymbolTable::Mapper::iterator it=fGlobalSymbolTable.begin(); !done && (it != fGlobalSymbolTable.end()); ++it) { - ObjectFile::Atom* atom = it->second; - if ( (atom != NULL) && (atom->getDefinitionKind()==ObjectFile::Atom::kRegularDefinition) - && (atom->getScope() == ObjectFile::Atom::scopeGlobal) ) { - const char* name = atom->getName(); - //fprintf(stderr, "looking for dylibs with a weak %s\n", name); - // look for dylibs with weak exports of the same name - for (InstallNameToReader::iterator it=fDylibMap.begin(); it != fDylibMap.end(); it++) { - ObjectFile::Reader* reader = it->second; - if ( reader->hasWeakExternals() ) { - std::vector* atoms = reader->getJustInTimeAtomsFor(name); - if ( atoms != NULL ) { - //fprintf(stderr, "addJustInTimeAtoms(%s) => found in file %s\n", name, reader->getPath() ); - // if this is a weak definition in a dylib - if ( (atoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition) ) { - fGlobalSymbolTable.setHasExternalWeakDefinitions(); - done = true; - break; - } + + // record any overrides of weak symbols any linked dylib + for (SymbolTable::Mapper::iterator it=fGlobalSymbolTable.begin(); it != fGlobalSymbolTable.end(); ++it) { + ObjectFile::Atom* atom = it->second; + if ( (atom != NULL) && (atom->getDefinitionKind()==ObjectFile::Atom::kRegularDefinition) + && (atom->getScope() == ObjectFile::Atom::scopeGlobal) ) { + const char* name = atom->getName(); + //fprintf(stderr, "looking for dylibs with a weak %s\n", name); + // look for dylibs with weak exports of the same name + for (InstallNameToReader::iterator it=fDylibMap.begin(); it != fDylibMap.end(); it++) { + ObjectFile::Reader* reader = it->second; + if ( reader->hasWeakExternals() ) { + std::vector* dylibAtoms = reader->getJustInTimeAtomsFor(name); + if ( dylibAtoms != NULL ) { + //fprintf(stderr, "addJustInTimeAtoms(%s) => found in file %s\n", name, reader->getPath() ); + // if this is a weak definition in a dylib + if ( (dylibAtoms->at(0)->getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition) ) { + fRegularDefAtomsThatOverrideADylibsWeakDef.insert(atom); } } } @@ -1067,8 +1191,9 @@ void Linker::checkUndefines() -std::vector* Linker::addJustInTimeAtoms(const char* name, bool dylibsOnly) +std::vector* Linker::addJustInTimeAtoms(const char* name, bool searchDylibs, bool searchArchives, bool okToMakeProxy) { + //fprintf(stderr, "addJustInTimeAtoms(%s, searchDylibs=%d, searchArchives=%d)\n", name, searchDylibs, searchArchives ); // when creating final linked image, writer gets first chance if ( fOptions.outputKind() != Options::kObjectFile ) { std::vector* atoms = fOutputFile->getJustInTimeAtomsFor(name); @@ -1087,7 +1212,7 @@ std::vector* Linker::addJustInTimeAtoms(const char* nam // if this reader is a dylib that exports the symbol we need, have it synthesize an atom for us. //fprintf(stderr, "addJustInTimeAtoms(%s), looking in reader %s\n", name, reader->getPath() ); bool isDylibReader = (reader->getInstallPath() != NULL); - if ( !dylibsOnly || isDylibReader ) { + if ( isDylibReader ? searchDylibs : searchArchives ) { std::vector* atoms = reader->getJustInTimeAtomsFor(name); if ( atoms != NULL ) { this->addAtoms(*atoms); @@ -1148,9 +1273,11 @@ std::vector* Linker::addJustInTimeAtoms(const char* nam // 1) ld -r is being used to create a .o file // 2) -undefined dynamic_lookup is being used // 3) -U _foo is being used + // 4) x86_64 kext bundle is being created if ( (fOptions.outputKind() == Options::kObjectFile) - || ((fOptions.undefinedTreatment() != Options::kUndefinedError) && !dylibsOnly) - || (fOptions.someAllowedUndefines() && !dylibsOnly) ) { + || ((fOptions.undefinedTreatment() != Options::kUndefinedError) && okToMakeProxy) + || (fOptions.someAllowedUndefines() && okToMakeProxy) + || (fOptions.outputKind() == Options::kKextBundle) ) { ObjectFile::Atom* atom = fOutputFile->getUndefinedProxyAtom(name); if ( atom != NULL ) { this->addAtom(*atom); @@ -1167,7 +1294,7 @@ void Linker::resolve(ObjectFile::Reference* reference) const char* targetName = reference->getTargetName(); ObjectFile::Atom* target = fGlobalSymbolTable.find(targetName); if ( target == NULL ) { - fprintf(stderr, "Undefined symbol: %s\n", targetName); + throwf("unexpected undefined symbol: %s", targetName); } reference->setTarget(*target, reference->getTargetOffset()); } @@ -1178,7 +1305,7 @@ void Linker::resolveFrom(ObjectFile::Reference* reference) const char* fromTargetName = reference->getFromTargetName(); ObjectFile::Atom* fromTarget = fGlobalSymbolTable.find(fromTargetName); if ( fromTarget == NULL ) { - fprintf(stderr, "Undefined symbol: %s\n", fromTargetName); + throwf("unexpected undefined symbol: %s", fromTargetName); } reference->setFromTarget(*fromTarget); } @@ -1236,7 +1363,8 @@ private: void Linker::addJustInTimeAtomsAndMarkLive(const char* name) { - std::vector* atoms = this->addJustInTimeAtoms(name); + //fprintf(stderr, "addJustInTimeAtomsAndMarkLive(%s)\n", name); + std::vector* atoms = this->addJustInTimeAtoms(name, true, true, true); if ( atoms != NULL ) { if ( fOptions.allGlobalsAreDeadStripRoots() ) { for (std::vector::iterator it=atoms->begin(); it != atoms->end(); it++) { @@ -1244,7 +1372,7 @@ void Linker::addJustInTimeAtomsAndMarkLive(const char* name) if ( atom->getScope() == ObjectFile::Atom::scopeGlobal ) { WhyLiveBackChain rootChain; rootChain.previous = NULL; - rootChain.name = atom->getDisplayName(); + rootChain.referer = atom; this->markLive(*atom, &rootChain); } } @@ -1255,14 +1383,15 @@ void Linker::addJustInTimeAtomsAndMarkLive(const char* name) void Linker::markLive(ObjectFile::Atom& atom, struct Linker::WhyLiveBackChain* previous) { + //fprintf(stderr, "markLive(%p)\n", &atom); if ( fLiveAtoms.count(&atom) == 0 ) { - // if -whylive cares about this symbol, then dump chain - if ( (previous->name != NULL) && fOptions.printWhyLive(previous->name) ) { + // if -why_live cares about this symbol, then dump chain + if ( (previous->referer != NULL) && fOptions.printWhyLive(previous->referer->getDisplayName()) ) { int depth = 0; for(WhyLiveBackChain* p = previous; p != NULL; p = p->previous, ++depth) { for(int i=depth; i > 0; --i) fprintf(stderr, " "); - fprintf(stderr, "%s\n", p->name); + fprintf(stderr, "%p %s from %s\n", p->referer, p->referer->getDisplayName(), p->referer->getFile()->getPath()); } } // set up next chain @@ -1284,7 +1413,7 @@ void Linker::markLive(ObjectFile::Atom& atom, struct Linker::WhyLiveBackChain* p // look in global symbol table const char* targetName = reference->getTargetName(); ObjectFile::Atom* target = fGlobalSymbolTable.find(targetName); - if ( target == NULL ) { + if ( (target == NULL) || (target->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) ) { // load archives or dylibs this->addJustInTimeAtomsAndMarkLive(targetName); } @@ -1302,12 +1431,10 @@ void Linker::markLive(ObjectFile::Atom& atom, struct Linker::WhyLiveBackChain* p switch ( reference->getTargetBinding() ) { case ObjectFile::Reference::kBoundDirectly: case ObjectFile::Reference::kBoundByName: - thisChain.name = reference->getTargetName(); + thisChain.referer = &reference->getTarget(); markLive(reference->getTarget(), &thisChain); break; case ObjectFile::Reference::kDontBind: - addDtraceProbe(atom, reference->getFixUpOffset(), reference->getTargetName()); - break; case ObjectFile::Reference::kUnboundByName: // do nothing break; @@ -1317,7 +1444,7 @@ void Linker::markLive(ObjectFile::Atom& atom, struct Linker::WhyLiveBackChain* p // look in global symbol table const char* targetName = reference->getFromTargetName(); ObjectFile::Atom* target = fGlobalSymbolTable.find(targetName); - if ( target == NULL ) { + if ( (target == NULL) || (target->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) ) { // load archives or dylibs this->addJustInTimeAtomsAndMarkLive(targetName); } @@ -1334,7 +1461,7 @@ void Linker::markLive(ObjectFile::Atom& atom, struct Linker::WhyLiveBackChain* p switch ( reference->getFromTargetBinding() ) { case ObjectFile::Reference::kBoundDirectly: case ObjectFile::Reference::kBoundByName: - thisChain.name = reference->getFromTargetName(); + thisChain.referer = &reference->getFromTarget(); markLive(reference->getFromTarget(), &thisChain); break; case ObjectFile::Reference::kUnboundByName: @@ -1358,6 +1485,32 @@ void Linker::addLiveRoot(const char* name) fLiveRootAtoms.insert(target); } +void Linker::moveToFrontOfSection(ObjectFile::Atom* atom) +{ + // check if already moved to front + if ( fInitializerAtoms.find(atom) == fInitializerAtoms.end() ) { + // don't re-order initializers from .o files without MH_SUBSECTIONS_VIA_SYMBOLS + // since that could make all atoms in the file look like initializers + if ( atom->getFile()->canScatterAtoms() ) { + //fprintf(stdout, "marking as initializer: %s\n", atom->getDisplayName()); + fInitializerAtoms.insert(atom); + // mark all functions that this function references + std::vector& references = atom->getReferences(); + for (std::vector::const_iterator rit=references.begin(); rit != references.end(); rit++) { + ObjectFile::Atom* childAtom = &((*rit)->getTarget()); + if ( childAtom != NULL ) { + if ( (*rit)->isBranch() ) { + this->moveToFrontOfSection(childAtom); + } + else if ( (childAtom->getName() != NULL) && (strncmp(childAtom->getName(), "___tcf_", 7) == 0) ) { + //fprintf(stdout, "marking as terminator: %s\n", childAtom->getDisplayName()); + fTerminatorAtoms.insert(childAtom); + } + } + } + } + } +} void Linker::deadStripResolve() { @@ -1366,8 +1519,11 @@ void Linker::deadStripResolve() if ( entryPoint != NULL ) fLiveRootAtoms.insert(entryPoint); - // add dyld_stub_binding_helper() to live roots - ObjectFile::Atom* dyldHelper = this->dyldHelper(); + // add dyld_stub_binding_helper/dyld_stub_binder to live roots + ObjectFile::Atom* dyldHelper = this->dyldClassicHelper(); + if ( dyldHelper != NULL ) + fLiveRootAtoms.insert(dyldHelper); + dyldHelper = this->dyldCompressedHelper(); if ( dyldHelper != NULL ) fLiveRootAtoms.insert(dyldHelper); @@ -1408,7 +1564,7 @@ void Linker::deadStripResolve() for (std::set::iterator it=fLiveRootAtoms.begin(); it != fLiveRootAtoms.end(); it++) { WhyLiveBackChain rootChain; rootChain.previous = NULL; - rootChain.name = (*it)->getDisplayName(); + rootChain.referer = *it; markLive(**it, &rootChain); } @@ -1445,6 +1601,46 @@ void Linker::deadStripResolve() } } + // It is possible that some weak symbols were overridden by lazily load objects from archives + // and we have some atoms that still refer to the overridden ones. + // In that case we need to go back and rebind + if ( fAtomsOverriddenByLateLoads.size() > 0 ) { + for (std::set::iterator it=fLiveAtoms.begin(); it != fLiveAtoms.end(); ++it) { + ObjectFile::Atom* atom = *it; + std::vector& references = atom->getReferences(); + for (std::vector::iterator rit=references.begin(); rit != references.end(); ++rit) { + ObjectFile::Reference* reference = *rit; + ObjectFile::Atom* toTarget = &reference->getTarget(); + if ( fAtomsOverriddenByLateLoads.count(toTarget) ) { + //fprintf(stderr, "change reference in %p from %p to %p\n", atom, toTarget, fGlobalSymbolTable.find(toTarget->getName())); + reference->setTarget(*fGlobalSymbolTable.find(toTarget->getName()), reference->getTargetOffset()); + } + ObjectFile::Atom* fromTarget = &reference->getFromTarget(); + if ( (fromTarget != NULL) && fAtomsOverriddenByLateLoads.count(fromTarget) ) { + //fprintf(stderr, "change from reference in %p from %p to %p\n", atom, fromTarget, fGlobalSymbolTable.find(fromTarget->getName())); + reference->setTarget(*fGlobalSymbolTable.find(fromTarget->getName()), reference->getFromTargetOffset()); + } + } + } + + // make sure overriders are live if the atom they overrid was live + for (std::set::iterator it=fAtomsOverriddenByLateLoads.begin(); it != fAtomsOverriddenByLateLoads.end(); ++it) { + ObjectFile::Atom* overriderAtom = *it; + if ( fLiveAtoms.count(overriderAtom) ) { + WhyLiveBackChain rootChain; + rootChain.previous = NULL; + rootChain.referer = *it; + markLive(*fGlobalSymbolTable.find(overriderAtom->getName()), &rootChain); + } + } + + // remove overridden atoms from fLiveAtoms + fAllAtoms.erase(std::remove_if(fAllAtoms.begin(), fAllAtoms.end(), InSet(fAtomsOverriddenByLateLoads)), fAllAtoms.end()); + fAtomsOverriddenByLateLoads.clear(); + // remove dead atoms from fLiveAtoms + fAllAtoms.erase(std::remove_if(fAllAtoms.begin(), fAllAtoms.end(), InSet(fDeadAtoms)), fAllAtoms.end()); + } + // now remove all non-live atoms from fAllAtoms fAllAtoms.erase(std::remove_if(fAllAtoms.begin(), fAllAtoms.end(), NotLive(fLiveAtoms)), fAllAtoms.end()); } @@ -1485,36 +1681,6 @@ void Linker::checkObjC() } } -void Linker::addDtraceProbe(ObjectFile::Atom& atom, uint32_t offsetInAtom, const char* probeName) -{ - if ( probeName != NULL ) { - if ( strncmp(probeName, "___dtrace_probe$", 16) == 0 ) - fDtraceProbeSites.push_back(DTraceProbeInfo(&atom, offsetInAtom, probeName)); - else if ( strncmp(probeName, "___dtrace_isenabled$", 20) == 0 ) - fDtraceIsEnabledSites.push_back(DTraceProbeInfo(&atom, offsetInAtom, probeName)); - else if ( strncmp(probeName, "___dtrace_", 10) == 0 ) - fDtraceAtomToTypes[&atom].insert(probeName); - else if ( fOptions.dTrace() && (strncmp(probeName, "__dtrace_probe$", 15) == 0) ) - fDtraceProbes.push_back(DTraceProbeInfo(&atom, offsetInAtom, probeName)); - } -} - -static uint8_t pointerKind(cpu_type_t arch) -{ - switch ( arch ) { - case CPU_TYPE_POWERPC: - return ppc::kPointer; - case CPU_TYPE_POWERPC64: - return ppc64::kPointer; - case CPU_TYPE_I386: - return x86::kPointer; - case CPU_TYPE_X86_64: - return x86_64::kPointer; - case CPU_TYPE_ARM: - return arm::kPointer; - } - throw "uknown architecture"; -} static uint8_t pcRelKind(cpu_type_t arch) { @@ -1539,180 +1705,167 @@ typedef uint8_t* (*createdof_func_t)(cpu_type_t, unsigned int, const char*[], un void Linker::processDTrace() { - // handle dtrace 2.0 static probes - if ( (fOptions.outputKind() != Options::kObjectFile) && ((fDtraceProbeSites.size() != 0) || (fDtraceIsEnabledSites.size() != 0)) ) { - // partition probes by provider name - // The symbol names looks like: - // "___dtrace_isenabled$" provider-name "$" probe-name [ "$"... ] - // "___dtrace_probe$" provider-name "$" probe-name [ "$"... ] - ProviderToProbes providerToProbes; - std::vector emptyList; - for(std::vector::iterator it = fDtraceProbeSites.begin(); it != fDtraceProbeSites.end(); ++it) { - // ignore probes in functions that were coalesed away rdar://problem/5628149 - if ( fDeadAtoms.count((ObjectFile::Atom*)(it->atom)) == 0 ) { - const char* providerStart = &it->probeName[16]; - const char* providerEnd = strchr(providerStart, '$'); - if ( providerEnd != NULL ) { - char providerName[providerEnd-providerStart+1]; - strlcpy(providerName, providerStart, providerEnd-providerStart+1); - ProviderToProbes::iterator pos = providerToProbes.find(providerName); - if ( pos == providerToProbes.end() ) { - const char* dup = strdup(providerName); - providerToProbes[dup] = emptyList; - } - providerToProbes[providerName].push_back(*it); - } - } - } - for(std::vector::iterator it = fDtraceIsEnabledSites.begin(); it != fDtraceIsEnabledSites.end(); ++it) { - // ignore probes in functions that were coalesed away rdar://problem/5628149 - if ( fDeadAtoms.count((ObjectFile::Atom*)(it->atom)) == 0 ) { - const char* providerStart = &it->probeName[20]; - const char* providerEnd = strchr(providerStart, '$'); - if ( providerEnd != NULL ) { - char providerName[providerEnd-providerStart+1]; - strlcpy(providerName, providerStart, providerEnd-providerStart+1); - ProviderToProbes::iterator pos = providerToProbes.find(providerName); - if ( pos == providerToProbes.end() ) { - const char* dup = strdup(providerName); - providerToProbes[dup] = emptyList; - } - providerToProbes[providerName].push_back(*it); + // only make __dof section in final linked images + if ( fOptions.outputKind() == Options::kObjectFile ) + return; + + // scan all atoms looking for dtrace probes + std::vector probeSites; + std::vector isEnabledSites; + std::map atomToDtraceTypes; + for (std::vector::iterator it=fAllAtoms.begin(); it != fAllAtoms.end(); ++it) { + ObjectFile::Atom* atom = *it; + std::vector& references = atom->getReferences(); + for (std::vector::iterator rit=references.begin(); rit != references.end(); ++rit) { + ObjectFile::Reference* ref = *rit; + if ( ref->getTargetBinding() == ObjectFile::Reference::kDontBind ) { + const char* probeName = ref->getTargetName(); + if ( probeName != NULL ) { + uint32_t offsetInAtom = ref->getFixUpOffset(); + if ( strncmp(probeName, "___dtrace_probe$", 16) == 0 ) + probeSites.push_back(DTraceProbeInfo(atom, offsetInAtom, probeName)); + else if ( strncmp(probeName, "___dtrace_isenabled$", 20) == 0 ) + isEnabledSites.push_back(DTraceProbeInfo(atom, offsetInAtom, probeName)); + else if ( strncmp(probeName, "___dtrace_", 10) == 0 ) + atomToDtraceTypes[atom].insert(probeName); } } } - - // create a DOF section for each provider - int dofIndex=1; - CStringSet sectionNamesUsed; - for(ProviderToProbes::iterator pit = providerToProbes.begin(); pit != providerToProbes.end(); ++pit, ++dofIndex) { - const char* providerName = pit->first; - const std::vector& probes = pit->second; - - // open library and find dtrace_create_dof() - void* handle = dlopen("/usr/lib/libdtrace.dylib", RTLD_LAZY); - if ( handle == NULL ) - throwf("couldn't dlopen() /usr/lib/libdtrace.dylib: %s", dlerror()); - createdof_func_t pCreateDOF = (createdof_func_t)dlsym(handle, "dtrace_ld_create_dof"); - if ( pCreateDOF == NULL ) - throwf("couldn't find \"dtrace_ld_create_dof\" in /usr/lib/libdtrace.dylib: %s", dlerror()); - // build list of typedefs/stability infos for this provider - CStringSet types; - for(std::vector::const_iterator it = probes.begin(); it != probes.end(); ++it) { - std::map::iterator pos = fDtraceAtomToTypes.find(it->atom); - if ( pos != fDtraceAtomToTypes.end() ) { - for(CStringSet::iterator sit = pos->second.begin(); sit != pos->second.end(); ++sit) { - const char* providerStart = strchr(*sit, '$')+1; - const char* providerEnd = strchr(providerStart, '$'); - if ( providerEnd != NULL ) { - char aProviderName[providerEnd-providerStart+1]; - strlcpy(aProviderName, providerStart, providerEnd-providerStart+1); - if ( strcmp(aProviderName, providerName) == 0 ) - types.insert(*sit); - } - } - } - } - int typeCount = types.size(); - const char* typeNames[typeCount]; - //fprintf(stderr, "types for %s:\n", providerName); - uint32_t index = 0; - for(CStringSet::iterator it = types.begin(); it != types.end(); ++it) { - typeNames[index] = *it; - //fprintf(stderr, "\t%s\n", *it); - ++index; - } - - // build list of probe/isenabled sites - const uint32_t probeCount = probes.size(); - const char* probeNames[probeCount]; - const char* funtionNames[probeCount]; - uint64_t offsetsInDOF[probeCount]; - index = 0; - for(std::vector::const_iterator it = probes.begin(); it != probes.end(); ++it) { - probeNames[index] = it->probeName; - funtionNames[index] = it->atom->getName(); - offsetsInDOF[index] = 0; - ++index; - } - //fprintf(stderr, "calling libtrace to create DOF\n"); - //for(uint32_t i=0; i < probeCount; ++i) - // fprintf(stderr, " [%u]\t %s\t%s\n", i, probeNames[i], funtionNames[i]); - // call dtrace library to create DOF section - size_t dofSectionSize; - uint8_t* p = (*pCreateDOF)(fArchitecture, typeCount, typeNames, probeCount, probeNames, funtionNames, offsetsInDOF, &dofSectionSize); - if ( p != NULL ) { - char sectionName[18]; - strcpy(sectionName, "__dof_"); - strlcpy(§ionName[6], providerName, 10); - // create unique section name so each DOF is in its own section - if ( sectionNamesUsed.count(sectionName) != 0 ) { - sectionName[15] = '0'; - sectionName[16] = '\0'; - while ( sectionNamesUsed.count(sectionName) != 0 ) - ++sectionName[15]; - } - sectionNamesUsed.insert(sectionName); - char symbolName[strlen(providerName)+64]; - sprintf(symbolName, "__dtrace_dof_for_provider_%s", providerName); - opaque_section::Reader* reader = new opaque_section::Reader("__TEXT", sectionName, - "dtrace", p, dofSectionSize, fNextInputOrdinal, symbolName); - fNextInputOrdinal += dofSectionSize; - // add references - for (uint32_t i=0; i < probeCount; ++i) { - uint64_t offset = offsetsInDOF[i]; - //fprintf(stderr, "%s offset[%d]=0x%08llX\n", providerName, i, offset); - if ( offset > dofSectionSize ) - throwf("offsetsInDOF[i]=%0llX > dofSectionSize=%0lX\n", i, offset, dofSectionSize); - reader->addSectionReference(pcRelKind(fArchitecture), offset, probes[i].atom, probes[i].offset, reader->getAtoms()[0], 0); - } - this->addAtoms(reader->getAtoms()); - } - else { - throw "error creating dtrace DOF section"; + } + + // if no probes, we're done + if ( (probeSites.size() == 0) && (isEnabledSites.size() == 0) ) + return; + + // partition probes by provider name + // The symbol names looks like: + // "___dtrace_probe$" provider-name "$" probe-name [ "$"... ] + // "___dtrace_isenabled$" provider-name "$" probe-name [ "$"... ] + ProviderToProbes providerToProbes; + std::vector emptyList; + for(std::vector::iterator it = probeSites.begin(); it != probeSites.end(); ++it) { + // ignore probes in functions that were coalesed away rdar://problem/5628149 + if ( fDeadAtoms.count((ObjectFile::Atom*)(it->atom)) == 0 ) { + const char* providerStart = &it->probeName[16]; + const char* providerEnd = strchr(providerStart, '$'); + if ( providerEnd != NULL ) { + char providerName[providerEnd-providerStart+1]; + strlcpy(providerName, providerStart, providerEnd-providerStart+1); + ProviderToProbes::iterator pos = providerToProbes.find(providerName); + if ( pos == providerToProbes.end() ) { + const char* dup = strdup(providerName); + providerToProbes[dup] = emptyList; + } + providerToProbes[providerName].push_back(*it); + } + } + } + for(std::vector::iterator it = isEnabledSites.begin(); it != isEnabledSites.end(); ++it) { + // ignore probes in functions that were coalesed away rdar://problem/5628149 + if ( fDeadAtoms.count((ObjectFile::Atom*)(it->atom)) == 0 ) { + const char* providerStart = &it->probeName[20]; + const char* providerEnd = strchr(providerStart, '$'); + if ( providerEnd != NULL ) { + char providerName[providerEnd-providerStart+1]; + strlcpy(providerName, providerStart, providerEnd-providerStart+1); + ProviderToProbes::iterator pos = providerToProbes.find(providerName); + if ( pos == providerToProbes.end() ) { + const char* dup = strdup(providerName); + providerToProbes[dup] = emptyList; + } + providerToProbes[providerName].push_back(*it); } } } - // create a __DATA __dof section iff -dtrace option was used and static probes were found in .o files - else if ( fOptions.dTrace() && (fDtraceProbes.size() != 0) ) { - const uint32_t probeCount = fDtraceProbes.size(); - const char* labels[probeCount]; - const char* funtionNames[probeCount]; - uint64_t offsetsInDOF[probeCount]; - - // open libray and find dtrace_ld64_create_dof() + + // create a DOF section for each provider + int dofIndex=1; + CStringSet sectionNamesUsed; + for(ProviderToProbes::iterator pit = providerToProbes.begin(); pit != providerToProbes.end(); ++pit, ++dofIndex) { + const char* providerName = pit->first; + const std::vector& probes = pit->second; + + // open library and find dtrace_create_dof() void* handle = dlopen("/usr/lib/libdtrace.dylib", RTLD_LAZY); if ( handle == NULL ) - throwf("couldn't dlopen() /usr/lib/libdtrace.dylib: %s\n", dlerror()); - oldcreatedof_func_t pCreateDOF = (oldcreatedof_func_t)dlsym(handle, "dtrace_ld64_create_dof"); + throwf("couldn't dlopen() /usr/lib/libdtrace.dylib: %s", dlerror()); + createdof_func_t pCreateDOF = (createdof_func_t)dlsym(handle, "dtrace_ld_create_dof"); if ( pCreateDOF == NULL ) - throwf("couldn't find \"dtrace_ld64_create_dof\" in /usr/lib/libdtrace.dylib: %s\n", dlerror()); - - // build argument list + throwf("couldn't find \"dtrace_ld_create_dof\" in /usr/lib/libdtrace.dylib: %s", dlerror()); + // build list of typedefs/stability infos for this provider + CStringSet types; + for(std::vector::const_iterator it = probes.begin(); it != probes.end(); ++it) { + std::map::iterator pos = atomToDtraceTypes.find(it->atom); + if ( pos != atomToDtraceTypes.end() ) { + for(CStringSet::iterator sit = pos->second.begin(); sit != pos->second.end(); ++sit) { + const char* providerStart = strchr(*sit, '$')+1; + const char* providerEnd = strchr(providerStart, '$'); + if ( providerEnd != NULL ) { + char aProviderName[providerEnd-providerStart+1]; + strlcpy(aProviderName, providerStart, providerEnd-providerStart+1); + if ( strcmp(aProviderName, providerName) == 0 ) + types.insert(*sit); + } + } + } + } + int typeCount = types.size(); + const char* typeNames[typeCount]; + //fprintf(stderr, "types for %s:\n", providerName); uint32_t index = 0; - for(std::vector::iterator it = fDtraceProbes.begin(); it != fDtraceProbes.end(); ++it) { - labels[index] = it->probeName; + for(CStringSet::iterator it = types.begin(); it != types.end(); ++it) { + typeNames[index] = *it; + //fprintf(stderr, "\t%s\n", *it); + ++index; + } + + // build list of probe/isenabled sites + const uint32_t probeCount = probes.size(); + const char* probeNames[probeCount]; + const char* funtionNames[probeCount]; + uint64_t offsetsInDOF[probeCount]; + index = 0; + for(std::vector::const_iterator it = probes.begin(); it != probes.end(); ++it) { + probeNames[index] = it->probeName; funtionNames[index] = it->atom->getName(); offsetsInDOF[index] = 0; ++index; } - size_t dofSectionSize; + //fprintf(stderr, "calling libtrace to create DOF\n"); + //for(uint32_t i=0; i < probeCount; ++i) + // fprintf(stderr, " [%u]\t %s\t%s\n", i, probeNames[i], funtionNames[i]); // call dtrace library to create DOF section - uint8_t* p = (*pCreateDOF)(fOptions.dTraceScriptName(), fArchitecture, probeCount, labels, funtionNames, offsetsInDOF, &dofSectionSize); + size_t dofSectionSize; + uint8_t* p = (*pCreateDOF)(fArchitecture, typeCount, typeNames, probeCount, probeNames, funtionNames, offsetsInDOF, &dofSectionSize); if ( p != NULL ) { - opaque_section::Reader* reader = new opaque_section::Reader("__DATA", "__dof", "dtrace", p, dofSectionSize, fNextInputOrdinal); + char sectionName[18]; + strcpy(sectionName, "__dof_"); + strlcpy(§ionName[6], providerName, 10); + // create unique section name so each DOF is in its own section + if ( sectionNamesUsed.count(sectionName) != 0 ) { + sectionName[15] = '0'; + sectionName[16] = '\0'; + while ( sectionNamesUsed.count(sectionName) != 0 ) + ++sectionName[15]; + } + sectionNamesUsed.insert(sectionName); + char symbolName[strlen(providerName)+64]; + sprintf(symbolName, "__dtrace_dof_for_provider_%s", providerName); + opaque_section::Reader* reader = new opaque_section::Reader("__TEXT", sectionName, + "dtrace", p, dofSectionSize, fNextInputOrdinal, symbolName); fNextInputOrdinal += dofSectionSize; // add references for (uint32_t i=0; i < probeCount; ++i) { uint64_t offset = offsetsInDOF[i]; + //fprintf(stderr, "%s offset[%d]=0x%08llX\n", providerName, i, offset); if ( offset > dofSectionSize ) - throwf("offsetsInDOF[i]=%0llX > dofSectionSize=%0lX", i, offset, dofSectionSize); - reader->addSectionReference(pointerKind(fArchitecture), offset, fDtraceProbes[i].atom, fDtraceProbes[i].offset); + throwf("offsetsInDOF[i]=%0llX > dofSectionSize=%0lX\n", i, offset, dofSectionSize); + reader->addSectionReference(pcRelKind(fArchitecture), offset, probes[i].atom, probes[i].offset, reader->getAtoms()[0], 0); } this->addAtoms(reader->getAtoms()); } else { - throw "error created dtrace DOF section"; + throw "error creating dtrace DOF section"; } } } @@ -2040,11 +2193,11 @@ void Linker::sortAtoms() } // sort atoms - std::sort(fAllAtoms.begin(), fAllAtoms.end(), Linker::AtomSorter(ordinalOverrideMap)); + std::sort(fAllAtoms.begin(), fAllAtoms.end(), Linker::AtomSorter(ordinalOverrideMap, fInitializerAtoms, fTerminatorAtoms)); //fprintf(stderr, "Sorted atoms:\n"); //for (std::vector::iterator it=fAllAtoms.begin(); it != fAllAtoms.end(); it++) { - // fprintf(stderr, "\t%p, %u %s\n", (*it)->getSection(), (*it)->getSection()->getIndex(), (*it)->getDisplayName()); + // fprintf(stderr, "\t%p, %u %s\t%s\n", (*it)->getSection(), (*it)->getSection()->getIndex(), (*it)->getDisplayName(), (*it)->getFile()->getPath()); //} } @@ -2067,6 +2220,81 @@ void Linker::tweakLayout() atom->setSection(hugeZeroFills); } } + + // move all initializers to start of __text section + if ( fOptions.readerOptions().fAutoOrderInitializers ) { + // move -init function to front of __text + if ( fOptions.initFunctionName() != NULL ) { + ObjectFile::Atom* initAtom = fGlobalSymbolTable.find(fOptions.initFunctionName()); + if ( initAtom == NULL ) + throwf("could not find -init function: \"%s\"", fOptions.initFunctionName()); + moveToFrontOfSection(initAtom); + } + + // move all functions pointed to by __mod_init_func section to front of __text + Section* initSection = Section::find("__mod_init_func", "__DATA", false, false); + if ( initSection != NULL ) { + for (std::vector::iterator it=fAllAtoms.begin(); it != fAllAtoms.end(); ++it) { + if ( (*it)->getSection() == initSection ) { + std::vector& references = (*it)->getReferences(); + if ( references.size() == 1 ) + moveToFrontOfSection(&(references[0]->getTarget())); + } + } + } + } + + // move atoms with relocations to start of __DATA,__data section + // linker should order __DATA segment to reduce dyld dirtied pages + if ( fOptions.orderData() ) { + bool slideable = false; + switch ( fOptions.outputKind() ) { + case Options::kDynamicExecutable: + case Options::kStaticExecutable: + case Options::kDyld: + case Options::kPreload: + case Options::kObjectFile: + case Options::kKextBundle: + slideable = false; + break; + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + slideable = true; + break; + } + const bool hasPreferredLoadAddress = (fOptions.baseAddress() != 0); + Section* dataSection = Section::find("__data", "__DATA", false, false); + if ( dataSection != NULL ) { + for (std::vector::iterator it=fAllAtoms.begin(); it != fAllAtoms.end(); ++it) { + ObjectFile::Atom* dataAtom = *it; + if ( dataAtom->getSection() == dataSection ) { + std::vector& references = dataAtom->getReferences(); + if ( references.size() > 0 ) { + if ( slideable && !hasPreferredLoadAddress ) { + // in a slidable image dyld will need to rebase and bind so any references will need runtime fixups + // if image has preferred base address, assume it will load there and not rebase + moveToFrontOfSection(dataAtom); + } + else { + // in a non-slideable image, dyld will only do binding, so only references to + // symbols in another dylib will need runtime fixups + //fprintf(stderr, "reference from atom %s\n", dataAtom->getDisplayName()); + for (std::vector::iterator rit=references.begin(); rit != references.end(); rit++) { + ObjectFile::Reference* reference = *rit; + //fprintf(stderr, "\t%d %s\n", reference->getTarget().getDefinitionKind(), reference->getTarget().getDisplayName()); + if ( (reference->getTarget().getDefinitionKind() == ObjectFile::Atom::kExternalDefinition) + || (reference->getTarget().getDefinitionKind() == ObjectFile::Atom::kExternalWeakDefinition) ) { + moveToFrontOfSection(dataAtom); + break; + } + } + } + } + } + } + } + } + } @@ -2157,6 +2385,7 @@ ObjectFile::Atom* Linker::entryPoint(bool orInit) case Options::kDynamicExecutable: case Options::kStaticExecutable: case Options::kDyld: + case Options::kPreload: entryPoint = fGlobalSymbolTable.find(fOptions.entryName()); if ( entryPoint == NULL ) { throwf("could not find entry point \"%s\" (perhaps missing crt1.o)", fOptions.entryName()); @@ -2172,15 +2401,34 @@ ObjectFile::Atom* Linker::entryPoint(bool orInit) break; case Options::kObjectFile: case Options::kDynamicBundle: + case Options::kKextBundle: entryPoint = NULL; break; } return entryPoint; } -ObjectFile::Atom* Linker::dyldHelper() +ObjectFile::Atom* Linker::dyldClassicHelper() { - return fGlobalSymbolTable.find("dyld_stub_binding_helper"); + if ( fOptions.makeClassicDyldInfo() ) + return fGlobalSymbolTable.find("dyld_stub_binding_helper"); + else + return NULL; +} + +ObjectFile::Atom* Linker::dyldCompressedHelper() +{ + if ( fOptions.makeCompressedDyldInfo() ) { + // dyld_stub_binder is in libSystem.B.dylib + ObjectFile::Atom* atom = fGlobalSymbolTable.find("dyld_stub_binder"); + if ( atom == NULL ) { + this->addJustInTimeAtoms("dyld_stub_binder", true, false, true); + } + atom = fGlobalSymbolTable.find("dyld_stub_binder"); + return atom; + } + else + return NULL; } ObjectFile::Atom* Linker::dyldLazyLibraryHelper() @@ -2618,7 +2866,8 @@ void Linker::synthesizeDebugNotes(std::vector& allAtoms ObjectFile::Reader::Stab objStab; objStab.atom = NULL; objStab.type = N_OSO; - objStab.other = 0; + // linker should put cpusubtype in n_sect field of nlist entry for N_OSO debug note entries + objStab.other = atom->getFile()->updateCpuConstraint(0); objStab.desc = 1; objStab.value = useZeroOSOModTime ? 0 : atom->getFile()->getModificationTime(); objStab.string = assureFullPath(atom->getFile()->getPath()); @@ -2695,6 +2944,9 @@ void Linker::synthesizeDebugNotes(std::vector& allAtoms else if ( (strcmp(atom->getSectionName(), "__eh_frame") == 0) ) { // no stabs for .eh atoms } + else if ( (strncmp(atom->getName(), "__dtrace_probe$", 15) == 0) ) { + // no stabs for old style dtrace probes + } else { ObjectFile::Reader::Stab globalsStab; const char* name = atom->getName(); @@ -2846,9 +3098,10 @@ void Linker::writeOutput() fStartWriteTime = mach_absolute_time(); // tell writer about each segment's atoms fOutputFileSize = fOutputFile->write(fAllAtoms, fStabs, this->entryPoint(true), - this->dyldHelper(), this->dyldLazyLibraryHelper(), + this->dyldClassicHelper(),this->dyldCompressedHelper(), this->dyldLazyLibraryHelper(), fCreateUUID, fCanScatter, - fCurrentCpuConstraint, fBiggerThanTwoGigOutput, + fCurrentCpuConstraint, fBiggerThanTwoGigOutput, + fRegularDefAtomsThatOverrideADylibsWeakDef, fGlobalSymbolTable.hasExternalWeakDefinitions()); } @@ -2913,6 +3166,7 @@ ObjectFile::Reader* Linker::createReader(const Options::FileInfo& info) } ::close(fd); + bool objSubtypeMustMatch = (fOptions.preferSubArchitecture() && !fOptions.allowSubArchitectureMismatches()); switch (fArchitecture) { case CPU_TYPE_POWERPC: if ( mach_o::relocatable::Reader::validFile(p) ) @@ -2920,7 +3174,7 @@ ObjectFile::Reader* Linker::createReader(const Options::FileInfo& info) else if ( mach_o::dylib::Reader::validFile(p, info.options.fBundleLoader) ) return this->addDylib(new mach_o::dylib::Reader::Reader(p, len, info.path, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( archive::Reader::validFile(p, len) ) - return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); + return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); break; case CPU_TYPE_POWERPC64: if ( mach_o::relocatable::Reader::validFile(p) ) @@ -2928,7 +3182,7 @@ ObjectFile::Reader* Linker::createReader(const Options::FileInfo& info) else if ( mach_o::dylib::Reader::validFile(p, info.options.fBundleLoader) ) return this->addDylib(new mach_o::dylib::Reader::Reader(p, len, info.path, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( archive::Reader::validFile(p, len) ) - return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); + return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); break; case CPU_TYPE_I386: if ( mach_o::relocatable::Reader::validFile(p) ) @@ -2936,7 +3190,7 @@ ObjectFile::Reader* Linker::createReader(const Options::FileInfo& info) else if ( mach_o::dylib::Reader::validFile(p, info.options.fBundleLoader) ) return this->addDylib(new mach_o::dylib::Reader::Reader(p, len, info.path, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( archive::Reader::validFile(p, len) ) - return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); + return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); break; case CPU_TYPE_X86_64: if ( mach_o::relocatable::Reader::validFile(p) ) @@ -2944,15 +3198,14 @@ ObjectFile::Reader* Linker::createReader(const Options::FileInfo& info) else if ( mach_o::dylib::Reader::validFile(p, info.options.fBundleLoader) ) return this->addDylib(new mach_o::dylib::Reader::Reader(p, len, info.path, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( archive::Reader::validFile(p, len) ) - return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); + return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); case CPU_TYPE_ARM: - if ( mach_o::relocatable::Reader::validFile(p) ) - return this->addObject(new mach_o::relocatable::Reader::Reader(p, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); + if ( mach_o::relocatable::Reader::validFile(p, objSubtypeMustMatch, fOptions.subArchitecture()) ) + return this->addObject(new mach_o::relocatable::Reader::Reader(p, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( mach_o::dylib::Reader::validFile(p, info.options.fBundleLoader) ) return this->addDylib(new mach_o::dylib::Reader::Reader(p, len, info.path, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); else if ( archive::Reader::validFile(p, len) ) - return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, fOptions.readerOptions(), fNextInputOrdinal), info, len); - break; + return this->addArchive(new archive::Reader::Reader(p, len, info.path, info.modTime, info.options, fOptions.readerOptions(), fNextInputOrdinal), info, len); break; } @@ -3075,7 +3328,7 @@ void Linker::processDylibs() if ( childParent != NULL ) { if ( strcmp(childParent, &myLeaf[1]) == 0 ) { // set re-export bit of info - std::map::iterator pos = fDylibOptionsMap.find(reader); + std::map::iterator pos = fDylibOptionsMap.find(reader); if ( pos != fDylibOptionsMap.end() ) { pos->second.fReExport = true; } @@ -3105,8 +3358,8 @@ void Linker::createReaders() this->addInputFile(this->createReader(entry), entry); } catch (const char* msg) { - if ( strstr(msg, "architecture") != NULL ) { - if ( fOptions.ignoreOtherArchInputFiles() ) { + if ( (strstr(msg, "architecture") != NULL) && !fOptions.errorOnOtherArchFiles() ) { + if ( fOptions.ignoreOtherArchInputFiles() ) { // ignore, because this is about an architecture not in use } else { @@ -3225,12 +3478,25 @@ void Linker::checkDylibClientRestrictions(ObjectFile::Reader* reader) } } } - - } + ObjectFile::Reader* Linker::addDylib(ObjectFile::Reader* reader, const Options::FileInfo& info, uint64_t mappedLen) { + switch ( fOptions.outputKind() ) { + case Options::kDynamicExecutable: + case Options::kDynamicLibrary: + case Options::kDynamicBundle: + break; + case Options::kStaticExecutable: + case Options::kDyld: + case Options::kPreload: + case Options::kObjectFile: + case Options::kKextBundle: + warning("unexpected dylib (%s) on link line", reader->getPath()); + break; + } + fNextInputOrdinal += mappedLen; if ( (reader->getInstallPath() == NULL) && !info.options.fBundleLoader ) { // this is a "blank" stub @@ -3337,7 +3603,7 @@ void Linker::createWriter() if ( ! alreadyInDynamicLibraries ) { ExecutableFile::DyLibUsed dylibInfo; dylibInfo.reader = it->second; - std::map::iterator pos = fDylibOptionsMap.find(it->second); + std::map::iterator pos = fDylibOptionsMap.find(it->second); if ( pos != fDylibOptionsMap.end() ) { dylibInfo.options = pos->second; } @@ -3442,18 +3708,6 @@ bool Linker::SymbolTable::add(ObjectFile::Atom& newAtom) bool useNew = true; bool checkVisibilityMismatch = false; const char* name = newAtom.getName(); - if ( newAtom.getScope() == ObjectFile::Atom::scopeGlobal ) { - switch ( newAtom.getDefinitionKind() ) { - case ObjectFile::Atom::kTentativeDefinition: - fHasExternalTentativeDefinitions = true; - break; - case ObjectFile::Atom::kWeakDefinition: - fHasExternalWeakDefinitions = true; - break; - default: - break; - } - } //fprintf(stderr, "map.add(%s => %p from %s)\n", name, &newAtom, newAtom.getFile()->getPath()); Mapper::iterator pos = fTable.find(name); ObjectFile::Atom* existingAtom = NULL; @@ -3658,8 +3912,26 @@ bool Linker::SymbolTable::add(ObjectFile::Atom& newAtom) } if ( useNew ) { fTable[name] = &newAtom; - if ( existingAtom != NULL ) + if ( existingAtom != NULL ) { fOwner.markDead(existingAtom); + if ( fOwner.fInitialLoadsDone ) { + //fprintf(stderr, "existing %p %s overridden by %p\n", existingAtom, existingAtom->getName(), &newAtom); + fOwner.fAtomsOverriddenByLateLoads.insert(existingAtom); + } + } + if ( newAtom.getScope() == ObjectFile::Atom::scopeGlobal ) { + switch ( newAtom.getDefinitionKind() ) { + case ObjectFile::Atom::kTentativeDefinition: + fHasExternalTentativeDefinitions = true; + ++fRequireCount; // added a tentative definition means loadUndefines() needs to continue + break; + case ObjectFile::Atom::kWeakDefinition: + fHasExternalWeakDefinitions = true; + break; + default: + break; + } + } } else { fOwner.markDead(&newAtom); @@ -3679,15 +3951,27 @@ ObjectFile::Atom* Linker::SymbolTable::find(const char* name) } -void Linker::SymbolTable::getNeededNames(bool andWeakDefintions, std::vector& undefines) +void Linker::SymbolTable::getUndefinesNames(std::vector& undefines) { for (Mapper::iterator it=fTable.begin(); it != fTable.end(); it++) { - if ( (it->second == NULL) || (andWeakDefintions && (it->second->getDefinitionKind()==ObjectFile::Atom::kWeakDefinition)) ) { + if ( it->second == NULL ) { undefines.push_back(it->first); } } } +void Linker::SymbolTable::getTentativesNames(std::vector& tents) +{ + for (Mapper::iterator it=fTable.begin(); it != fTable.end(); it++) { + if ( it->second != NULL ) { + if ( (it->second->getDefinitionKind() == ObjectFile::Atom::kTentativeDefinition) + && (it->second->getScope() == ObjectFile::Atom::scopeGlobal) ) { + tents.push_back(it->first); + } + } + } +} + bool Linker::AtomSorter::operator()(const ObjectFile::Atom* left, const ObjectFile::Atom* right) @@ -3735,6 +4019,22 @@ bool Linker::AtomSorter::operator()(const ObjectFile::Atom* left, const ObjectFi if ( leftIsTent != rightIsTent ) return rightIsTent; + // initializers are auto sorted to start of section + if ( !fInitializerSet.empty() ) { + bool leftFirst = (fInitializerSet.count(left) != 0); + bool rightFirst = (fInitializerSet.count(right) != 0); + if ( leftFirst != rightFirst ) + return leftFirst; + } + + // terminators are auto sorted to end of section + if ( !fTerminatorSet.empty() ) { + bool leftLast = (fTerminatorSet.count(left) != 0); + bool rightLast = (fTerminatorSet.count(right) != 0); + if ( leftLast != rightLast ) + return rightLast; + } + // lastly sort by atom ordinal. this is already sorted by .o order return left->getOrdinal() < right->getOrdinal(); } diff --git a/src/ObjectDump.cpp b/src/other/ObjectDump.cpp old mode 100755 new mode 100644 similarity index 94% rename from src/ObjectDump.cpp rename to src/other/ObjectDump.cpp index e46cd3d..c2ae578 --- a/src/ObjectDump.cpp +++ b/src/other/ObjectDump.cpp @@ -294,7 +294,7 @@ static void dumpAtom(ObjectFile::Atom* atom) uint8_t content[size]; atom->copyRawContent(content); printf("content: "); - if ( strcmp(atom->getSectionName(), "__cstring") == 0 ) { + if ( atom->getContentType() == ObjectFile::Atom::kCStringType ) { printf("\""); for (unsigned int i=0; i < size; ++i) { if(content[i]<'!' || content[i]>=127) @@ -312,6 +312,16 @@ static void dumpAtom(ObjectFile::Atom* atom) printf("\n"); } + // unwind info + if(!sPrintRestrict) { + if ( atom->beginUnwind() != atom->endUnwind() ) { + printf("unwind encodings:\n"); + for (ObjectFile::UnwindInfo::iterator it = atom->beginUnwind(); it != atom->endUnwind(); ++it) { + printf("\t 0x%04X 0x%08X\n", it->startOffset, it->unwindInfo); + } + } + } + // references if(!sPrintRestrict) { std::vector& references = atom->getReferences(); @@ -344,7 +354,11 @@ struct AtomSorter { if ( left == right ) return false; - return (strcmp(left->getDisplayName(), right->getDisplayName()) < 0); + int name = strcmp(left->getDisplayName(), right->getDisplayName()); + if ( name == 0 ) + return (left->getSize() < right->getSize()); + else + return ( name < 0); } }; @@ -437,6 +451,7 @@ int main(int argc, const char* argv[]) } ObjectFile::ReaderOptions options; + options.fAddCompactUnwindEncoding = true; try { for(int i=1; i < argc; ++i) { const char* arg = argv[i]; @@ -463,6 +478,10 @@ int main(int argc, const char* argv[]) sPreferredArch = CPU_TYPE_I386; else if ( strcmp(arch, "x86_64") == 0 ) sPreferredArch = CPU_TYPE_X86_64; + else if ( strcmp(arch, "arm") == 0 ) + sPreferredArch = CPU_TYPE_ARM; + else if ( strcmp(arch, "armv6") == 0 ) + sPreferredArch = CPU_TYPE_ARM; else throwf("unknown architecture %s", arch); } diff --git a/src/other/PruneTrie.cpp b/src/other/PruneTrie.cpp new file mode 100644 index 0000000..766ae94 --- /dev/null +++ b/src/other/PruneTrie.cpp @@ -0,0 +1,100 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ +#include + +#include "MachOFileAbstraction.hpp" +#include "MachOTrie.hpp" +#include "prune_trie.h" + + + + +/* + * prune_trie() is a C vended function that is used by strip(1) to prune out + * defined exported symbols from the export trie. It is passed a pointer to + * the start of bytes of the the trie and the size. The prune() funciton + * passed is called with each symbol name in the trie to determine if it is + * to be pruned (retuning 1) or not (returning 0). It writes the new trie + * back into the trie buffer and returns the new size in trie_new_size. + * If the pruning succeeds, NULL is returned. If there was an error processing + * the trie (e.f. it is malformed), then an error message string is returned. + * The error string can be freed. + */ +const char* +prune_trie( + uint8_t* trie_start, + uint32_t trie_start_size, + int (*prune)(const char *name), + uint32_t* trie_new_size) +{ + // convert trie to vector of entries + std::vector originalExports; + try { + parseTrie(trie_start, trie_start+trie_start_size, originalExports); + } + catch (const char* msg) { + return strdup(msg); + } + catch (...) { + return strdup("unexpected exception processing trie"); + } + + // prune entries into new vector of entries + std::vector newExports; + newExports.reserve(originalExports.size()); + for(std::vector::iterator it = originalExports.begin(); it != originalExports.end(); ++it) { + if ( prune(it->name) == 0 ) + newExports.push_back(*it); + } + + // create new export trie + std::vector newExportTrieBytes; + newExportTrieBytes.reserve(trie_start_size); + mach_o::trie::makeTrie(newExports, newExportTrieBytes); + // Need to align trie to 8 or 4 bytes. We don't know the arch, but if the incoming trie + // was not 8-byte aligned, then it can't be a 64-bit arch, so use 4-byte alignement. + if ( (trie_start_size % 8) != 0 ) { + // 4-byte align + while ( (newExportTrieBytes.size() % 4 ) != 0) + newExportTrieBytes.push_back(0); + } + else { + // 8-byte align + while ( (newExportTrieBytes.size() % 8 ) != 0) + newExportTrieBytes.push_back(0); + } + + // copy into place, zero pad + *trie_new_size = newExportTrieBytes.size(); + if ( *trie_new_size > trie_start_size ) { + char* msg; + asprintf(&msg, "new trie is larger (%d) than original (%d)", *trie_new_size, trie_start_size); + return msg; + } + memcpy(trie_start, &newExportTrieBytes[0], *trie_new_size); + bzero(trie_start+*trie_new_size, trie_start_size - *trie_new_size); + + // success + return NULL; +} diff --git a/src/other/dyldinfo.cpp b/src/other/dyldinfo.cpp new file mode 100644 index 0000000..016fda3 --- /dev/null +++ b/src/other/dyldinfo.cpp @@ -0,0 +1,1460 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "MachOFileAbstraction.hpp" +#include "Architectures.hpp" +#include "MachOTrie.hpp" + +static bool printRebase = false; +static bool printBind = false; +static bool printWeakBind = false; +static bool printLazyBind = false; +static bool printOpcodes = false; +static bool printExport = false; +static bool printExportGraph = false; +static cpu_type_t sPreferredArch = CPU_TYPE_I386; + + + __attribute__((noreturn)) +void throwf(const char* format, ...) +{ + va_list list; + char* p; + va_start(list, format); + vasprintf(&p, format, list); + va_end(list); + + const char* t = p; + throw t; +} + + +template +class DyldInfoPrinter +{ +public: + static bool validFile(const uint8_t* fileContent); + static DyldInfoPrinter* make(const uint8_t* fileContent, uint32_t fileLength, const char* path) + { return new DyldInfoPrinter(fileContent, fileLength, path); } + virtual ~DyldInfoPrinter() {} + + +private: + typedef typename A::P P; + typedef typename A::P::E E; + typedef typename A::P::uint_t pint_t; + + class CStringEquals + { + public: + bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); } + }; + + typedef __gnu_cxx::hash_set, CStringEquals> StringSet; + + DyldInfoPrinter(const uint8_t* fileContent, uint32_t fileLength, const char* path); + void printRebaseInfo(); + void printRebaseInfoOpcodes(); + void printBindingInfo(); + void printWeakBindingInfo(); + void printLazyBindingInfo(); + void printBindingInfoOpcodes(bool weakBinding); + void printWeakBindingInfoOpcodes(); + void printLazyBindingOpcodes(); + void printExportInfo(); + void printExportInfoGraph(); + void processExportNode(const uint8_t* const start, const uint8_t* p, const uint8_t* const end, + char* cummulativeString, int curStrOffset); + void processExportGraphNode(const uint8_t* const start, const uint8_t* const end, + const uint8_t* parent, const uint8_t* p, + char* cummulativeString, int curStrOffset); + const char* rebaseTypeName(uint8_t type); + const char* bindTypeName(uint8_t type); + pint_t segStartAddress(uint8_t segIndex); + const char* segmentName(uint8_t segIndex); + const char* sectionName(uint8_t segIndex, pint_t address); + const char* getSegAndSectName(uint8_t segIndex, pint_t address); + const char* ordinalName(int libraryOrdinal); + + + const char* fPath; + const macho_header

* fHeader; + uint64_t fLength; + const char* fStrings; + const char* fStringsEnd; + const macho_nlist

* fSymbols; + uint32_t fSymbolCount; + const macho_dyld_info_command

* fInfo; + uint64_t fBaseAddress; + std::vector*>fSegments; + std::vector fDylibs; +}; + + + +template <> +bool DyldInfoPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_POWERPC ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool DyldInfoPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC_64 ) + return false; + if ( header->cputype() != CPU_TYPE_POWERPC64 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool DyldInfoPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_I386 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool DyldInfoPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC_64 ) + return false; + if ( header->cputype() != CPU_TYPE_X86_64 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool DyldInfoPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_ARM ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + + +template +DyldInfoPrinter::DyldInfoPrinter(const uint8_t* fileContent, uint32_t fileLength, const char* path) + : fHeader(NULL), fLength(fileLength), + fStrings(NULL), fStringsEnd(NULL), fSymbols(NULL), fSymbolCount(0), fInfo(NULL), fBaseAddress(0) +{ + // sanity check + if ( ! validFile(fileContent) ) + throw "not a mach-o file that can be checked"; + + fPath = strdup(path); + fHeader = (const macho_header

*)fileContent; + + // get LC_DYLD_INFO + const uint8_t* const endOfFile = (uint8_t*)fHeader + fLength; + const uint8_t* const endOfLoadCommands = (uint8_t*)fHeader + sizeof(macho_header

) + fHeader->sizeofcmds(); + const uint32_t cmd_count = fHeader->ncmds(); + const macho_load_command

* const cmds = (macho_load_command

*)((uint8_t*)fHeader + sizeof(macho_header

)); + const macho_load_command

* cmd = cmds; + for (uint32_t i = 0; i < cmd_count; ++i) { + uint32_t size = cmd->cmdsize(); + const uint8_t* endOfCmd = ((uint8_t*)cmd)+cmd->cmdsize(); + if ( endOfCmd > endOfLoadCommands ) + throwf("load command #%d extends beyond the end of the load commands", i); + if ( endOfCmd > endOfFile ) + throwf("load command #%d extends beyond the end of the file", i); + switch ( cmd->cmd() ) { + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: + fInfo = (macho_dyld_info_command

*)cmd; + break; + case macho_segment_command

::CMD: + { + const macho_segment_command

* segCmd = (const macho_segment_command

*)cmd; + fSegments.push_back(segCmd); + if ( (segCmd->fileoff() == 0) && (segCmd->filesize() != 0) ) + fBaseAddress = segCmd->vmaddr(); + } + break; + case LC_LOAD_DYLIB: + case LC_LOAD_WEAK_DYLIB: + case LC_REEXPORT_DYLIB: + case LC_LAZY_LOAD_DYLIB: + { + const macho_dylib_command

* dylib = (macho_dylib_command

*)cmd; + const char* lastSlash = strrchr(dylib->name(), '/'); + const char* leafName = (lastSlash != NULL) ? lastSlash+1 : dylib->name(); + const char* firstDot = strchr(leafName, '.'); + if ( firstDot != NULL ) { + char* t = strdup(leafName); + t[firstDot-leafName] = '\0'; + fDylibs.push_back(t); + } + else { + fDylibs.push_back(leafName); + } + } + break; + } + cmd = (const macho_load_command

*)endOfCmd; + } + + if ( printRebase ) + printRebaseInfo(); + if ( printBind ) + printBindingInfo(); + if ( printWeakBind ) + printWeakBindingInfo(); + if ( printLazyBind ) + printLazyBindingInfo(); + if ( printExport ) + printExportInfo(); + if ( printOpcodes ) { + printRebaseInfoOpcodes(); + printBindingInfoOpcodes(false); + printBindingInfoOpcodes(true); + printLazyBindingOpcodes(); + } + if ( printExportGraph ) + printExportInfoGraph(); +} + +static uint64_t read_uleb128(const uint8_t*& p, const uint8_t* end) +{ + uint64_t result = 0; + int bit = 0; + do { + if (p == end) + throwf("malformed uleb128"); + + uint64_t slice = *p & 0x7f; + + if (bit >= 64 || slice << bit >> bit != slice) + throwf("uleb128 too big"); + else { + result |= (slice << bit); + bit += 7; + } + } + while (*p++ & 0x80); + return result; +} + +static int64_t read_sleb128(const uint8_t*& p, const uint8_t* end) +{ + int64_t result = 0; + int bit = 0; + uint8_t byte; + do { + if (p == end) + throwf("malformed sleb128"); + byte = *p++; + result |= ((byte & 0x7f) << bit); + bit += 7; + } while (byte & 0x80); + // sign extend negative numbers + if ( (byte & 0x40) != 0 ) + result |= (-1LL) << bit; + return result; +} + + +template +const char* DyldInfoPrinter::rebaseTypeName(uint8_t type) +{ + switch (type ){ + case REBASE_TYPE_POINTER: + return "pointer"; + case REBASE_TYPE_TEXT_ABSOLUTE32: + return "text abs32"; + case REBASE_TYPE_TEXT_PCREL32: + return "text rel32"; + } + return "!!unknown!!"; +} + + +template +const char* DyldInfoPrinter::bindTypeName(uint8_t type) +{ + switch (type ){ + case BIND_TYPE_POINTER: + return "pointer"; + case BIND_TYPE_TEXT_ABSOLUTE32: + return "text abs32"; + case BIND_TYPE_TEXT_PCREL32: + return "text rel32"; + } + return "!!unknown!!"; +} + + +template +typename A::P::uint_t DyldInfoPrinter::segStartAddress(uint8_t segIndex) +{ + if ( segIndex > fSegments.size() ) + throw "segment index out of range"; + return fSegments[segIndex]->vmaddr(); +} + +template +const char* DyldInfoPrinter::segmentName(uint8_t segIndex) +{ + if ( segIndex > fSegments.size() ) + throw "segment index out of range"; + return fSegments[segIndex]->segname(); +} + +template +const char* DyldInfoPrinter::sectionName(uint8_t segIndex, pint_t address) +{ + if ( segIndex > fSegments.size() ) + throw "segment index out of range"; + const macho_segment_command

* segCmd = fSegments[segIndex]; + macho_section

* const sectionsStart = (macho_section

*)((char*)segCmd + sizeof(macho_segment_command

)); + macho_section

* const sectionsEnd = §ionsStart[segCmd->nsects()]; + for(macho_section

* sect = sectionsStart; sect < sectionsEnd; ++sect) { + if ( (sect->addr() <= address) && (address < (sect->addr()+sect->size())) ) { + if ( strlen(sect->sectname()) > 15 ) { + static char temp[18]; + strlcpy(temp, sect->sectname(), 17); + return temp; + } + else { + return sect->sectname(); + } + } + } + return "??"; +} + +template +const char* DyldInfoPrinter::getSegAndSectName(uint8_t segIndex, pint_t address) +{ + static char buffer[64]; + strcpy(buffer, segmentName(segIndex)); + strcat(buffer, "/"); + const macho_segment_command

* segCmd = fSegments[segIndex]; + macho_section

* const sectionsStart = (macho_section

*)((char*)segCmd + sizeof(macho_segment_command

)); + macho_section

* const sectionsEnd = §ionsStart[segCmd->nsects()]; + for(macho_section

* sect = sectionsStart; sect < sectionsEnd; ++sect) { + if ( (sect->addr() <= address) && (address < (sect->addr()+sect->size())) ) { + // section name may not be zero terminated + char* end = &buffer[strlen(buffer)]; + strlcpy(end, sect->sectname(), 16); + return buffer; + } + } + return "??"; +} + +template +const char* DyldInfoPrinter::ordinalName(int libraryOrdinal) +{ + switch ( libraryOrdinal) { + case BIND_SPECIAL_DYLIB_SELF: + return "this-image"; + case BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: + return "main-executable"; + case BIND_SPECIAL_DYLIB_FLAT_LOOKUP: + return "flat-namespace"; + } + if ( libraryOrdinal < BIND_SPECIAL_DYLIB_FLAT_LOOKUP ) + throw "unknown special ordinal"; + if ( libraryOrdinal > fDylibs.size() ) + throw "libraryOrdinal out of range"; + return fDylibs[libraryOrdinal-1]; +} + + +template +void DyldInfoPrinter::printRebaseInfo() +{ + if ( (fInfo == NULL) || (fInfo->rebase_off() == 0) ) { + printf("no compressed rebase info\n"); + } + else { + printf("rebase information:\n"); + printf("segment section address type\n"); + + const uint8_t* p = (uint8_t*)fHeader + fInfo->rebase_off(); + const uint8_t* end = &p[fInfo->rebase_size()]; + + uint8_t type = 0; + uint64_t segOffset = 0; + uint32_t count; + uint32_t skip; + int segIndex; + pint_t segStartAddr = 0; + const char* segName = "??"; + const char* typeName = "??"; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & REBASE_IMMEDIATE_MASK; + uint8_t opcode = *p & REBASE_OPCODE_MASK; + ++p; + switch (opcode) { + case REBASE_OPCODE_DONE: + done = true; + break; + case REBASE_OPCODE_SET_TYPE_IMM: + type = immediate; + typeName = rebaseTypeName(type); + break; + case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segIndex = immediate; + segStartAddr = segStartAddress(segIndex); + segName = segmentName(segIndex); + segOffset = read_uleb128(p, end); + break; + case REBASE_OPCODE_ADD_ADDR_ULEB: + segOffset += read_uleb128(p, end); + break; + case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: + segOffset += immediate*sizeof(pint_t); + break; + case REBASE_OPCODE_DO_REBASE_IMM_TIMES: + for (int i=0; i < immediate; ++i) { + printf("%-7s %-16s 0x%08llX %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName); + segOffset += sizeof(pint_t); + } + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: + count = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + printf("%-7s %-16s 0x%08llX %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName); + segOffset += sizeof(pint_t); + } + break; + case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: + printf("%-7s %-16s 0x%08llX %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName); + segOffset += read_uleb128(p, end) + sizeof(pint_t); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + printf("%-7s %-16s 0x%08llX %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName); + segOffset += skip + sizeof(pint_t); + } + break; + default: + throwf("bad rebase opcode %d", *p); + } + } + } + +} + + + +template +void DyldInfoPrinter::printRebaseInfoOpcodes() +{ + if ( (fInfo == NULL) || (fInfo->rebase_off() == 0) ) { + printf("no compressed rebase info\n"); + } + else { + printf("rebase opcodes:\n"); + const uint8_t* p = (uint8_t*)fHeader + fInfo->rebase_off(); + const uint8_t* end = &p[fInfo->rebase_size()]; + + uint8_t type = 0; + uint64_t address = fBaseAddress; + uint32_t count; + uint32_t skip; + unsigned int segmentIndex; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & REBASE_IMMEDIATE_MASK; + uint8_t opcode = *p & REBASE_OPCODE_MASK; + ++p; + switch (opcode) { + case REBASE_OPCODE_DONE: + done = true; + printf("REBASE_OPCODE_DONE()\n"); + break; + case REBASE_OPCODE_SET_TYPE_IMM: + type = immediate; + printf("REBASE_OPCODE_SET_TYPE_IMM(%d)\n", type); + break; + case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segmentIndex = immediate; + address = read_uleb128(p, end); + printf("REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%d, 0x%08llX)\n", segmentIndex, address); + break; + case REBASE_OPCODE_ADD_ADDR_ULEB: + address = read_uleb128(p, end); + printf("REBASE_OPCODE_ADD_ADDR_ULEB(0x%0llX)\n", address); + break; + case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: + address = immediate*sizeof(pint_t); + printf("REBASE_OPCODE_ADD_ADDR_IMM_SCALED(0x%0llX)\n", address); + break; + case REBASE_OPCODE_DO_REBASE_IMM_TIMES: + printf("REBASE_OPCODE_DO_REBASE_IMM_TIMES(%d)\n", immediate); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: + count = read_uleb128(p, end); + printf("REBASE_OPCODE_DO_REBASE_ULEB_TIMES(%d)\n", count); + break; + case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: + skip = read_uleb128(p, end) + sizeof(pint_t); + printf("REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB(%d)\n", skip); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + printf("REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB(%d, %d)\n", count, skip); + break; + default: + throwf("bad rebase opcode %d", *p); + } + } + } + +} + + + + + + +template +void DyldInfoPrinter::printBindingInfoOpcodes(bool weakbinding) +{ + if ( fInfo == NULL ) { + printf("no compressed binding info\n"); + } + else if ( !weakbinding && (fInfo->bind_off() == 0) ) { + printf("no compressed binding info\n"); + } + else if ( weakbinding && (fInfo->weak_bind_off() == 0) ) { + printf("no compressed weak binding info\n"); + } + else { + const uint8_t* start; + const uint8_t* end; + if ( weakbinding ) { + printf("weak binding opcodes:\n"); + start = (uint8_t*)fHeader + fInfo->weak_bind_off(); + end = &start[fInfo->weak_bind_size()]; + } + else { + printf("binding opcodes:\n"); + start = (uint8_t*)fHeader + fInfo->bind_off(); + end = &start[fInfo->bind_size()]; + } + const uint8_t* p = start; + uint8_t type = 0; + uint8_t flags; + uint64_t address = fBaseAddress; + const char* symbolName = NULL; + int libraryOrdinal = 0; + int64_t addend = 0; + uint32_t segmentIndex = 0; + uint32_t count; + uint32_t skip; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + uint32_t opcodeOffset = p-start; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + done = true; + printf("0x%04X BIND_OPCODE_DONE\n", opcodeOffset); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + libraryOrdinal = immediate; + printf("0x%04X BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + libraryOrdinal = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // the special ordinals are negative numbers + if ( immediate == 0 ) + libraryOrdinal = 0; + else { + int8_t signExtended = BIND_OPCODE_MASK | immediate; + libraryOrdinal = signExtended; + } + printf("0x%04X BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + flags = immediate; + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + printf("0x%04X BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%02X, %s)\n", opcodeOffset, flags, symbolName); + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + printf("0x%04X BIND_OPCODE_SET_TYPE_IMM(%d)\n", opcodeOffset, type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", opcodeOffset, addend); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segmentIndex = immediate; + address = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(0x%02X, 0x%08llX)\n", opcodeOffset, segmentIndex, address); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND: + printf("0x%04X BIND_OPCODE_DO_BIND()\n", opcodeOffset); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + skip = immediate*sizeof(pint_t) + sizeof(pint_t); + printf("0x%04X BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%d, 0x%08X)\n", opcodeOffset, count, skip); + break; + default: + throwf("unknown bind opcode %d", *p); + } + } + } + +} + + + +template +void DyldInfoPrinter::printBindingInfo() +{ + if ( (fInfo == NULL) || (fInfo->bind_off() == 0) ) { + printf("no compressed binding info\n"); + } + else { + printf("bind information:\n"); + printf("segment section address type weak addend dylib symbol\n"); + const uint8_t* p = (uint8_t*)fHeader + fInfo->bind_off(); + const uint8_t* end = &p[fInfo->bind_size()]; + + uint8_t type = 0; + uint8_t segIndex = 0; + uint64_t segOffset = 0; + const char* symbolName = NULL; + const char* fromDylib = "??"; + int libraryOrdinal = 0; + int64_t addend = 0; + uint32_t count; + uint32_t skip; + pint_t segStartAddr = 0; + const char* segName = "??"; + const char* typeName = "??"; + const char* weak_import = ""; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + done = true; + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + libraryOrdinal = immediate; + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + libraryOrdinal = read_uleb128(p, end); + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // the special ordinals are negative numbers + if ( immediate == 0 ) + libraryOrdinal = 0; + else { + int8_t signExtended = BIND_OPCODE_MASK | immediate; + libraryOrdinal = signExtended; + } + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + if ( (immediate & BIND_SYMBOL_FLAGS_WEAK_IMPORT) != 0 ) + weak_import = "weak"; + else + weak_import = ""; + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + typeName = bindTypeName(type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segIndex = immediate; + segStartAddr = segStartAddress(segIndex); + segName = segmentName(segIndex); + segOffset = read_uleb128(p, end); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + segOffset += read_uleb128(p, end); + break; + case BIND_OPCODE_DO_BIND: + printf("%-7s %-16s 0x%08llX %10s %4s %5lld %-16s %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, weak_import, addend, fromDylib, symbolName ); + segOffset += sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + printf("%-7s %-16s 0x%08llX %10s %4s %5lld %-16s %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, weak_import, addend, fromDylib, symbolName ); + segOffset += read_uleb128(p, end) + sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + printf("%-7s %-16s 0x%08llX %10s %4s %5lld %-16s %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, weak_import, addend, fromDylib, symbolName ); + segOffset += immediate*sizeof(pint_t) + sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + printf("%-7s %-16s 0x%08llX %10s %4s %5lld %-16s %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, weak_import, addend, fromDylib, symbolName ); + segOffset += skip + sizeof(pint_t); + } + break; + default: + throwf("bad bind opcode %d", *p); + } + } + } + +} + +template +void DyldInfoPrinter::printWeakBindingInfo() +{ + if ( (fInfo == NULL) || (fInfo->weak_bind_off() == 0) ) { + printf("no weak binding\n"); + } + else { + printf("weak binding information:\n"); + printf("segment section address type addend symbol\n"); + const uint8_t* p = (uint8_t*)fHeader + fInfo->weak_bind_off(); + const uint8_t* end = &p[fInfo->weak_bind_size()]; + + uint8_t type = 0; + uint8_t segIndex = 0; + uint64_t segOffset = 0; + const char* symbolName = NULL; + int64_t addend = 0; + uint32_t count; + uint32_t skip; + pint_t segStartAddr = 0; + const char* segName = "??"; + const char* typeName = "??"; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + done = true; + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + if ( (immediate & BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) != 0 ) + printf(" strong %s\n", symbolName ); + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + typeName = bindTypeName(type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segIndex = immediate; + segStartAddr = segStartAddress(segIndex); + segName = segmentName(segIndex); + segOffset = read_uleb128(p, end); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + segOffset += read_uleb128(p, end); + break; + case BIND_OPCODE_DO_BIND: + printf("%-7s %-16s 0x%08llX %10s %5lld %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, addend, symbolName ); + segOffset += sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + printf("%-7s %-16s 0x%08llX %10s %5lld %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, addend, symbolName ); + segOffset += read_uleb128(p, end) + sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + printf("%-7s %-16s 0x%08llX %10s %5lld %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, addend, symbolName ); + segOffset += immediate*sizeof(pint_t) + sizeof(pint_t); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + printf("%-7s %-16s 0x%08llX %10s %5lld %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, typeName, addend, symbolName ); + segOffset += skip + sizeof(pint_t); + } + break; + default: + throwf("unknown weak bind opcode %d", *p); + } + } + } + +} + + +template +void DyldInfoPrinter::printLazyBindingInfo() +{ + if ( fInfo == NULL ) { + printf("no compressed dyld info\n"); + } + else if ( fInfo->lazy_bind_off() == 0 ) { + printf("no compressed lazy binding info\n"); + } + else { + printf("lazy binding information:\n"); + printf("segment section address index dylib symbol\n"); + const uint8_t* const start = (uint8_t*)fHeader + fInfo->lazy_bind_off(); + const uint8_t* const end = &start[fInfo->lazy_bind_size()]; + + uint8_t type = BIND_TYPE_POINTER; + uint8_t segIndex = 0; + uint64_t segOffset = 0; + const char* symbolName = NULL; + const char* fromDylib = "??"; + int libraryOrdinal = 0; + int64_t addend = 0; + uint32_t lazy_offset = 0; + pint_t segStartAddr = 0; + const char* segName = "??"; + const char* typeName = "??"; + for (const uint8_t* p=start; p < end; ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + lazy_offset = p-start; + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + libraryOrdinal = immediate; + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + libraryOrdinal = read_uleb128(p, end); + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // the special ordinals are negative numbers + if ( immediate == 0 ) + libraryOrdinal = 0; + else { + int8_t signExtended = BIND_OPCODE_MASK | immediate; + libraryOrdinal = signExtended; + } + fromDylib = ordinalName(libraryOrdinal); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + typeName = bindTypeName(type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segIndex = immediate; + segStartAddr = segStartAddress(segIndex); + segName = segmentName(segIndex); + segOffset = read_uleb128(p, end); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + segOffset += read_uleb128(p, end); + break; + case BIND_OPCODE_DO_BIND: + printf("%-7s %-16s 0x%08llX 0x%04X %-16s %s\n", segName, sectionName(segIndex, segStartAddr+segOffset), segStartAddr+segOffset, lazy_offset, fromDylib, symbolName ); + segOffset += sizeof(pint_t); + break; + default: + throwf("bad lazy bind opcode %d", *p); + } + } + } + +} + +#if 0 + uint8_t type = BIND_TYPE_POINTER; + uint8_t flags; + uint64_t address = fBaseAddress; + const char* symbolName = NULL; + int libraryOrdinal = 0; + int64_t addend = 0; + uint32_t segmentIndex = 0; + uint32_t count; + uint32_t skip; + for (const uint8_t* p = start; p < end; ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + uint32_t opcodeOffset = p-start; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + printf("0x%08X BIND_OPCODE_DONE\n", opcodeOffset); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + libraryOrdinal = immediate; + printf("0x%08X BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + libraryOrdinal = read_uleb128(p, end); + printf("0x%08X BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // the special ordinals are negative numbers + if ( immediate == 0 ) + libraryOrdinal = 0; + else { + int8_t signExtended = BIND_OPCODE_MASK | immediate; + libraryOrdinal = signExtended; + } + printf("0x%08X BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + flags = immediate; + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + printf("0x%08X BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%02X, %s)\n", opcodeOffset, flags, symbolName); + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + printf("0x%08X BIND_OPCODE_SET_TYPE_IMM(%d)\n", opcodeOffset, type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + printf("0x%08X BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", opcodeOffset, addend); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segmentIndex = immediate; + address = read_uleb128(p, end); + printf("0x%08X BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(0x%02X, 0x%08llX)\n", opcodeOffset, segmentIndex, address); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%08X BIND_OPCODE_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND: + printf("0x%08X BIND_OPCODE_DO_BIND()\n", opcodeOffset); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%08X BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + skip = immediate*sizeof(pint_t) + sizeof(pint_t); + printf("0x%08X BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + printf("0x%08X BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%d, 0x%08X)\n", opcodeOffset, count, skip); + break; + default: + throwf("unknown bind opcode %d", *p); + } + } +#endif + +template +void DyldInfoPrinter::printLazyBindingOpcodes() +{ + if ( fInfo == NULL ) { + printf("no compressed dyld info\n"); + } + else if ( fInfo->lazy_bind_off() == 0 ) { + printf("no compressed lazy binding info\n"); + } + else { + printf("lazy binding opcodes:\n"); + const uint8_t* const start = (uint8_t*)fHeader + fInfo->lazy_bind_off(); + const uint8_t* const end = &start[fInfo->lazy_bind_size()]; + uint8_t type = BIND_TYPE_POINTER; + uint8_t flags; + uint64_t address = fBaseAddress; + const char* symbolName = NULL; + int libraryOrdinal = 0; + int64_t addend = 0; + uint32_t segmentIndex = 0; + uint32_t count; + uint32_t skip; + for (const uint8_t* p = start; p < end; ) { + uint8_t immediate = *p & BIND_IMMEDIATE_MASK; + uint8_t opcode = *p & BIND_OPCODE_MASK; + uint32_t opcodeOffset = p-start; + ++p; + switch (opcode) { + case BIND_OPCODE_DONE: + printf("0x%04X BIND_OPCODE_DONE\n", opcodeOffset); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: + libraryOrdinal = immediate; + printf("0x%04X BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: + libraryOrdinal = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: + // the special ordinals are negative numbers + if ( immediate == 0 ) + libraryOrdinal = 0; + else { + int8_t signExtended = BIND_OPCODE_MASK | immediate; + libraryOrdinal = signExtended; + } + printf("0x%04X BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%d)\n", opcodeOffset, libraryOrdinal); + break; + case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: + flags = immediate; + symbolName = (char*)p; + while (*p != '\0') + ++p; + ++p; + printf("0x%04X BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%02X, %s)\n", opcodeOffset, flags, symbolName); + break; + case BIND_OPCODE_SET_TYPE_IMM: + type = immediate; + printf("0x%04X BIND_OPCODE_SET_TYPE_IMM(%d)\n", opcodeOffset, type); + break; + case BIND_OPCODE_SET_ADDEND_SLEB: + addend = read_sleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", opcodeOffset, addend); + break; + case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segmentIndex = immediate; + address = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(0x%02X, 0x%08llX)\n", opcodeOffset, segmentIndex, address); + break; + case BIND_OPCODE_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND: + printf("0x%04X BIND_OPCODE_DO_BIND()\n", opcodeOffset); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: + skip = immediate*sizeof(pint_t) + sizeof(pint_t); + printf("0x%04X BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(0x%08X)\n", opcodeOffset, skip); + break; + case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + printf("0x%04X BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%d, 0x%08X)\n", opcodeOffset, count, skip); + break; + default: + throwf("unknown bind opcode %d", *p); + } + } + } + +} + + +template +void DyldInfoPrinter::processExportNode(const uint8_t* const start, const uint8_t* p, const uint8_t* const end, + char* cummulativeString, int curStrOffset) +{ + const uint8_t terminalSize = *p++; + const uint8_t* children = p + terminalSize; + if ( terminalSize != 0 ) { + uint32_t flags = read_uleb128(p, end); + uint64_t address = read_uleb128(p, end); + if ( flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION ) + fprintf(stdout, "0x%08llX [weak_def] %s\n", address, cummulativeString); + else + fprintf(stdout, "0x%08llX %s\n", address, cummulativeString); + } + const uint8_t childrenCount = *children++; + const uint8_t* s = children; + for (uint8_t i=0; i < childrenCount; ++i) { + int edgeStrLen = 0; + while (*s != '\0') { + cummulativeString[curStrOffset+edgeStrLen] = *s++; + ++edgeStrLen; + } + cummulativeString[curStrOffset+edgeStrLen] = *s++; + uint32_t childNodeOffet = read_uleb128(s, end); + processExportNode(start, start+childNodeOffet, end, cummulativeString, curStrOffset+edgeStrLen); + } +} + +struct SortExportsByAddress +{ + bool operator()(const mach_o::trie::Entry& left, const mach_o::trie::Entry& right) + { + return ( left.address < right.address ); + } +}; + +template +void DyldInfoPrinter::printExportInfo() +{ + if ( (fInfo == NULL) || (fInfo->export_off() == 0) ) { + printf("no compressed export info\n"); + } + else { + const uint8_t* start = (uint8_t*)fHeader + fInfo->export_off(); + const uint8_t* end = &start[fInfo->export_size()]; + std::vector list; + parseTrie(start, end, list); + //std::sort(list.begin(), list.end(), SortExportsByAddress()); + for (std::vector::iterator it=list.begin(); it != list.end(); ++it) { + const char* flags = ""; + if ( it->flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION ) + flags = "[weak_def] "; + fprintf(stdout, "0x%08llX %s%s\n", fBaseAddress+it->address, flags, it->name); + } + } +} + + +template +void DyldInfoPrinter::processExportGraphNode(const uint8_t* const start, const uint8_t* const end, + const uint8_t* parent, const uint8_t* p, + char* cummulativeString, int curStrOffset) +{ + const uint8_t* const me = p; + const uint8_t terminalSize = *p++; + const uint8_t* children = p + terminalSize; + if ( terminalSize != 0 ) { + uint32_t flags = read_uleb128(p, end); + uint64_t address = read_uleb128(p, end); + printf("\tnode%03ld [ label=%s,addr0x%08llX ];\n", (long)(me-start), cummulativeString, address); + } + else { + printf("\tnode%03ld;\n", (long)(me-start)); + } + const uint8_t childrenCount = *children++; + const uint8_t* s = children; + for (uint8_t i=0; i < childrenCount; ++i) { + const char* edgeName = (char*)s; + int edgeStrLen = 0; + while (*s != '\0') { + cummulativeString[curStrOffset+edgeStrLen] = *s++; + ++edgeStrLen; + } + cummulativeString[curStrOffset+edgeStrLen] = *s++; + uint32_t childNodeOffet = read_uleb128(s, end); + printf("\tnode%03ld -> node%03d [ label=%s ] ;\n", (long)(me-start), childNodeOffet, edgeName); + processExportGraphNode(start, end, start, start+childNodeOffet, cummulativeString, curStrOffset+edgeStrLen); + } +} + +template +void DyldInfoPrinter::printExportInfoGraph() +{ + if ( (fInfo == NULL) || (fInfo->export_off() == 0) ) { + printf("no compressed export info\n"); + } + else { + const uint8_t* p = (uint8_t*)fHeader + fInfo->export_off(); + const uint8_t* end = &p[fInfo->export_size()]; + char cummulativeString[2000]; + printf("digraph {\n"); + processExportGraphNode(p, end, p, p, cummulativeString, 0); + printf("}\n"); + } +} + + + + + +static void dump(const char* path) +{ + struct stat stat_buf; + + try { + int fd = ::open(path, O_RDONLY, 0); + if ( fd == -1 ) + throw "cannot open file"; + if ( ::fstat(fd, &stat_buf) != 0 ) + throwf("fstat(%s) failed, errno=%d\n", path, errno); + uint32_t length = stat_buf.st_size; + uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0); + if ( p == ((uint8_t*)(-1)) ) + throw "cannot map file"; + ::close(fd); + const mach_header* mh = (mach_header*)p; + if ( mh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) { + const struct fat_header* fh = (struct fat_header*)p; + const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header)); + for (unsigned long i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) { + size_t offset = OSSwapBigToHostInt32(archs[i].offset); + size_t size = OSSwapBigToHostInt32(archs[i].size); + cpu_type_t cputype = OSSwapBigToHostInt32(archs[i].cputype); + if ( cputype == (uint32_t)sPreferredArch ) { + switch(cputype) { + case CPU_TYPE_POWERPC: + if ( DyldInfoPrinter::validFile(p + offset) ) + DyldInfoPrinter::make(p + offset, size, path); + else + throw "in universal file, ppc slice does not contain ppc mach-o"; + break; + case CPU_TYPE_I386: + if ( DyldInfoPrinter::validFile(p + offset) ) + DyldInfoPrinter::make(p + offset, size, path); + else + throw "in universal file, i386 slice does not contain i386 mach-o"; + break; + case CPU_TYPE_POWERPC64: + if ( DyldInfoPrinter::validFile(p + offset) ) + DyldInfoPrinter::make(p + offset, size, path); + else + throw "in universal file, ppc64 slice does not contain ppc64 mach-o"; + break; + case CPU_TYPE_X86_64: + if ( DyldInfoPrinter::validFile(p + offset) ) + DyldInfoPrinter::make(p + offset, size, path); + else + throw "in universal file, x86_64 slice does not contain x86_64 mach-o"; + break; + case CPU_TYPE_ARM: + if ( DyldInfoPrinter::validFile(p + offset) ) + DyldInfoPrinter::make(p + offset, size, path); + else + throw "in universal file, arm slice does not contain arm mach-o"; + break; + default: + throwf("in universal file, unknown architecture slice 0x%x\n", cputype); + } + } + } + } + else if ( DyldInfoPrinter::validFile(p) ) { + DyldInfoPrinter::make(p, length, path); + } + else if ( DyldInfoPrinter::validFile(p) ) { + DyldInfoPrinter::make(p, length, path); + } + else if ( DyldInfoPrinter::validFile(p) ) { + DyldInfoPrinter::make(p, length, path); + } + else if ( DyldInfoPrinter::validFile(p) ) { + DyldInfoPrinter::make(p, length, path); + } + else if ( DyldInfoPrinter::validFile(p) ) { + DyldInfoPrinter::make(p, length, path); + } + else { + throw "not a known file type"; + } + } + catch (const char* msg) { + throwf("%s in %s", msg, path); + } +} + +static void usage() +{ + fprintf(stderr, "Usage: dyldinfo [-arch ] \n" + "\t-rebase print addresses dyld will adjust if file not loaded at preferred address\n" + "\t-bind print addresses dyld will set based on symbolic lookups\n" + "\t-weak_bind print symbols which dyld must coalesce\n" + "\t-lazy_bind print addresses dyld will lazily set on first use\n" + "\t-export print addresses of all symbols this file exports\n" + "\t-opcodes print opcodes used to generate the rebase and binding information\n" + "\t-export_dot print a GraphViz .dot file of the exported symbols trie\n" + ); +} + + +int main(int argc, const char* argv[]) +{ + if ( argc == 1 ) { + usage(); + return 0; + } + + try { + std::vector files; + for(int i=1; i < argc; ++i) { + const char* arg = argv[i]; + if ( arg[0] == '-' ) { + if ( strcmp(arg, "-arch") == 0 ) { + const char* arch = ++i::iterator it=files.begin(); it != files.end(); ++it) { + printf("\n%s:\n", *it); + dump(*it); + } + } + } + catch (const char* msg) { + fprintf(stderr, "dyldinfo failed: %s\n", msg); + return 1; + } + + return 0; +} + + + diff --git a/src/machochecker.cpp b/src/other/machochecker.cpp old mode 100755 new mode 100644 similarity index 97% rename from src/machochecker.cpp rename to src/other/machochecker.cpp index 311809b..cb4a781 --- a/src/machochecker.cpp +++ b/src/other/machochecker.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -285,6 +286,8 @@ void MachOChecker::checkLoadCommands() case LC_REEXPORT_DYLIB: case LC_SEGMENT_SPLIT_INFO: case LC_CODE_SIGNATURE: + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: break; case LC_ENCRYPTION_INFO: encryption_info = (macho_encryption_info_command

*)cmd; @@ -583,12 +586,26 @@ void MachOChecker::checkSymbolTable() StringSet externalNames; const macho_nlist

* const exportedStart = &fSymbols[fDynamicSymbolTable->iextdefsym()]; const macho_nlist

* const exportedEnd = &exportedStart[fDynamicSymbolTable->nextdefsym()]; - for(const macho_nlist

* p = exportedStart; p < exportedEnd; ++p) { + int i = fDynamicSymbolTable->iextdefsym(); + for(const macho_nlist

* p = exportedStart; p < exportedEnd; ++p, ++i) { const char* symName = &fStrings[p->n_strx()]; + if ( symName > fStringsEnd ) + throw "string index out of range"; + //fprintf(stderr, "sym[%d] = %s\n", i, symName); if ( externalNames.find(symName) != externalNames.end() ) throwf("duplicate external symbol: %s", symName); externalNames.insert(symName); } + // verify no undefines with same name as an external symbol + const macho_nlist

* const undefinesStart = &fSymbols[fDynamicSymbolTable->iundefsym()]; + const macho_nlist

* const undefinesEnd = &undefinesStart[fDynamicSymbolTable->nundefsym()]; + for(const macho_nlist

* p = undefinesStart; p < undefinesEnd; ++p) { + const char* symName = &fStrings[p->n_strx()]; + if ( symName > fStringsEnd ) + throw "string index out of range"; + if ( externalNames.find(symName) != externalNames.end() ) + throwf("undefine with same name as external symbol: %s", symName); + } } } @@ -859,7 +876,8 @@ static void check(const char* path) int fd = ::open(path, O_RDONLY, 0); if ( fd == -1 ) throw "cannot open file"; - ::fstat(fd, &stat_buf); + if ( ::fstat(fd, &stat_buf) != 0 ) + throwf("fstat(%s) failed, errno=%d\n", path, errno); uint32_t length = stat_buf.st_size; uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0); if ( p == ((uint8_t*)(-1)) ) diff --git a/src/other/prune_trie.h b/src/other/prune_trie.h new file mode 100644 index 0000000..23af95e --- /dev/null +++ b/src/other/prune_trie.h @@ -0,0 +1,54 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ + +#include + + +#if __cplusplus +extern "C" { +#endif /* __cplusplus */ + + +/* + * prune_trie() is a C vended function that is used by strip(1) to prune out + * defined exported symbols from the export trie. It is passed a pointer to + * the start of bytes of the the trie and the size. The prune() funciton + * passed is called with each symbol name in the trie to determine if it is + * to be pruned (retuning 1) or not (returning 0). It writes the new trie + * back into the trie buffer and returns the new size in trie_new_size. + * If the pruning succeeds, NULL is returned. If there was an error processing + * the trie (e.f. it is malformed), then an error message string is returned. + * The error string can be freed. + */ +extern const char* +prune_trie( + uint8_t* trie_start, + uint32_t trie_start_size, + int (*prune)(const char *name), + uint32_t* trie_new_size); + + +#if __cplusplus +} +#endif /* __cplusplus */ diff --git a/src/rebase.cpp b/src/other/rebase.cpp old mode 100755 new mode 100644 similarity index 83% rename from src/rebase.cpp rename to src/other/rebase.cpp index ad9b905..f8dc1ee --- a/src/rebase.cpp +++ b/src/other/rebase.cpp @@ -1,6 +1,6 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * - * Copyright (c) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -91,11 +91,11 @@ private: void adjustDATA(); void doLocalRelocation(const macho_relocation_info

* reloc); pint_t* mappedAddressForVMAddress(uint32_t vmaddress); + void rebaseAt(int segIndex, uint64_t offset, uint8_t type); const macho_header

* fHeader; pint_t fOrignalVMRelocBaseAddress; pint_t fSlide; - pint_t fRelocBase; std::vector fVMMApping; }; @@ -124,7 +124,7 @@ MultiArchRebaser::MultiArchRebaser(const char* path, bool writable) // map in whole file int fd = ::open(path, (writable ? O_RDWR : O_RDONLY), 0); if ( fd == -1 ) - throwf("can't open file, errno=%d", errno); + throwf("can't open file %s, errno=%d", path, errno); struct stat stat_buf; if ( fstat(fd, &stat_buf) == -1) throwf("can't stat open file %s, errno=%d", path, errno); @@ -411,10 +411,72 @@ void Rebaser::adjustSymbolTable() // FIXME ¥¥¥ adjust dylib_module if it exists } +static uint64_t read_uleb128(const uint8_t*& p, const uint8_t* end) +{ + uint64_t result = 0; + int bit = 0; + do { + if (p == end) + throwf("malformed uleb128"); + + uint64_t slice = *p & 0x7f; + + if (bit >= 64 || slice << bit >> bit != slice) + throwf("uleb128 too big"); + else { + result |= (slice << bit); + bit += 7; + } + } + while (*p++ & 0x80); + return result; +} + +template +void Rebaser::rebaseAt(int segIndex, uint64_t offset, uint8_t type) +{ + //fprintf(stderr, "rebaseAt(seg=%d, offset=0x%08llX, type=%d\n", segIndex, offset, type); + static int lastSegIndex = -1; + static uint8_t* lastSegMappedStart = NULL; + if ( segIndex != lastSegIndex ) { + const macho_load_command

* const cmds = (macho_load_command

*)((uint8_t*)fHeader + sizeof(macho_header

)); + const uint32_t cmd_count = fHeader->ncmds(); + const macho_load_command

* cmd = cmds; + int segCount = 0; + for (uint32_t i = 0; i < cmd_count; ++i) { + if ( cmd->cmd() == macho_segment_command

::CMD ) { + if ( segIndex == segCount ) { + const macho_segment_command

* seg = (macho_segment_command

*)cmd; + lastSegMappedStart = (uint8_t*)fHeader + seg->fileoff(); + lastSegIndex == segCount; + break; + } + ++segCount; + } + cmd = (const macho_load_command

*)(((uint8_t*)cmd)+cmd->cmdsize()); + } + } + + pint_t* locationToFix = (pint_t*)(lastSegMappedStart+offset); + uint32_t* locationToFix32 = (uint32_t*)(lastSegMappedStart+offset); + switch (type) { + case REBASE_TYPE_POINTER: + P::setP(*locationToFix, A::P::getP(*locationToFix) + fSlide); + break; + case REBASE_TYPE_TEXT_ABSOLUTE32: + E::set32(*locationToFix32, E::get32(*locationToFix32) + fSlide); + break; + default: + throwf("bad rebase type %d", type); + } +} + + template void Rebaser::adjustDATA() { const macho_dysymtab_command

* dysymtab = NULL; + const macho_dyld_info_command

* dyldInfo = NULL; // get symbol table info const macho_load_command

* const cmds = (macho_load_command

*)((uint8_t*)fHeader + sizeof(macho_header

)); @@ -425,41 +487,113 @@ void Rebaser::adjustDATA() case LC_DYSYMTAB: dysymtab = (macho_dysymtab_command

*)cmd; break; + case LC_DYLD_INFO: + case LC_DYLD_INFO_ONLY: + dyldInfo = (macho_dyld_info_command

*)cmd; + break; } cmd = (const macho_load_command

*)(((uint8_t*)cmd)+cmd->cmdsize()); } - // walk all local relocations and slide every pointer - const macho_relocation_info

* const relocsStart = (macho_relocation_info

*)(((uint8_t*)fHeader) + dysymtab->locreloff()); - const macho_relocation_info

* const relocsEnd = &relocsStart[dysymtab->nlocrel()]; - for (const macho_relocation_info

* reloc=relocsStart; reloc < relocsEnd; ++reloc) { - this->doLocalRelocation(reloc); + // use new encoding of rebase info if present + if ( dyldInfo != NULL ) { + if ( dyldInfo->rebase_size() != 0 ) { + const uint8_t* p = (uint8_t*)fHeader + dyldInfo->rebase_off(); + const uint8_t* end = &p[dyldInfo->rebase_size()]; + + uint8_t type = 0; + uint64_t offset = 0; + uint32_t count; + uint32_t skip; + int segIndex; + bool done = false; + while ( !done && (p < end) ) { + uint8_t immediate = *p & REBASE_IMMEDIATE_MASK; + uint8_t opcode = *p & REBASE_OPCODE_MASK; + ++p; + switch (opcode) { + case REBASE_OPCODE_DONE: + done = true; + break; + case REBASE_OPCODE_SET_TYPE_IMM: + type = immediate; + break; + case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: + segIndex = immediate; + offset = read_uleb128(p, end); + break; + case REBASE_OPCODE_ADD_ADDR_ULEB: + offset += read_uleb128(p, end); + break; + case REBASE_OPCODE_ADD_ADDR_IMM_SCALED: + offset += immediate*sizeof(pint_t); + break; + case REBASE_OPCODE_DO_REBASE_IMM_TIMES: + for (int i=0; i < immediate; ++i) { + rebaseAt(segIndex, offset, type); + offset += sizeof(pint_t); + } + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES: + count = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + rebaseAt(segIndex, offset, type); + offset += sizeof(pint_t); + } + break; + case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: + rebaseAt(segIndex, offset, type); + offset += read_uleb128(p, end) + sizeof(pint_t); + break; + case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: + count = read_uleb128(p, end); + skip = read_uleb128(p, end); + for (uint32_t i=0; i < count; ++i) { + rebaseAt(segIndex, offset, type); + offset += skip + sizeof(pint_t); + } + break; + default: + throwf("bad rebase opcode %d", *p); + } + } + + + + } } - - // walk non-lazy-pointers and slide the ones that are LOCAL - cmd = cmds; - for (uint32_t i = 0; i < cmd_count; ++i) { - if ( cmd->cmd() == macho_segment_command

::CMD ) { - const macho_segment_command

* seg = (macho_segment_command

*)cmd; - const macho_section

* const sectionsStart = (macho_section

*)((char*)seg + sizeof(macho_segment_command

)); - const macho_section

* const sectionsEnd = §ionsStart[seg->nsects()]; - const uint32_t* const indirectTable = (uint32_t*)(((uint8_t*)fHeader) + dysymtab->indirectsymoff()); - for(const macho_section

* sect = sectionsStart; sect < sectionsEnd; ++sect) { - if ( (sect->flags() & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS ) { - const uint32_t indirectTableOffset = sect->reserved1(); - uint32_t pointerCount = sect->size() / sizeof(pint_t); - pint_t* nonLazyPointer = (pint_t*)(((uint8_t*)fHeader) + sect->offset()); - for (uint32_t i=0; i < pointerCount; ++i, ++nonLazyPointer) { - if ( E::get32(indirectTable[indirectTableOffset + i]) == INDIRECT_SYMBOL_LOCAL ) { - P::setP(*nonLazyPointer, A::P::getP(*nonLazyPointer) + fSlide); + else { + // walk all local relocations and slide every pointer + const macho_relocation_info

* const relocsStart = (macho_relocation_info

*)(((uint8_t*)fHeader) + dysymtab->locreloff()); + const macho_relocation_info

* const relocsEnd = &relocsStart[dysymtab->nlocrel()]; + for (const macho_relocation_info

* reloc=relocsStart; reloc < relocsEnd; ++reloc) { + this->doLocalRelocation(reloc); + } + + // walk non-lazy-pointers and slide the ones that are LOCAL + cmd = cmds; + for (uint32_t i = 0; i < cmd_count; ++i) { + if ( cmd->cmd() == macho_segment_command

::CMD ) { + const macho_segment_command

* seg = (macho_segment_command

*)cmd; + const macho_section

* const sectionsStart = (macho_section

*)((char*)seg + sizeof(macho_segment_command

)); + const macho_section

* const sectionsEnd = §ionsStart[seg->nsects()]; + const uint32_t* const indirectTable = (uint32_t*)(((uint8_t*)fHeader) + dysymtab->indirectsymoff()); + for(const macho_section

* sect = sectionsStart; sect < sectionsEnd; ++sect) { + if ( (sect->flags() & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS ) { + const uint32_t indirectTableOffset = sect->reserved1(); + uint32_t pointerCount = sect->size() / sizeof(pint_t); + pint_t* nonLazyPointer = (pint_t*)(((uint8_t*)fHeader) + sect->offset()); + for (uint32_t i=0; i < pointerCount; ++i, ++nonLazyPointer) { + if ( E::get32(indirectTable[indirectTableOffset + i]) == INDIRECT_SYMBOL_LOCAL ) { + P::setP(*nonLazyPointer, A::P::getP(*nonLazyPointer) + fSlide); + } } } } } - } - cmd = (const macho_load_command

*)(((uint8_t*)cmd)+cmd->cmdsize()); - } - + cmd = (const macho_load_command

*)(((uint8_t*)cmd)+cmd->cmdsize()); + } + } } @@ -567,7 +701,6 @@ template void Rebaser::setRelocBase() { // reloc addresses are from the start of the mapped file (base address) - fRelocBase = (pint_t)fHeader; fOrignalVMRelocBaseAddress = this->getBaseAddress(); //fprintf(stderr, "fOrignalVMRelocBaseAddress=0x%08X\n", fOrignalVMRelocBaseAddress); } @@ -587,7 +720,6 @@ void Rebaser::setRelocBase() if ( segCmd->initprot() & VM_PROT_WRITE ) { if ( (segCmd->vmaddr() + segCmd->vmsize() - this->getBaseAddress()) > 0x100000000ULL ) { // found writable segment with address > 4GB past base address - fRelocBase = segCmd->fileoff() + (pint_t)fHeader; fOrignalVMRelocBaseAddress = segCmd->vmaddr(); return; } @@ -596,7 +728,6 @@ void Rebaser::setRelocBase() cmd = (const macho_load_command

*)(((uint8_t*)cmd)+cmd->cmdsize()); } // just use base address - fRelocBase = (pint_t)fHeader; fOrignalVMRelocBaseAddress = this->getBaseAddress(); } @@ -611,7 +742,6 @@ void Rebaser::setRelocBase() if ( cmd->cmd() == macho_segment_command

::CMD ) { const macho_segment_command

* segCmd = (const macho_segment_command

*)cmd; if ( segCmd->initprot() & VM_PROT_WRITE ) { - fRelocBase = segCmd->fileoff() + (pint_t)fHeader; fOrignalVMRelocBaseAddress = segCmd->vmaddr(); return; } diff --git a/src/other/unwinddump.cpp b/src/other/unwinddump.cpp new file mode 100644 index 0000000..098d932 --- /dev/null +++ b/src/other/unwinddump.cpp @@ -0,0 +1,926 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + + +#include "MachOFileAbstraction.hpp" +#include "Architectures.hpp" + + + __attribute__((noreturn)) +void throwf(const char* format, ...) +{ + va_list list; + char* p; + va_start(list, format); + vasprintf(&p, format, list); + va_end(list); + + const char* t = p; + throw t; +} + + +template +class UnwindPrinter +{ +public: + static bool validFile(const uint8_t* fileContent); + static UnwindPrinter* make(const uint8_t* fileContent, uint32_t fileLength, const char* path) + { return new UnwindPrinter(fileContent, fileLength, path); } + virtual ~UnwindPrinter() {} + + +private: + typedef typename A::P P; + typedef typename A::P::E E; + typedef typename A::P::uint_t pint_t; + + class CStringEquals + { + public: + bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); } + }; + + typedef __gnu_cxx::hash_set, CStringEquals> StringSet; + + UnwindPrinter(const uint8_t* fileContent, uint32_t fileLength, const char* path); + bool findUnwindSection(); + void printUnwindSection(); + void getSymbolTableInfo(); + const char* functionName(pint_t addr); + static const char* archName(); + static void decode(uint32_t encoding, const uint8_t* funcStart, char* str); + + const char* fPath; + const macho_header

* fHeader; + uint64_t fLength; + const macho_section

* fUnwindSection; + const char* fStrings; + const char* fStringsEnd; + const macho_nlist

* fSymbols; + uint32_t fSymbolCount; + pint_t fMachHeaderAddress; +}; + + +template <> const char* UnwindPrinter::archName() { return "ppc"; } +template <> const char* UnwindPrinter::archName() { return "ppc64"; } +template <> const char* UnwindPrinter::archName() { return "i386"; } +template <> const char* UnwindPrinter::archName() { return "x86_64"; } +template <> const char* UnwindPrinter::archName() { return "arm"; } + +template <> +bool UnwindPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_POWERPC ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool UnwindPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC_64 ) + return false; + if ( header->cputype() != CPU_TYPE_POWERPC64 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool UnwindPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_I386 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool UnwindPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC_64 ) + return false; + if ( header->cputype() != CPU_TYPE_X86_64 ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + +template <> +bool UnwindPrinter::validFile(const uint8_t* fileContent) +{ + const macho_header

* header = (const macho_header

*)fileContent; + if ( header->magic() != MH_MAGIC ) + return false; + if ( header->cputype() != CPU_TYPE_ARM ) + return false; + switch (header->filetype()) { + case MH_EXECUTE: + case MH_DYLIB: + case MH_BUNDLE: + case MH_DYLINKER: + return true; + } + return false; +} + + +template +UnwindPrinter::UnwindPrinter(const uint8_t* fileContent, uint32_t fileLength, const char* path) + : fHeader(NULL), fLength(fileLength), fUnwindSection(NULL), + fStrings(NULL), fStringsEnd(NULL), fSymbols(NULL), fSymbolCount(0), fMachHeaderAddress(0) +{ + // sanity check + if ( ! validFile(fileContent) ) + throw "not a mach-o file that can be checked"; + + fPath = strdup(path); + fHeader = (const macho_header

*)fileContent; + + getSymbolTableInfo(); + + if ( findUnwindSection() ) + printUnwindSection(); +} + + +template +void UnwindPrinter::getSymbolTableInfo() +{ + const uint8_t* const endOfFile = (uint8_t*)fHeader + fLength; + const uint8_t* const endOfLoadCommands = (uint8_t*)fHeader + sizeof(macho_header

) + fHeader->sizeofcmds(); + const uint32_t cmd_count = fHeader->ncmds(); + const macho_load_command

* const cmds = (macho_load_command

*)((uint8_t*)fHeader + sizeof(macho_header

)); + const macho_load_command

* cmd = cmds; + for (uint32_t i = 0; i < cmd_count; ++i) { + uint32_t size = cmd->cmdsize(); + const uint8_t* endOfCmd = ((uint8_t*)cmd)+cmd->cmdsize(); + if ( endOfCmd > endOfLoadCommands ) + throwf("load command #%d extends beyond the end of the load commands", i); + if ( endOfCmd > endOfFile ) + throwf("load command #%d extends beyond the end of the file", i); + if ( cmd->cmd() == LC_SYMTAB) { + const macho_symtab_command

* symtab = (macho_symtab_command

*)cmd; + fSymbolCount = symtab->nsyms(); + fSymbols = (const macho_nlist

*)((char*)fHeader + symtab->symoff()); + fStrings = (char*)fHeader + symtab->stroff(); + fStringsEnd = fStrings + symtab->strsize(); + } + cmd = (const macho_load_command

*)endOfCmd; + } +} + +template +const char* UnwindPrinter::functionName(pint_t addr) +{ + for (uint32_t i=0; i < fSymbolCount; ++i) { + uint8_t type = fSymbols[i].n_type(); + if ( ((type & N_STAB) == 0) && ((type & N_TYPE) == N_SECT) ) { + if ( fSymbols[i].n_value() == addr ) { + const char* r = &fStrings[fSymbols[i].n_strx()]; + //fprintf(stderr, "addr=0x%08llX, i=%u, n_type=0x%0X, r=%s\n", (long long)(fSymbols[i].n_value()), i, fSymbols[i].n_type(), r); + return r; + } + } + } + return "--anonymous function--"; +} + + + +template +bool UnwindPrinter::findUnwindSection() +{ + const uint8_t* const endOfFile = (uint8_t*)fHeader + fLength; + const uint8_t* const endOfLoadCommands = (uint8_t*)fHeader + sizeof(macho_header

) + fHeader->sizeofcmds(); + const uint32_t cmd_count = fHeader->ncmds(); + const macho_load_command

* const cmds = (macho_load_command

*)((uint8_t*)fHeader + sizeof(macho_header

)); + const macho_load_command

* cmd = cmds; + for (uint32_t i = 0; i < cmd_count; ++i) { + uint32_t size = cmd->cmdsize(); + const uint8_t* endOfCmd = ((uint8_t*)cmd)+cmd->cmdsize(); + if ( endOfCmd > endOfLoadCommands ) + throwf("load command #%d extends beyond the end of the load commands", i); + if ( endOfCmd > endOfFile ) + throwf("load command #%d extends beyond the end of the file", i); + if ( cmd->cmd() == macho_segment_command

::CMD ) { + const macho_segment_command

* segCmd = (const macho_segment_command

*)cmd; + const macho_section

* const sectionsStart = (macho_section

*)((char*)segCmd + sizeof(macho_segment_command

)); + const macho_section

* const sectionsEnd = §ionsStart[segCmd->nsects()]; + for(const macho_section

* sect = sectionsStart; sect < sectionsEnd; ++sect) { + if ( (strcmp(sect->sectname(), "__unwind_info") == 0) && (strcmp(sect->segname(), "__TEXT") == 0) ) { + fUnwindSection = sect; + fMachHeaderAddress = segCmd->vmaddr(); + return fUnwindSection; + } + } + } + cmd = (const macho_load_command

*)endOfCmd; + } + return false; +} + +#define EXTRACT_BITS(value, mask) \ + ( (value >> __builtin_ctz(mask)) & (((1 << __builtin_popcount(mask)))-1) ) + + +template <> +void UnwindPrinter::decode(uint32_t encoding, const uint8_t* funcStart, char* str) +{ + *str = '\0'; + switch ( encoding & UNWIND_X86_64_MODE_MASK ) { + case UNWIND_X86_64_MODE_RBP_FRAME: + { + uint32_t savedRegistersOffset = EXTRACT_BITS(encoding, UNWIND_X86_64_RBP_FRAME_OFFSET); + uint32_t savedRegistersLocations = EXTRACT_BITS(encoding, UNWIND_X86_64_RBP_FRAME_REGISTERS); + if ( savedRegistersLocations == 0 ) { + strcpy(str, "rbp frame, no saved registers"); + } + else { + sprintf(str, "rbp frame, at -%d:", savedRegistersOffset*8); + bool needComma = false; + for (int i=0; i < 5; ++i) { + if ( needComma ) + strcat(str, ","); + else + needComma = true; + switch (savedRegistersLocations & 0x7) { + case UNWIND_X86_64_REG_NONE: + strcat(str, "-"); + break; + case UNWIND_X86_64_REG_RBX: + strcat(str, "rbx"); + break; + case UNWIND_X86_64_REG_R12: + strcat(str, "r12"); + break; + case UNWIND_X86_64_REG_R13: + strcat(str, "r13"); + break; + case UNWIND_X86_64_REG_R14: + strcat(str, "r14"); + break; + case UNWIND_X86_64_REG_R15: + strcat(str, "r15"); + break; + default: + strcat(str, "r?"); + } + savedRegistersLocations = (savedRegistersLocations >> 3); + if ( savedRegistersLocations == 0 ) + break; + } + } + } + break; + case UNWIND_X86_64_MODE_STACK_IMMD: + case UNWIND_X86_64_MODE_STACK_IND: + { + uint32_t stackSize = EXTRACT_BITS(encoding, UNWIND_X86_64_FRAMELESS_STACK_SIZE); + uint32_t stackAdjust = EXTRACT_BITS(encoding, UNWIND_X86_64_FRAMELESS_STACK_ADJUST); + uint32_t regCount = EXTRACT_BITS(encoding, UNWIND_X86_64_FRAMELESS_STACK_REG_COUNT); + uint32_t permutation = EXTRACT_BITS(encoding, UNWIND_X86_64_FRAMELESS_STACK_REG_PERMUTATION); + if ( (encoding & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_STACK_IND ) { + // stack size is encoded in subl $xxx,%esp instruction + uint32_t subl = x86_64::P::E::get32(*((uint32_t*)(funcStart+stackSize))); + sprintf(str, "stack size=0x%08X, ", subl + 8*stackAdjust); + } + else { + sprintf(str, "stack size=%d, ", stackSize*8); + } + if ( regCount == 0 ) { + strcat(str, "no registers saved"); + } + else { + int permunreg[6]; + switch ( regCount ) { + case 6: + permunreg[0] = permutation/120; + permutation -= (permunreg[0]*120); + permunreg[1] = permutation/24; + permutation -= (permunreg[1]*24); + permunreg[2] = permutation/6; + permutation -= (permunreg[2]*6); + permunreg[3] = permutation/2; + permutation -= (permunreg[3]*2); + permunreg[4] = permutation; + permunreg[5] = 0; + break; + case 5: + permunreg[0] = permutation/120; + permutation -= (permunreg[0]*120); + permunreg[1] = permutation/24; + permutation -= (permunreg[1]*24); + permunreg[2] = permutation/6; + permutation -= (permunreg[2]*6); + permunreg[3] = permutation/2; + permutation -= (permunreg[3]*2); + permunreg[4] = permutation; + break; + case 4: + permunreg[0] = permutation/60; + permutation -= (permunreg[0]*60); + permunreg[1] = permutation/12; + permutation -= (permunreg[1]*12); + permunreg[2] = permutation/3; + permutation -= (permunreg[2]*3); + permunreg[3] = permutation; + break; + case 3: + permunreg[0] = permutation/20; + permutation -= (permunreg[0]*20); + permunreg[1] = permutation/4; + permutation -= (permunreg[1]*4); + permunreg[2] = permutation; + break; + case 2: + permunreg[0] = permutation/5; + permutation -= (permunreg[0]*5); + permunreg[1] = permutation; + break; + case 1: + permunreg[0] = permutation; + break; + } + // renumber registers back to standard numbers + int registers[6]; + bool used[7] = { false, false, false, false, false, false, false }; + for (int i=0; i < regCount; ++i) { + int renum = 0; + for (int u=1; u < 7; ++u) { + if ( !used[u] ) { + if ( renum == permunreg[i] ) { + registers[i] = u; + used[u] = true; + break; + } + ++renum; + } + } + } + bool needComma = false; + for (int i=0; i < regCount; ++i) { + if ( needComma ) + strcat(str, ","); + else + needComma = true; + switch ( registers[i] ) { + case UNWIND_X86_64_REG_RBX: + strcat(str, "rbx"); + break; + case UNWIND_X86_64_REG_R12: + strcat(str, "r12"); + break; + case UNWIND_X86_64_REG_R13: + strcat(str, "r13"); + break; + case UNWIND_X86_64_REG_R14: + strcat(str, "r14"); + break; + case UNWIND_X86_64_REG_R15: + strcat(str, "r15"); + break; + case UNWIND_X86_64_REG_RBP: + strcat(str, "rbp"); + break; + default: + strcat(str, "r??"); + } + } + } + } + break; + case UNWIND_X86_64_MODE_DWARF: + sprintf(str, "dwarf offset 0x%08X, ", encoding & UNWIND_X86_64_DWARF_SECTION_OFFSET); + break; + default: + if ( encoding == 0 ) + strcat(str, "no unwind information"); + else + strcat(str, "tbd "); + } + if ( encoding & UNWIND_HAS_LSDA ) { + strcat(str, " LSDA"); + } + +} + +template <> +void UnwindPrinter::decode(uint32_t encoding, const uint8_t* funcStart, char* str) +{ + *str = '\0'; + switch ( encoding & UNWIND_X86_MODE_MASK ) { + case UNWIND_X86_MODE_EBP_FRAME: + { + uint32_t savedRegistersOffset = EXTRACT_BITS(encoding, UNWIND_X86_EBP_FRAME_OFFSET); + uint32_t savedRegistersLocations = EXTRACT_BITS(encoding, UNWIND_X86_EBP_FRAME_REGISTERS); + if ( savedRegistersLocations == 0 ) { + strcpy(str, "ebp frame, no saved registers"); + } + else { + sprintf(str, "ebp frame, at -%d:", savedRegistersOffset*4); + bool needComma = false; + for (int i=0; i < 5; ++i) { + if ( needComma ) + strcat(str, ","); + else + needComma = true; + switch (savedRegistersLocations & 0x7) { + case UNWIND_X86_REG_NONE: + strcat(str, "-"); + break; + case UNWIND_X86_REG_EBX: + strcat(str, "ebx"); + break; + case UNWIND_X86_REG_ECX: + strcat(str, "ecx"); + break; + case UNWIND_X86_REG_EDX: + strcat(str, "edx"); + break; + case UNWIND_X86_REG_EDI: + strcat(str, "edi"); + break; + case UNWIND_X86_REG_ESI: + strcat(str, "esi"); + break; + default: + strcat(str, "e??"); + } + savedRegistersLocations = (savedRegistersLocations >> 3); + if ( savedRegistersLocations == 0 ) + break; + } + } + } + break; + case UNWIND_X86_MODE_STACK_IMMD: + case UNWIND_X86_MODE_STACK_IND: + { + uint32_t stackSize = EXTRACT_BITS(encoding, UNWIND_X86_FRAMELESS_STACK_SIZE); + uint32_t stackAdjust = EXTRACT_BITS(encoding, UNWIND_X86_FRAMELESS_STACK_ADJUST); + uint32_t regCount = EXTRACT_BITS(encoding, UNWIND_X86_FRAMELESS_STACK_REG_COUNT); + uint32_t permutation = EXTRACT_BITS(encoding, UNWIND_X86_FRAMELESS_STACK_REG_PERMUTATION); + if ( (encoding & UNWIND_X86_MODE_MASK) == UNWIND_X86_MODE_STACK_IND ) { + // stack size is encoded in subl $xxx,%esp instruction + uint32_t subl = x86::P::E::get32(*((uint32_t*)(funcStart+stackSize))); + sprintf(str, "stack size=0x%08X, ", subl+4*stackAdjust); + } + else { + sprintf(str, "stack size=%d, ", stackSize*4); + } + if ( regCount == 0 ) { + strcat(str, "no saved regs"); + } + else { + int permunreg[6]; + switch ( regCount ) { + case 6: + permunreg[0] = permutation/120; + permutation -= (permunreg[0]*120); + permunreg[1] = permutation/24; + permutation -= (permunreg[1]*24); + permunreg[2] = permutation/6; + permutation -= (permunreg[2]*6); + permunreg[3] = permutation/2; + permutation -= (permunreg[3]*2); + permunreg[4] = permutation; + permunreg[5] = 0; + break; + case 5: + permunreg[0] = permutation/120; + permutation -= (permunreg[0]*120); + permunreg[1] = permutation/24; + permutation -= (permunreg[1]*24); + permunreg[2] = permutation/6; + permutation -= (permunreg[2]*6); + permunreg[3] = permutation/2; + permutation -= (permunreg[3]*2); + permunreg[4] = permutation; + break; + case 4: + permunreg[0] = permutation/60; + permutation -= (permunreg[0]*60); + permunreg[1] = permutation/12; + permutation -= (permunreg[1]*12); + permunreg[2] = permutation/3; + permutation -= (permunreg[2]*3); + permunreg[3] = permutation; + break; + case 3: + permunreg[0] = permutation/20; + permutation -= (permunreg[0]*20); + permunreg[1] = permutation/4; + permutation -= (permunreg[1]*4); + permunreg[2] = permutation; + break; + case 2: + permunreg[0] = permutation/5; + permutation -= (permunreg[0]*5); + permunreg[1] = permutation; + break; + case 1: + permunreg[0] = permutation; + break; + } + // renumber registers back to standard numbers + int registers[6]; + bool used[7] = { false, false, false, false, false, false, false }; + for (int i=0; i < regCount; ++i) { + int renum = 0; + for (int u=1; u < 7; ++u) { + if ( !used[u] ) { + if ( renum == permunreg[i] ) { + registers[i] = u; + used[u] = true; + break; + } + ++renum; + } + } + } + bool needComma = false; + for (int i=0; i < regCount; ++i) { + if ( needComma ) + strcat(str, ","); + else + needComma = true; + switch ( registers[i] ) { + case UNWIND_X86_REG_EBX: + strcat(str, "ebx"); + break; + case UNWIND_X86_REG_ECX: + strcat(str, "ecx"); + break; + case UNWIND_X86_REG_EDX: + strcat(str, "edx"); + break; + case UNWIND_X86_REG_EDI: + strcat(str, "edi"); + break; + case UNWIND_X86_REG_ESI: + strcat(str, "esi"); + break; + case UNWIND_X86_REG_EBP: + strcat(str, "ebp"); + break; + default: + strcat(str, "e??"); + } + } + } + } + break; + case UNWIND_X86_MODE_DWARF: + sprintf(str, "dwarf offset 0x%08X, ", encoding & UNWIND_X86_DWARF_SECTION_OFFSET); + break; + default: + if ( encoding == 0 ) + strcat(str, "no unwind information"); + else + strcat(str, "tbd "); + } + if ( encoding & UNWIND_HAS_LSDA ) { + strcat(str, " LSDA"); + } + +} + + +template +void UnwindPrinter::decode(uint32_t encoding, const uint8_t* funcStart, char* str) +{ + + +} + +template +void UnwindPrinter::printUnwindSection() +{ + const uint8_t* sectionContent = (uint8_t*)fHeader + fUnwindSection->offset(); + macho_unwind_info_section_header

* sectionHeader = (macho_unwind_info_section_header

*)(sectionContent); + + printf("Arch: %s, Section: __TEXT,__unwind_info (addr=0x%08llX, size=0x%08llX, fileOffset=0x%08X)\n", + archName(), fUnwindSection->addr(), fUnwindSection->size(), fUnwindSection->offset()); + printf("\tversion=0x%08X\n", sectionHeader->version()); + printf("\tcommonEncodingsArraySectionOffset=0x%08X\n", sectionHeader->commonEncodingsArraySectionOffset()); + printf("\tcommonEncodingsArrayCount=0x%08X\n", sectionHeader->commonEncodingsArrayCount()); + printf("\tpersonalityArraySectionOffset=0x%08X\n", sectionHeader->personalityArraySectionOffset()); + printf("\tpersonalityArrayCount=0x%08X\n", sectionHeader->personalityArrayCount()); + printf("\tindexSectionOffset=0x%08X\n", sectionHeader->indexSectionOffset()); + printf("\tindexCount=0x%08X\n", sectionHeader->indexCount()); + printf("\tcommon encodings: (count=%u)\n", sectionHeader->commonEncodingsArrayCount()); + const uint32_t* commonEncodings = (uint32_t*)§ionContent[sectionHeader->commonEncodingsArraySectionOffset()]; + for (uint32_t i=0; i < sectionHeader->commonEncodingsArrayCount(); ++i) { + printf("\t\tencoding[%3u]=0x%08X\n", i, A::P::E::get32(commonEncodings[i])); + } + printf("\tpersonalities: (count=%u)\n", sectionHeader->personalityArrayCount()); + const uint32_t* personalityArray = (uint32_t*)§ionContent[sectionHeader->personalityArraySectionOffset()]; + for (uint32_t i=0; i < sectionHeader->personalityArrayCount(); ++i) { + printf("\t\t[%2u]=0x%08X\n", i+1, A::P::E::get32(personalityArray[i])); + } + printf("\tfirst level index: (count=%u)\n", sectionHeader->indexCount()); + macho_unwind_info_section_header_index_entry

* indexes = (macho_unwind_info_section_header_index_entry

*)§ionContent[sectionHeader->indexSectionOffset()]; + for (uint32_t i=0; i < sectionHeader->indexCount(); ++i) { + printf("\t\t[%2u] funcOffset=0x%08X, pageOffset=0x%08X, lsdaOffset=0x%08X\n", + i, indexes[i].functionOffset(), indexes[i].secondLevelPagesSectionOffset(), indexes[i].lsdaIndexArraySectionOffset()); + } + uint32_t lsdaIndexArraySectionOffset = indexes[0].lsdaIndexArraySectionOffset(); + uint32_t lsdaIndexArrayEndSectionOffset = indexes[sectionHeader->indexCount()-1].lsdaIndexArraySectionOffset(); + uint32_t lsdaIndexArrayCount = (lsdaIndexArrayEndSectionOffset-lsdaIndexArraySectionOffset)/sizeof(macho_unwind_info_section_header_lsda_index_entry

); + printf("\tLSDA table: (section offset 0x%08X, count=%u)\n", lsdaIndexArraySectionOffset, lsdaIndexArrayCount); + macho_unwind_info_section_header_lsda_index_entry

* lindex = (macho_unwind_info_section_header_lsda_index_entry

*)§ionContent[lsdaIndexArraySectionOffset]; + for (uint32_t i=0; i < lsdaIndexArrayCount; ++i) { + printf("\t\t[%3u] funcOffset=0x%08X, lsdaOffset=0x%08X, %s\n", + i, lindex[i].functionOffset(), lindex[i].lsdaOffset(), functionName(lindex[i].functionOffset()+fMachHeaderAddress)); + if ( *(((uint8_t*)fHeader) + lindex[i].lsdaOffset()) != 0xFF ) + fprintf(stderr, "BAD LSDA entry (does not start with 0xFF) for %s\n", functionName(lindex[i].functionOffset()+fMachHeaderAddress)); + } + for (uint32_t i=0; i < sectionHeader->indexCount()-1; ++i) { + printf("\tsecond level index[%u] sectionOffset=0x%08X, count=%u, fileOffset=0x%08X\n", i, indexes[i].secondLevelPagesSectionOffset(), + sectionHeader->indexCount(), fUnwindSection->offset()+indexes[i].secondLevelPagesSectionOffset()); + macho_unwind_info_regular_second_level_page_header

* page = (macho_unwind_info_regular_second_level_page_header

*)§ionContent[indexes[i].secondLevelPagesSectionOffset()]; + if ( page->kind() == UNWIND_SECOND_LEVEL_REGULAR ) { + printf("\t\tkind=UNWIND_SECOND_LEVEL_REGULAR\n"); + printf("\t\tentryPageOffset=0x%08X\n", page->entryPageOffset()); + printf("\t\tentryCount=0x%08X\n", page->entryCount()); + const macho_unwind_info_regular_second_level_entry

* entry = (macho_unwind_info_regular_second_level_entry

*)((char*)page+page->entryPageOffset()); + for (uint32_t j=0; j < page->entryCount(); ++j) { + uint32_t funcOffset = entry[j].functionOffset(); + if ( entry[j].encoding() & UNWIND_HAS_LSDA ) { + // verify there is a corresponding entry in lsda table + bool found = false; + for (uint32_t k=0; k < lsdaIndexArrayCount; ++k) { + if ( lindex[k].functionOffset() == funcOffset ) { + found = true; + break; + } + } + if ( !found ) { + fprintf(stderr, "MISSING LSDA entry for %s\n", functionName(funcOffset+fMachHeaderAddress)); + } + } + char encodingString[100]; + decode(entry[j].encoding(), ((const uint8_t*)fHeader)+funcOffset, encodingString); + printf("\t\t\t[%3u] funcOffset=0x%08X, encoding=0x%08X (%-40s) %s\n", + j, funcOffset, entry[j].encoding(), encodingString, functionName(funcOffset+fMachHeaderAddress)); + } + } + else if ( page->kind() == UNWIND_SECOND_LEVEL_COMPRESSED ) { + macho_unwind_info_compressed_second_level_page_header

* cp = (macho_unwind_info_compressed_second_level_page_header

*)page; + printf("\t\tkind=UNWIND_SECOND_LEVEL_COMPRESSED\n"); + printf("\t\tentryPageOffset=0x%08X\n", cp->entryPageOffset()); + printf("\t\tentryCount=0x%08X\n", cp->entryCount()); + printf("\t\tencodingsPageOffset=0x%08X\n", cp->encodingsPageOffset()); + printf("\t\tencodingsCount=0x%08X\n", cp->encodingsCount()); + const uint32_t* entries = (uint32_t*)(((uint8_t*)page)+cp->entryPageOffset()); + const uint32_t* encodings = (uint32_t*)(((uint8_t*)page)+cp->encodingsPageOffset()); + const uint32_t baseFunctionOffset = indexes[i].functionOffset(); + for (uint32_t j=0; j < cp->entryCount(); ++j) { + uint8_t encodingIndex = UNWIND_INFO_COMPRESSED_ENTRY_ENCODING_INDEX(entries[j]); + uint32_t encoding; + if ( encodingIndex < sectionHeader->commonEncodingsArrayCount() ) + encoding = A::P::E::get32(commonEncodings[encodingIndex]); + else + encoding = A::P::E::get32(encodings[encodingIndex-sectionHeader->commonEncodingsArrayCount()]); + char encodingString[100]; + uint32_t funcOff = UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(entries[j])+baseFunctionOffset; + decode(encoding, ((const uint8_t*)fHeader)+funcOff, encodingString); + const char* name = functionName(funcOff+fMachHeaderAddress); + if ( encoding & UNWIND_HAS_LSDA ) { + // verify there is a corresponding entry in lsda table + bool found = false; + for (uint32_t k=0; k < lsdaIndexArrayCount; ++k) { + if ( lindex[k].functionOffset() == funcOff ) { + found = true; + break; + } + } + if ( !found ) { + fprintf(stderr, "MISSING LSDA entry for %s\n", name); + } + } + printf("\t\t\t[%3u] funcOffset=0x%08X, encoding[%3u]=0x%08X (%-40s) %s\n", + j, funcOff, encodingIndex, encoding, encodingString, name); + } + } + else { + fprintf(stderr, "\t\tbad page header\n"); + } + } + +} + +static void dump(const char* path, const std::set& onlyArchs) +{ + struct stat stat_buf; + + try { + int fd = ::open(path, O_RDONLY, 0); + if ( fd == -1 ) + throw "cannot open file"; + if ( ::fstat(fd, &stat_buf) != 0 ) + throwf("fstat(%s) failed, errno=%d\n", path, errno); + uint32_t length = stat_buf.st_size; + uint8_t* p = (uint8_t*)::mmap(NULL, stat_buf.st_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0); + if ( p == ((uint8_t*)(-1)) ) + throw "cannot map file"; + ::close(fd); + const mach_header* mh = (mach_header*)p; + if ( mh->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) { + const struct fat_header* fh = (struct fat_header*)p; + const struct fat_arch* archs = (struct fat_arch*)(p + sizeof(struct fat_header)); + for (unsigned long i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) { + size_t offset = OSSwapBigToHostInt32(archs[i].offset); + size_t size = OSSwapBigToHostInt32(archs[i].size); + unsigned int cputype = OSSwapBigToHostInt32(archs[i].cputype); + if ( onlyArchs.count(cputype) ) { + switch(cputype) { + case CPU_TYPE_POWERPC: + if ( UnwindPrinter::validFile(p + offset) ) + UnwindPrinter::make(p + offset, size, path); + else + throw "in universal file, ppc slice does not contain ppc mach-o"; + break; + case CPU_TYPE_I386: + if ( UnwindPrinter::validFile(p + offset) ) + UnwindPrinter::make(p + offset, size, path); + else + throw "in universal file, i386 slice does not contain i386 mach-o"; + break; + case CPU_TYPE_POWERPC64: + if ( UnwindPrinter::validFile(p + offset) ) + UnwindPrinter::make(p + offset, size, path); + else + throw "in universal file, ppc64 slice does not contain ppc64 mach-o"; + break; + case CPU_TYPE_X86_64: + if ( UnwindPrinter::validFile(p + offset) ) + UnwindPrinter::make(p + offset, size, path); + else + throw "in universal file, x86_64 slice does not contain x86_64 mach-o"; + break; + case CPU_TYPE_ARM: + if ( UnwindPrinter::validFile(p + offset) ) + UnwindPrinter::make(p + offset, size, path); + else + throw "in universal file, arm slice does not contain arm mach-o"; + break; + default: + throwf("in universal file, unknown architecture slice 0x%x\n", cputype); + } + } + } + } + else if ( UnwindPrinter::validFile(p) && onlyArchs.count(CPU_TYPE_I386) ) { + UnwindPrinter::make(p, length, path); + } + else if ( UnwindPrinter::validFile(p) && onlyArchs.count(CPU_TYPE_POWERPC) ) { + UnwindPrinter::make(p, length, path); + } + else if ( UnwindPrinter::validFile(p) && onlyArchs.count(CPU_TYPE_POWERPC64) ) { + UnwindPrinter::make(p, length, path); + } + else if ( UnwindPrinter::validFile(p) && onlyArchs.count(CPU_TYPE_X86_64) ) { + UnwindPrinter::make(p, length, path); + } + else if ( UnwindPrinter::validFile(p) && onlyArchs.count(CPU_TYPE_ARM) ) { + UnwindPrinter::make(p, length, path); + } + else { + throw "not a known file type"; + } + } + catch (const char* msg) { + throwf("%s in %s", msg, path); + } +} + + +int main(int argc, const char* argv[]) +{ + std::set onlyArchs; + std::vector files; + + try { + for(int i=1; i < argc; ++i) { + const char* arg = argv[i]; + if ( arg[0] == '-' ) { + if ( strcmp(arg, "-arch") == 0 ) { + const char* arch = argv[++i]; + if ( strcmp(arch, "ppc") == 0 ) + onlyArchs.insert(CPU_TYPE_POWERPC); + else if ( strcmp(arch, "ppc64") == 0 ) + onlyArchs.insert(CPU_TYPE_POWERPC64); + else if ( strcmp(arch, "i386") == 0 ) + onlyArchs.insert(CPU_TYPE_I386); + else if ( strcmp(arch, "x86_64") == 0 ) + onlyArchs.insert(CPU_TYPE_X86_64); + else if ( strcmp(arch, "arm") == 0 ) + onlyArchs.insert(CPU_TYPE_ARM); + else + throwf("unknown architecture %s", arch); + } + else { + throwf("unknown option: %s\n", arg); + } + } + else { + files.push_back(arg); + } + } + + // use all architectures if no restrictions specified + if ( onlyArchs.size() == 0 ) { + onlyArchs.insert(CPU_TYPE_POWERPC); + onlyArchs.insert(CPU_TYPE_POWERPC64); + onlyArchs.insert(CPU_TYPE_I386); + onlyArchs.insert(CPU_TYPE_X86_64); + onlyArchs.insert(CPU_TYPE_ARM); + } + + // process each file + for(std::vector::iterator it=files.begin(); it != files.end(); ++it) { + dump(*it, onlyArchs); + } + + } + catch (const char* msg) { + fprintf(stderr, "UnwindDump failed: %s\n", msg); + return 1; + } + + return 0; +} + + + diff --git a/unit-tests/README b/unit-tests/README old mode 100755 new mode 100644 diff --git a/unit-tests/include/common.makefile b/unit-tests/include/common.makefile old mode 100755 new mode 100644 index 70e05f8..7222efa --- a/unit-tests/include/common.makefile +++ b/unit-tests/include/common.makefile @@ -9,16 +9,31 @@ ARCH ?= $(shell arch) VALID_ARCHS ?= "ppc ppc64 i386 x86_64 armv6" MYDIR=$(shell cd ../../bin;pwd) +LD = ld +OBJECTDUMP = ObjectDump +MACHOCHECK = machocheck +OTOOL = otool +REBASE = rebase -# if run within Xcode, add the just built tools to the command path ifdef BUILT_PRODUCTS_DIR + # if run within Xcode, add the just built tools to the command path PATH := ${BUILT_PRODUCTS_DIR}:${MYDIR}:${PATH} COMPILER_PATH := ${BUILT_PRODUCTS_DIR}:${MYDIR}:${COMPILER_PATH} + LD = ${BUILT_PRODUCTS_DIR}/ld + OBJECTDUMP = ${BUILT_PRODUCTS_DIR}/ObjectDump + MACHOCHECK = ${BUILT_PRODUCTS_DIR}/machocheck + REBASE = ${BUILT_PRODUCTS_DIR}/rebase else ifneq "$(findstring /unit-tests/test-cases/, $(shell pwd))" "" + # if run from Terminal inside unit-test directory RELEASEDIR=$(shell cd ../../../build/Release;pwd) - PATH := ${RELEASEDIR}:${MYDIR}:${PATH} - COMPILER_PATH := ${RELEASEDIR}:${MYDIR}:${COMPILER_PATH} + DEBUGDIR=$(shell cd ../../../build/Debug;pwd) + PATH := ${RELEASEDIR}:${DEBUGDIR}:${MYDIR}:${PATH} + COMPILER_PATH := ${RELEASEDIR}:${DEBUGDIR}:${MYDIR}:${COMPILER_PATH} + LD = ${RELEASEDIR}/ld + OBJECTDUMP = ${RELEASEDIR}/ObjectDump + MACHOCHECK = ${RELEASEDIR}/machocheck + REBASE = ${RELEASEDIR}/rebase else PATH := ${MYDIR}:${PATH}: COMPILER_PATH := ${MYDIR}:${COMPILER_PATH}: @@ -27,27 +42,33 @@ endif export PATH export COMPILER_PATH -LD = ld -OBJECTDUMP = ObjectDump -MACHOCHECK = machocheck -OTOOL = otool -CC = gcc-4.0 -arch ${ARCH} +CC = gcc-4.2 -arch ${ARCH} ${SDKExtra} CCFLAGS = -Wall -std=c99 ASMFLAGS = -CXX = g++-4.0 -arch ${ARCH} +CXX = g++-4.2 -arch ${ARCH} ${SDKExtra} CXXFLAGS = -Wall ifeq ($(ARCH),armv6) - LDFLAGS := -syslibroot /Developer/SDKs/Purple + SDKExtra = -isysroot /Developer/SDKs/Extra + LDFLAGS := -syslibroot /Developer/SDKs/Extra + override FILEARCH = arm +else + FILEARCH = $(ARCH) +endif + +ifeq ($(ARCH),armv7) + SDKExtra = -isysroot /Developer/SDKs/Extra + LDFLAGS := -syslibroot /Developer/SDKs/Extra override FILEARCH = arm else FILEARCH = $(ARCH) endif ifeq ($(ARCH),thumb) - LDFLAGS := -syslibroot /Developer/SDKs/Purple + SDKExtra = -isysroot /Developer/SDKs/Extra + LDFLAGS := -syslibroot /Developer/SDKs/Extra CCFLAGS += -mthumb CXXFLAGS += -mthumb override ARCH = armv6 @@ -56,21 +77,33 @@ else FILEARCH = $(ARCH) endif +ifeq ($(ARCH),thumb2) + SDKExtra = -isysroot /Developer/SDKs/Extra + LDFLAGS := -syslibroot /Developer/SDKs/Extra + CCFLAGS += -mthumb + CXXFLAGS += -mthumb + override ARCH = armv7 + override FILEARCH = arm + CC = /Volumes/Leopard/Developer/Platforms/iPhoneOS.platform/usr/bin/gcc-4.2 -arch ${ARCH} +else + FILEARCH = $(ARCH) +endif + RM = rm RMFLAGS = -rf # utilites for Makefiles -PASS_IFF = pass-iff-exit-zero.pl +PASS_IFF = ${MYDIR}/pass-iff-exit-zero.pl PASS_IFF_SUCCESS = ${PASS_IFF} -PASS_IFF_EMPTY = pass-iff-no-stdin.pl -PASS_IFF_STDIN = pass-iff-stdin.pl -FAIL_IFF = fail-iff-exit-zero.pl +PASS_IFF_EMPTY = ${MYDIR}/pass-iff-no-stdin.pl +PASS_IFF_STDIN = ${MYDIR}/pass-iff-stdin.pl +FAIL_IFF = ${MYDIR}/fail-iff-exit-zero.pl FAIL_IFF_SUCCESS = ${FAIL_IFF} -PASS_IFF_ERROR = pass-iff-exit-non-zero.pl -FAIL_IF_ERROR = fail-if-exit-non-zero.pl -FAIL_IF_SUCCESS = fail-if-exit-zero.pl -FAIL_IF_EMPTY = fail-if-no-stdin.pl -FAIL_IF_STDIN = fail-if-stdin.pl +PASS_IFF_ERROR = ${MYDIR}/pass-iff-exit-non-zero.pl +FAIL_IF_ERROR = ${MYDIR}/fail-if-exit-non-zero.pl +FAIL_IF_SUCCESS = ${MYDIR}/fail-if-exit-zero.pl +FAIL_IF_EMPTY = ${MYDIR}/fail-if-no-stdin.pl +FAIL_IF_STDIN = ${MYDIR}/fail-if-stdin.pl PASS_IFF_GOOD_MACHO = ${PASS_IFF} ${MACHOCHECK} FAIL_IF_BAD_MACHO = ${FAIL_IF_ERROR} ${MACHOCHECK} FAIL_IF_BAD_OBJ = ${FAIL_IF_ERROR} ${OBJECTDUMP} >/dev/null diff --git a/unit-tests/include/test.h b/unit-tests/include/test.h old mode 100755 new mode 100644 diff --git a/unit-tests/run-all-unit-tests b/unit-tests/run-all-unit-tests index e21c2b3..fa96968 100755 --- a/unit-tests/run-all-unit-tests +++ b/unit-tests/run-all-unit-tests @@ -11,13 +11,16 @@ cd `echo "$0" | sed 's/run-all-unit-tests/test-cases/'` [ "$PROCTORRUN" ] && exec ../proctor-run -all_archs="x86_64 armv6 thumb ppc ppc64 i386 " -valid_archs="x86_64 armv6 ppc ppc64 i386 " +all_archs="x86_64 ppc i386 " +#armv6 thumb +valid_archs="x86_64 armv6 ppc i386 " # clean first ../bin/make-recursive.pl clean > /dev/null mkdir /tmp/$$ +mkdir $BUILD_ROOT/lib +ln -s /Developer/usr/lib/libLTO.dylib ${BUILD_ROOT}/lib/libLTO.dylib for arch in $all_archs do echo "" diff --git a/unit-tests/src/Makefile b/unit-tests/src/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/src/results-to-xml.cpp b/unit-tests/src/results-to-xml.cpp old mode 100755 new mode 100644 diff --git a/unit-tests/src/xmlparser/xmlparser.1 b/unit-tests/src/xmlparser/xmlparser.1 old mode 100755 new mode 100644 diff --git a/unit-tests/src/xmlparser/xmlparser.m b/unit-tests/src/xmlparser/xmlparser.m old mode 100755 new mode 100644 diff --git a/unit-tests/src/xmlparser/xmlparser.xcodeproj/project.pbxproj b/unit-tests/src/xmlparser/xmlparser.xcodeproj/project.pbxproj old mode 100755 new mode 100644 diff --git a/unit-tests/src/xmlparser/xmlparser_Prefix.pch b/unit-tests/src/xmlparser/xmlparser_Prefix.pch old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/16-byte-alignment/Makefile b/unit-tests/test-cases/16-byte-alignment/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/16-byte-alignment/comment.txt b/unit-tests/test-cases/16-byte-alignment/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/16-byte-alignment/tl_test2.c b/unit-tests/test-cases/16-byte-alignment/tl_test2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/absolute-symbol/Makefile b/unit-tests/test-cases/absolute-symbol/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/absolute-symbol/abs.s b/unit-tests/test-cases/absolute-symbol/abs.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/absolute-symbol/main.c b/unit-tests/test-cases/absolute-symbol/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/alias-command-line/Makefile b/unit-tests/test-cases/alias-command-line/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/alias-command-line/aliases.s b/unit-tests/test-cases/alias-command-line/aliases.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/alias-command-line/aliases.txt b/unit-tests/test-cases/alias-command-line/aliases.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/alias-objects/Makefile b/unit-tests/test-cases/alias-objects/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/alias-objects/aliases.s b/unit-tests/test-cases/alias-objects/aliases.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/align-modulus/Makefile b/unit-tests/test-cases/align-modulus/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/align-modulus/align.s b/unit-tests/test-cases/align-modulus/align.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/align-modulus/comment.txt b/unit-tests/test-cases/align-modulus/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/align-modulus/foo.c b/unit-tests/test-cases/align-modulus/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/align-modulus/foo.exp b/unit-tests/test-cases/align-modulus/foo.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allow-stack-execute/Makefile b/unit-tests/test-cases/allow-stack-execute/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allow-stack-execute/comment.txt b/unit-tests/test-cases/allow-stack-execute/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allow-stack-execute/foo.c b/unit-tests/test-cases/allow-stack-execute/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/Makefile b/unit-tests/test-cases/allowable-client/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/bar.c b/unit-tests/test-cases/allowable-client/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/baz.c b/unit-tests/test-cases/allowable-client/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/comment.txt b/unit-tests/test-cases/allowable-client/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/foo.c b/unit-tests/test-cases/allowable-client/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/allowable-client/main.c b/unit-tests/test-cases/allowable-client/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-ObjC/Makefile b/unit-tests/test-cases/archive-ObjC/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-ObjC/bar.c b/unit-tests/test-cases/archive-ObjC/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-ObjC/baz.m b/unit-tests/test-cases/archive-ObjC/baz.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-ObjC/foo.m b/unit-tests/test-cases/archive-ObjC/foo.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-ObjC/main.c b/unit-tests/test-cases/archive-ObjC/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-basic/Makefile b/unit-tests/test-cases/archive-basic/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-basic/bar.c b/unit-tests/test-cases/archive-basic/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-basic/comment.txt b/unit-tests/test-cases/archive-basic/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-basic/foo.c b/unit-tests/test-cases/archive-basic/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-basic/main.c b/unit-tests/test-cases/archive-basic/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-duplicate/Makefile b/unit-tests/test-cases/archive-duplicate/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-duplicate/bar.c b/unit-tests/test-cases/archive-duplicate/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-duplicate/foo.c b/unit-tests/test-cases/archive-duplicate/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-duplicate/main.c b/unit-tests/test-cases/archive-duplicate/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-force-load/Makefile b/unit-tests/test-cases/archive-force-load/Makefile new file mode 100644 index 0000000..132fdbd --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/Makefile @@ -0,0 +1,48 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check the -force_load option. +# Need a linker option to load all objects from one library +# + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + ${CC} ${CCFLAGS} bar.c -c -o bar.o + ${CC} ${CCFLAGS} baz.c -c -o baz.o + ${CC} ${CCFLAGS} bat.c -c -o bat.o + libtool -static foo.o bar.o -o libfoobar.a + libtool -static baz.o bat.o -o libbazbat.a + ${CC} ${CCFLAGS} main.c -Wl,-force_load,libfoobar.a libbazbat.a -o main -Wl,-why_load + nm main | grep "_bar" | ${FAIL_IF_EMPTY} + nm main | grep "_foo" | ${FAIL_IF_EMPTY} + nm main | grep "_baz" | ${FAIL_IF_STDIN} + nm main | grep "_bat" | ${FAIL_IF_STDIN} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm -rf main *.o *.a diff --git a/unit-tests/test-cases/archive-force-load/bar.c b/unit-tests/test-cases/archive-force-load/bar.c new file mode 100644 index 0000000..e425999 --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/bar.c @@ -0,0 +1 @@ +void bar() {} diff --git a/unit-tests/test-cases/archive-force-load/bat.c b/unit-tests/test-cases/archive-force-load/bat.c new file mode 100644 index 0000000..f5a7956 --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/bat.c @@ -0,0 +1 @@ +void bat() {} diff --git a/unit-tests/test-cases/archive-force-load/baz.c b/unit-tests/test-cases/archive-force-load/baz.c new file mode 100644 index 0000000..4b361f6 --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/baz.c @@ -0,0 +1,2 @@ +void baz() {} + diff --git a/unit-tests/test-cases/archive-force-load/foo.c b/unit-tests/test-cases/archive-force-load/foo.c new file mode 100644 index 0000000..85e6cd8 --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/foo.c @@ -0,0 +1 @@ +void foo() {} diff --git a/unit-tests/test-cases/archive-force-load/main.c b/unit-tests/test-cases/archive-force-load/main.c new file mode 100644 index 0000000..fc047f7 --- /dev/null +++ b/unit-tests/test-cases/archive-force-load/main.c @@ -0,0 +1,5 @@ + +int main() +{ + return 0; +} diff --git a/unit-tests/test-cases/archive-weak/Makefile b/unit-tests/test-cases/archive-weak/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-weak/bar.c b/unit-tests/test-cases/archive-weak/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-weak/baz.c b/unit-tests/test-cases/archive-weak/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-weak/comment.txt b/unit-tests/test-cases/archive-weak/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-weak/foo.c b/unit-tests/test-cases/archive-weak/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/archive-weak/main.c b/unit-tests/test-cases/archive-weak/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/auto-arch/Makefile b/unit-tests/test-cases/auto-arch/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/auto-arch/hello.c b/unit-tests/test-cases/auto-arch/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/blank-stubs/Makefile b/unit-tests/test-cases/blank-stubs/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/blank-stubs/comment.txt b/unit-tests/test-cases/blank-stubs/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/blank-stubs/foo.c b/unit-tests/test-cases/blank-stubs/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/blank-stubs/main.c b/unit-tests/test-cases/blank-stubs/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/branch-distance/Makefile b/unit-tests/test-cases/branch-distance/Makefile new file mode 100644 index 0000000..46472ee --- /dev/null +++ b/unit-tests/test-cases/branch-distance/Makefile @@ -0,0 +1,44 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + + +# +# test thumb2 branch ranges +# + +run: all + + +all: + ${CC} ${CCFLAGS} foo.s -c + ${CC} ${CCFLAGS} bar.s -c + ${CC} ${CCFLAGS} foo.o bar.o -e _foo -o foobar ${ARCH_FLAGS} -nostdlib + ${LD} -arch ${ARCH} -r foo.o bar.o -o foobar.o + ${CC} ${CCFLAGS} foobar.o -e _foo -o foobar2 ${ARCH_FLAGS} -nostdlib + ${PASS_IFF_GOOD_MACHO} foobar + +clean: + rm *.o foobar* diff --git a/unit-tests/test-cases/branch-distance/bar.s b/unit-tests/test-cases/branch-distance/bar.s new file mode 100644 index 0000000..5b1f6dd --- /dev/null +++ b/unit-tests/test-cases/branch-distance/bar.s @@ -0,0 +1,21 @@ + + .text +#if __thumb__ + .thumb_func _bar + .code 16 +#endif + + .globl _bar +_bar: + nop +#if __arm__ + bl _foo + blx _foo +// b _foo +#endif + + + + + .subsections_via_symbols + \ No newline at end of file diff --git a/unit-tests/test-cases/branch-distance/foo.s b/unit-tests/test-cases/branch-distance/foo.s new file mode 100644 index 0000000..18f3a81 --- /dev/null +++ b/unit-tests/test-cases/branch-distance/foo.s @@ -0,0 +1,33 @@ + + + .text + +#if __thumb__ + .thumb_func _foo + .code 16 +#endif + .globl _foo +_foo: + nop +#if __arm__ + bl _bar + blx _bar +// b _bar + + +_space1: + +#if __thumb2__ + .space 16*1024*1024 -100 +#elif __thumb__ + .space 4*1024*1024 -100 +#else + .space 16*1024*1024 -100 +#endif + +#endif // __arm__ + + + + .subsections_via_symbols + \ No newline at end of file diff --git a/unit-tests/test-cases/branch-islands/Makefile b/unit-tests/test-cases/branch-islands/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/branch-islands/extra.c b/unit-tests/test-cases/branch-islands/extra.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/branch-islands/hello.c b/unit-tests/test-cases/branch-islands/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/branch-islands/space.s b/unit-tests/test-cases/branch-islands/space.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/bundle_loader/Makefile b/unit-tests/test-cases/bundle_loader/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/bundle_loader/bar.c b/unit-tests/test-cases/bundle_loader/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/bundle_loader/bundle.c b/unit-tests/test-cases/bundle_loader/bundle.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/bundle_loader/main.c b/unit-tests/test-cases/bundle_loader/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cfstring-coalesce/Makefile b/unit-tests/test-cases/cfstring-coalesce/Makefile old mode 100755 new mode 100644 index c1ca816..c8b16ee --- a/unit-tests/test-cases/cfstring-coalesce/Makefile +++ b/unit-tests/test-cases/cfstring-coalesce/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -23,6 +23,8 @@ TESTROOT = ../.. include ${TESTROOT}/include/common.makefile +SHELL = bash # use bash shell so we can redirect just stderr + # # Test that cfstring literals are coalesced and dead stripped # There is 3 CFSTR in foo.c and 1 CFSTR in bar.c @@ -31,10 +33,8 @@ include ${TESTROOT}/include/common.makefile ifeq (,${findstring 64,$(ARCH)}) CFSTRING_SIZE = 16 - CFSTRING_SIZE_WRITABLE = 32 else CFSTRING_SIZE = 32 - CFSTRING_SIZE_WRITABLE = 64 endif @@ -45,8 +45,8 @@ all: ${CC} ${CCFLAGS} foo.c bar.c -o foo -framework CoreFoundation -dead_strip size -l foo | grep "__cfstring: ${CFSTRING_SIZE}" | ${FAIL_IF_EMPTY} # now try with -fwritable-strings - ${CC} ${CCFLAGS} foo.c bar.c -o foo_writable -framework CoreFoundation -dead_strip -fwritable-strings - size -l foo_writable | grep "__cfstring: ${CFSTRING_SIZE_WRITABLE}" | ${PASS_IFF_STDIN} + ${CC} ${CCFLAGS} foo.c bar.c -o foo_writable -framework CoreFoundation -dead_strip -fwritable-strings 2>/dev/null + size -l foo_writable | grep "__cfstring: ${CFSTRING_SIZE}" | ${PASS_IFF_STDIN} clean: rm -rf foo foo_writable diff --git a/unit-tests/test-cases/cfstring-coalesce/bar.c b/unit-tests/test-cases/cfstring-coalesce/bar.c old mode 100755 new mode 100644 index 9a84abd..b78cd63 --- a/unit-tests/test-cases/cfstring-coalesce/bar.c +++ b/unit-tests/test-cases/cfstring-coalesce/bar.c @@ -1,5 +1,6 @@ #include +CFStringRef OtherCFString = CFSTR("other"); void bar() { diff --git a/unit-tests/test-cases/cfstring-coalesce/foo.c b/unit-tests/test-cases/cfstring-coalesce/foo.c old mode 100755 new mode 100644 index fe1b30e..a5c794e --- a/unit-tests/test-cases/cfstring-coalesce/foo.c +++ b/unit-tests/test-cases/cfstring-coalesce/foo.c @@ -2,10 +2,13 @@ extern void bar(); +extern CFStringRef OtherCFString; + void foo() { CFStringGetLength(CFSTR("hello")); CFStringGetLength(CFSTR("world")); + CFStringGetLength(OtherCFString); } diff --git a/unit-tests/test-cases/cfstring-utf16/Makefile b/unit-tests/test-cases/cfstring-utf16/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cfstring-utf16/bar.m b/unit-tests/test-cases/cfstring-utf16/bar.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cfstring-utf16/foo.m b/unit-tests/test-cases/cfstring-utf16/foo.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/coalesce_weak_def_in_dylib/Makefile b/unit-tests/test-cases/coalesce_weak_def_in_dylib/Makefile new file mode 100644 index 0000000..72f365b --- /dev/null +++ b/unit-tests/test-cases/coalesce_weak_def_in_dylib/Makefile @@ -0,0 +1,55 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test the if all symbols from a dylib are weak_import, that the whole dylib is weakly loaded +# + +run: all-${ARCH} + + +all-ppc: + ${PASS_IFF} true + +all-arm: + ${PASS_IFF} true + +all-i386: all-real + +all-x86_64: all-real + + +all-real: + ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib + ${FAIL_IF_BAD_MACHO} libfoo.dylib + + ${CC} ${CCFLAGS} main.c -o main libfoo.dylib + dyldinfo -bind main | grep wfoo | ${FAIL_IF_EMPTY} + + ${PASS_IFF_GOOD_MACHO} main + + +clean: + rm -rf libfoo.dylib main diff --git a/unit-tests/test-cases/coalesce_weak_def_in_dylib/foo.c b/unit-tests/test-cases/coalesce_weak_def_in_dylib/foo.c new file mode 100644 index 0000000..1906d16 --- /dev/null +++ b/unit-tests/test-cases/coalesce_weak_def_in_dylib/foo.c @@ -0,0 +1,4 @@ + + +__attribute__((weak)) void wfoo() {} +void foo() {} diff --git a/unit-tests/test-cases/coalesce_weak_def_in_dylib/main.c b/unit-tests/test-cases/coalesce_weak_def_in_dylib/main.c new file mode 100644 index 0000000..afd696d --- /dev/null +++ b/unit-tests/test-cases/coalesce_weak_def_in_dylib/main.c @@ -0,0 +1,17 @@ + +extern void foo(); +extern void wfoo(); + +void* pfoo = &foo; +void* pwfoo = &wfoo; + +int main (void) +{ + if (pfoo != &foo) + return 1; + if (pwfoo != &wfoo) + return 1; + + return 0; +} + diff --git a/unit-tests/test-cases/code-signed-object-file/Makefile b/unit-tests/test-cases/code-signed-object-file/Makefile new file mode 100644 index 0000000..4871de3 --- /dev/null +++ b/unit-tests/test-cases/code-signed-object-file/Makefile @@ -0,0 +1,26 @@ + +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that an object file can be code signed +# +# when linking a kext the static linker should leave a pad in the headers to allow code signing +# + +CODE_SIGN_ARCH = ${ARCH} +ifeq (${ARCH},ppc) + CODE_SIGN_ARCH = ppc7400 +endif + + +run: all + +all: + ${CC} foo.c -c -o foo.o + ${LD} -r foo.o -o foo2.o + codesign_allocate -i foo2.o -a ${CODE_SIGN_ARCH} 256 -o foo3.o + ${PASS_IFF} true + +clean: + rm foo.o foo2.o foo3.o diff --git a/unit-tests/test-cases/code-signed-object-file/foo.c b/unit-tests/test-cases/code-signed-object-file/foo.c new file mode 100644 index 0000000..85e6cd8 --- /dev/null +++ b/unit-tests/test-cases/code-signed-object-file/foo.c @@ -0,0 +1 @@ +void foo() {} diff --git a/unit-tests/test-cases/commons-alignment/Makefile b/unit-tests/test-cases/commons-alignment/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-alignment/foo.s b/unit-tests/test-cases/commons-alignment/foo.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-coalesced-dead_strip/Makefile b/unit-tests/test-cases/commons-coalesced-dead_strip/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-coalesced-dead_strip/a.c b/unit-tests/test-cases/commons-coalesced-dead_strip/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-coalesced-dead_strip/b.c b/unit-tests/test-cases/commons-coalesced-dead_strip/b.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-coalesced-dead_strip/c.c b/unit-tests/test-cases/commons-coalesced-dead_strip/c.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-coalesced-dead_strip/c.h b/unit-tests/test-cases/commons-coalesced-dead_strip/c.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-mixed/Makefile b/unit-tests/test-cases/commons-mixed/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-mixed/bar.c b/unit-tests/test-cases/commons-mixed/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-mixed/foo.c b/unit-tests/test-cases/commons-mixed/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/Makefile b/unit-tests/test-cases/commons-order/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/bar.c b/unit-tests/test-cases/commons-order/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/baz.c b/unit-tests/test-cases/commons-order/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/expected.order b/unit-tests/test-cases/commons-order/expected.order old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/foo.c b/unit-tests/test-cases/commons-order/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/commons-order/main.c b/unit-tests/test-cases/commons-order/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types-preference/Makefile b/unit-tests/test-cases/cpu-sub-types-preference/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types-preference/foo.c b/unit-tests/test-cases/cpu-sub-types-preference/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types/Makefile b/unit-tests/test-cases/cpu-sub-types/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types/comment.txt b/unit-tests/test-cases/cpu-sub-types/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types/foo.c b/unit-tests/test-cases/cpu-sub-types/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cpu-sub-types/main.c b/unit-tests/test-cases/cpu-sub-types/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/cstring-alt-segment/Makefile b/unit-tests/test-cases/cstring-alt-segment/Makefile new file mode 100644 index 0000000..4e55304 --- /dev/null +++ b/unit-tests/test-cases/cstring-alt-segment/Makefile @@ -0,0 +1,39 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that __cstring sections in other segments are not coalesced +# ld coalesces C strings in different segments +# + +run: all + +all: + ${CC} ${CCFLAGS} main.c custom.s -o main + size -l main | grep __cstring | wc -l | grep 2 | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm main diff --git a/unit-tests/test-cases/cstring-alt-segment/custom.s b/unit-tests/test-cases/cstring-alt-segment/custom.s new file mode 100644 index 0000000..33705e5 --- /dev/null +++ b/unit-tests/test-cases/cstring-alt-segment/custom.s @@ -0,0 +1,8 @@ + + + + .section __MYSEG, __cstring, cstring_literals +LC: .ascii "hello" + + + diff --git a/unit-tests/test-cases/cstring-alt-segment/main.c b/unit-tests/test-cases/cstring-alt-segment/main.c new file mode 100644 index 0000000..8fe18db --- /dev/null +++ b/unit-tests/test-cases/cstring-alt-segment/main.c @@ -0,0 +1,7 @@ +#include + +int main() +{ + printf("hello"); + return 0; +} diff --git a/unit-tests/test-cases/cstring-custom-section/Makefile b/unit-tests/test-cases/cstring-custom-section/Makefile new file mode 100644 index 0000000..628d045 --- /dev/null +++ b/unit-tests/test-cases/cstring-custom-section/Makefile @@ -0,0 +1,47 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that cstrings in custom sections are not uniqued with +# cstrings in the standard section. +# + +run: all + +all: + ${CC} ${CCFLAGS} -c foo.s -o foo.o + ${CC} ${CCFLAGS} -c bar.s -o bar.o + ${LD} -arch ${ARCH} -r foo.o bar.o -o foobar.o + size -l foobar.o | grep "(__TEXT, __cstring): 13" | ${FAIL_IF_EMPTY} + size -l foobar.o | grep "(__TEXT, __mystring): 15" | ${FAIL_IF_EMPTY} + otool -lv foobar.o | grep -A10 __mystring | grep S_CSTRING_LITERALS | ${FAIL_IF_EMPTY} + ${CC} ${CCFLAGS} foo.o bar.o -dynamiclib -o libfoobar.dylib + size -l libfoobar.dylib | grep "__cstring: 13" | ${FAIL_IF_EMPTY} + size -l libfoobar.dylib | grep "__mystring: 15" | ${FAIL_IF_EMPTY} + otool -lv libfoobar.dylib | grep -A10 __mystring | grep S_CSTRING_LITERALS | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} libfoobar.dylib + +clean: + rm foo.o bar.o libfoobar.dylib foobar.o diff --git a/unit-tests/test-cases/cstring-custom-section/bar.s b/unit-tests/test-cases/cstring-custom-section/bar.s new file mode 100644 index 0000000..6aba48b --- /dev/null +++ b/unit-tests/test-cases/cstring-custom-section/bar.s @@ -0,0 +1,31 @@ + .cstring +LC0: + .ascii "bar\0" +LC1: + .ascii "coal\0" + .text + + + .section __TEXT, __mystring, cstring_literals +LC4: + .ascii "bar\0" +LC5: + .ascii "mycoal\0" + + + .data +#if __LP64__ + .quad LC0 + .quad LC1 + .quad LC4 + .quad LC5 +#else + .long LC0 + .long LC1 + .long LC4 + .long LC5 +#endif + + .subsections_via_symbols + + diff --git a/unit-tests/test-cases/cstring-custom-section/foo.s b/unit-tests/test-cases/cstring-custom-section/foo.s new file mode 100644 index 0000000..a855c91 --- /dev/null +++ b/unit-tests/test-cases/cstring-custom-section/foo.s @@ -0,0 +1,31 @@ + .cstring +LC0: + .ascii "foo\0" +LC1: + .ascii "coal\0" + .text + + + .section __TEXT, __mystring, cstring_literals +LC4: + .ascii "foo\0" +LC5: + .ascii "mycoal\0" + + + .data +#if __LP64__ + .quad LC0 + .quad LC1 + .quad LC4 + .quad LC5 +#else + .long LC0 + .long LC1 + .long LC4 + .long LC5 +#endif + + .subsections_via_symbols + + diff --git a/unit-tests/test-cases/cstring-labels/Makefile b/unit-tests/test-cases/cstring-labels/Makefile new file mode 100644 index 0000000..1c6ee7d --- /dev/null +++ b/unit-tests/test-cases/cstring-labels/Makefile @@ -0,0 +1,56 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# ld -r for x86_64 is changing visibility of cstring constants +# +# In order to coalesce strings from different .o files, the linker internally +# makes them weak/hidden. Test to make sure that weak/hidden does not leak out. +# + +ifeq (${ARCH},x86_64) + STRING_LABEL_COUNT = 3 +else + STRING_LABEL_COUNT = 1 +endif + + + +run: all + +all: + ${CC} ${CCFLAGS} -c foo.c -o foo.o + ${CC} ${CCFLAGS} -c bar.c -o bar.o + ${LD} -arch ${ARCH} -r foo.o bar.o -o foobar.o + nm -nm foobar.o | grep __cstring | grep "weak private external" | ${FAIL_IF_STDIN} + ${LD} -arch ${ARCH} -r foo.o bar.o -o foobar.o -keep_private_externs + nm -nm foobar.o | grep __cstring | grep "weak private external" | ${FAIL_IF_STDIN} + nm -m foobar.o | grep __cstring | wc -l | grep ${STRING_LABEL_COUNT} | ${FAIL_IF_EMPTY} + ${CC} ${CCFLAGS} foo.o bar.o -dynamiclib -o libfoobar.dylib + nm -m libfoobar.dylib | grep __cstring | wc -l | grep 1 | ${FAIL_IF_EMPTY} + ${PASS_IFF} /usr/bin/true + +clean: + rm foo.o bar.o foobar.o libfoobar.dylib diff --git a/unit-tests/test-cases/cstring-labels/bar.c b/unit-tests/test-cases/cstring-labels/bar.c new file mode 100644 index 0000000..8b1d11d --- /dev/null +++ b/unit-tests/test-cases/cstring-labels/bar.c @@ -0,0 +1,2 @@ +const char* kBar = "hello"; +const char* kBar2 = "there"; diff --git a/unit-tests/test-cases/cstring-labels/foo.c b/unit-tests/test-cases/cstring-labels/foo.c new file mode 100644 index 0000000..0780b62 --- /dev/null +++ b/unit-tests/test-cases/cstring-labels/foo.c @@ -0,0 +1,6 @@ + +void func() {} + +const char kFoo[] = "foo"; + +const char* kFoo2 = "hello"; diff --git a/unit-tests/test-cases/implicit-common3/Makefile b/unit-tests/test-cases/dead_strip-archive-eh/Makefile old mode 100755 new mode 100644 similarity index 63% rename from unit-tests/test-cases/implicit-common3/Makefile rename to unit-tests/test-cases/dead_strip-archive-eh/Makefile index 6785960..a1d0207 --- a/unit-tests/test-cases/implicit-common3/Makefile +++ b/unit-tests/test-cases/dead_strip-archive-eh/Makefile @@ -1,15 +1,15 @@ ## -# Copyright (c) 2006 Apple Computer, Inc. All rights reserved. +# Copyright (c) 2008 Apple Inc. All rights reserved. # # @APPLE_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. 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, @@ -17,28 +17,29 @@ # 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_LICENSE_HEADER_END@ ## TESTROOT = ../.. include ${TESTROOT}/include/common.makefile # -# The point of this test is a sanity check that ld -# can link a program with a large zero-fill section +# Tests that a non-weak symbol in an archive cleanly overrides +# a weak symbol in a .o file with dead code stripping +# +# duplicate typeinfo in executable # run: all all: - ${CC} ${CCFLAGS} -c test.c -o test-${ARCH}.o - ${FAIL_IF_BAD_OBJ} test-${ARCH}.o - ${CC} ${CCFLAGS} -c a.c -o a-${ARCH}.o - ${FAIL_IF_BAD_OBJ} a-${ARCH}.o - ${FAIL_IF_ERROR} ar -r libtest-${ARCH}.a test-${ARCH}.o 2>/dev/null - ${FAIL_IF_ERROR} ranlib libtest-${ARCH}.a - ${CC} ${CCFLAGS} a-${ARCH}.o -L. -ltest-${ARCH} -o a-${ARCH} - ${PASS_IFF_GOOD_MACHO} a-${ARCH} + ${CXX} ${CXXFLAGS} foo.cxx -c -o foo.o + ${CXX} ${CXXFLAGS} bar.cxx -c -o bar.o + libtool -static foo.o bar.o -o libfoobar.a + ${CXX} ${CXXFLAGS} main.cxx libfoobar.a -dead_strip -o main + dwarfdump --eh-frame --verify main >/dev/null + ${PASS_IFF_GOOD_MACHO} main + clean: - rm -rf *.o *.a a-* + rm -rf main foo.o bar.o libfoobar.a diff --git a/unit-tests/test-cases/dead_strip-archive-eh/bar.cxx b/unit-tests/test-cases/dead_strip-archive-eh/bar.cxx new file mode 100644 index 0000000..1231527 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-eh/bar.cxx @@ -0,0 +1,14 @@ + +#include + +void doit() +{ + printf("hello there %s\n", "world"); + +} + +void bar() +{ + doit(); +} + diff --git a/unit-tests/test-cases/dead_strip-archive-eh/foo.cxx b/unit-tests/test-cases/dead_strip-archive-eh/foo.cxx new file mode 100644 index 0000000..e743d41 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-eh/foo.cxx @@ -0,0 +1,13 @@ +#include + +__attribute__((weak)) void doit() +{ + printf("hello %s\n", "world"); +} + + +void foo() +{ + doit(); +} + diff --git a/unit-tests/test-cases/dead_strip-archive-eh/main.cxx b/unit-tests/test-cases/dead_strip-archive-eh/main.cxx new file mode 100644 index 0000000..fc6eda5 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-eh/main.cxx @@ -0,0 +1,12 @@ + +extern void foo(); +extern void bar(); + +int main() +{ + foo(); + bar(); + return 0; +} + + diff --git a/unit-tests/test-cases/dead_strip-archive-global/Makefile b/unit-tests/test-cases/dead_strip-archive-global/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive-global/foo.c b/unit-tests/test-cases/dead_strip-archive-global/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive-global/main.c b/unit-tests/test-cases/dead_strip-archive-global/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive-weak/Makefile b/unit-tests/test-cases/dead_strip-archive-weak/Makefile new file mode 100644 index 0000000..c2d8f6c --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-weak/Makefile @@ -0,0 +1,44 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Tests that a non-weak symbol in an archive cleanly overrides +# a weak symbol in a .o file with dead code stripping +# +# duplicate typeinfo in executable +# + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + libtool -static foo.o -o libfoo.a + ${CC} ${CCFLAGS} main.c libfoo.a -dead_strip -o main + nm main | grep _foo | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + + +clean: + rm -rf main foo.o libfoo.a diff --git a/unit-tests/test-cases/dead_strip-archive-weak/foo.c b/unit-tests/test-cases/dead_strip-archive-weak/foo.c new file mode 100644 index 0000000..79184c7 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-weak/foo.c @@ -0,0 +1,13 @@ + +extern void good(); + +void foo() +{ + good(); +} + +void loadme() +{ +// foo(); +} + diff --git a/unit-tests/test-cases/dead_strip-archive-weak/main.c b/unit-tests/test-cases/dead_strip-archive-weak/main.c new file mode 100644 index 0000000..c082574 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-archive-weak/main.c @@ -0,0 +1,27 @@ + +extern void loadme(); + +void good() +{ +} + +void bad() +{ +} + +// foo is first found be dead stripping here +// then the use of loadme causes libfoo.a(foo.o) +// to be loaded which overrides foo +__attribute__((weak)) void foo() +{ + bad(); +} + +int main() +{ + foo(); + loadme(); + return 0; +} + + diff --git a/unit-tests/test-cases/dead_strip-archive/Makefile b/unit-tests/test-cases/dead_strip-archive/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive/comment.txt b/unit-tests/test-cases/dead_strip-archive/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive/foo.c b/unit-tests/test-cases/dead_strip-archive/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-archive/main.c b/unit-tests/test-cases/dead_strip-archive/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-init-archive/Makefile b/unit-tests/test-cases/dead_strip-init-archive/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-init-archive/bar.c b/unit-tests/test-cases/dead_strip-init-archive/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-init-archive/foo.c b/unit-tests/test-cases/dead_strip-init-archive/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip-r_symbol_desc/Makefile b/unit-tests/test-cases/dead_strip-r_symbol_desc/Makefile new file mode 100644 index 0000000..e60513e --- /dev/null +++ b/unit-tests/test-cases/dead_strip-r_symbol_desc/Makefile @@ -0,0 +1,43 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that N_NO_DEAD_STRIP bit survives ld -r +# + +run: all + +all: + ${CC} ${CCFLAGS} main.c -c -o main.o + nm -m main.o | grep _bar | grep "no dead strip" | ${FAIL_IF_EMPTY} + nm -m main.o | grep _foo | grep "no dead strip" | ${FAIL_IF_EMPTY} + ${LD} -r main.o -o main2.o + nm -m main2.o | grep _bar | grep "no dead strip" | ${FAIL_IF_EMPTY} + nm -m main2.o | grep _foo | grep "no dead strip" | ${FAIL_IF_EMPTY} + ${CC} main2.o -o main + nm -m main | grep _bar | grep "no dead strip" | ${PASS_IFF_EMPTY} + +clean: + rm -rf main.o main2.o main diff --git a/unit-tests/test-cases/implicit-common3/test.c b/unit-tests/test-cases/dead_strip-r_symbol_desc/main.c old mode 100755 new mode 100644 similarity index 83% rename from unit-tests/test-cases/implicit-common3/test.c rename to unit-tests/test-cases/dead_strip-r_symbol_desc/main.c index e0fd7e8..7e206e5 --- a/unit-tests/test-cases/implicit-common3/test.c +++ b/unit-tests/test-cases/dead_strip-r_symbol_desc/main.c @@ -1,6 +1,6 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * - * Copyright (c) 2006 Apple Computer, Inc. All rights reserved. + * Copyright (c) 2009 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -22,16 +22,20 @@ * @APPLE_LICENSE_HEADER_END@ */ -struct abc { - int a; - int b; - int c; -} struct_var; -int common_var; -extern const int defined_var; +__attribute__((used)) static void foo() +{ +} + + +__attribute__((used)) void bar() +{ +} + -int *fn() +int main() { - return &common_var; + foo(); + bar(); + return 0; } diff --git a/unit-tests/test-cases/dead_strip-weak-coalesce/Makefile b/unit-tests/test-cases/dead_strip-weak-coalesce/Makefile new file mode 100644 index 0000000..45886c0 --- /dev/null +++ b/unit-tests/test-cases/dead_strip-weak-coalesce/Makefile @@ -0,0 +1,41 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that symbols in no-dead-strip sections can be coalesced. +# -dead_strip inhibits weak coalescing in no_dead_strip section +# + +run: all + +all: + ${CC} ${CCFLAGS} baz.c -c -o baz.o + libtool -static baz.o -o libbaz.a + ${CC} ${CCFLAGS} main.c foo.c libbaz.a -dead_strip -o main + nm -j main | grep _hidden | wc -l | grep 1 | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm -rf main baz.o libbaz.a diff --git a/unit-tests/test-cases/dead_strip-weak-coalesce/baz.c b/unit-tests/test-cases/dead_strip-weak-coalesce/baz.c new file mode 100644 index 0000000..7d76bdd --- /dev/null +++ b/unit-tests/test-cases/dead_strip-weak-coalesce/baz.c @@ -0,0 +1,7 @@ +void baz() +{ +} + + +#include "foo.c" + diff --git a/unit-tests/test-cases/dead_strip-weak-coalesce/foo.c b/unit-tests/test-cases/dead_strip-weak-coalesce/foo.c new file mode 100644 index 0000000..4cd4cfb --- /dev/null +++ b/unit-tests/test-cases/dead_strip-weak-coalesce/foo.c @@ -0,0 +1,25 @@ + +// function can be coalesced and should not be dead stripped +void __attribute__ ((weak, section ("__TEXT,__text_no_strip,regular,no_dead_strip"))) foo() +{ + +} + + +// function should not be exported, can be coalesced, and should not be dead stripped +void __attribute__ ((weak, visibility("hidden"), section ("__TEXT,__text_no_strip,regular,no_dead_strip"))) hidden() +{ + +} + +// bar should be dead stripped +void __attribute__ ((weak, section ("__DATA,__text2"))) bar() +{ + +} + +__attribute__((constructor)) static void init() +{ + foo(); + hidden(); +} diff --git a/unit-tests/test-cases/dead_strip-weak-coalesce/main.c b/unit-tests/test-cases/dead_strip-weak-coalesce/main.c new file mode 100644 index 0000000..e4c564c --- /dev/null +++ b/unit-tests/test-cases/dead_strip-weak-coalesce/main.c @@ -0,0 +1,13 @@ + +// baz is in a lazily loaded archive +extern void baz(); + +int main() +{ + baz(); + return 0; +} + + +#include "foo.c" + diff --git a/unit-tests/test-cases/dead_strip/Makefile b/unit-tests/test-cases/dead_strip/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip/comment.txt b/unit-tests/test-cases/dead_strip/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip/deadwood.c b/unit-tests/test-cases/dead_strip/deadwood.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip/main.c b/unit-tests/test-cases/dead_strip/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip/main.exp b/unit-tests/test-cases/dead_strip/main.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_dylibs/Makefile b/unit-tests/test-cases/dead_strip_dylibs/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_dylibs/bar.c b/unit-tests/test-cases/dead_strip_dylibs/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_dylibs/baz.c b/unit-tests/test-cases/dead_strip_dylibs/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_dylibs/foo.c b/unit-tests/test-cases/dead_strip_dylibs/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_dylibs/main.c b/unit-tests/test-cases/dead_strip_dylibs/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_section_attribute/Makefile b/unit-tests/test-cases/dead_strip_section_attribute/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_section_attribute/comment.txt b/unit-tests/test-cases/dead_strip_section_attribute/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strip_section_attribute/main.c b/unit-tests/test-cases/dead_strip_section_attribute/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dead_strippable_dylib/Makefile b/unit-tests/test-cases/dead_strippable_dylib/Makefile new file mode 100644 index 0000000..46cc5b4 --- /dev/null +++ b/unit-tests/test-cases/dead_strippable_dylib/Makefile @@ -0,0 +1,50 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test -mark_dead_strippable_dylib +# +# foo is used. +# bar is not used by should still be linked +# baz is not used and should be automatically not linked +# + + +run: all + +all: + ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib + ${CC} ${CCFLAGS} -dynamiclib bar.c -o libbar.dylib + ${CC} ${CCFLAGS} -dynamiclib baz.c -o libbaz.dylib -Wl,-mark_dead_strippable_dylib + ${CC} ${CCFLAGS} main.c libfoo.dylib libbar.dylib libbaz.dylib -o main + otool -L main | grep libfoo.dylib | ${FAIL_IF_EMPTY} + otool -L main | grep libbar.dylib | ${FAIL_IF_EMPTY} + otool -L main | grep libbaz.dylib | ${FAIL_IF_STDIN} + ${PASS_IFF_GOOD_MACHO} main + + +clean: + + rm -rf libbar.dylib libfoo.dylib libbaz.dylib main diff --git a/unit-tests/test-cases/dead_strippable_dylib/bar.c b/unit-tests/test-cases/dead_strippable_dylib/bar.c new file mode 100644 index 0000000..9c18401 --- /dev/null +++ b/unit-tests/test-cases/dead_strippable_dylib/bar.c @@ -0,0 +1,5 @@ + +int bar (void) +{ + return 1; +} diff --git a/unit-tests/test-cases/dead_strippable_dylib/baz.c b/unit-tests/test-cases/dead_strippable_dylib/baz.c new file mode 100644 index 0000000..af6a9f8 --- /dev/null +++ b/unit-tests/test-cases/dead_strippable_dylib/baz.c @@ -0,0 +1,5 @@ + +int baz (void) +{ + return 1; +} diff --git a/unit-tests/test-cases/dead_strippable_dylib/foo.c b/unit-tests/test-cases/dead_strippable_dylib/foo.c new file mode 100644 index 0000000..d0cdf47 --- /dev/null +++ b/unit-tests/test-cases/dead_strippable_dylib/foo.c @@ -0,0 +1,4 @@ +int foo (void) +{ + return 1; +} diff --git a/unit-tests/test-cases/dead_strippable_dylib/main.c b/unit-tests/test-cases/dead_strippable_dylib/main.c new file mode 100644 index 0000000..4f56fe0 --- /dev/null +++ b/unit-tests/test-cases/dead_strippable_dylib/main.c @@ -0,0 +1,8 @@ + +extern void foo(); + +int main() +{ + foo(); + return 0; +} diff --git a/unit-tests/test-cases/dtrace-static-probes-coalescing/Makefile b/unit-tests/test-cases/dtrace-static-probes-coalescing/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes-coalescing/Number.d b/unit-tests/test-cases/dtrace-static-probes-coalescing/Number.d old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes-coalescing/a.cxx b/unit-tests/test-cases/dtrace-static-probes-coalescing/a.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes-coalescing/header.h b/unit-tests/test-cases/dtrace-static-probes-coalescing/header.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes-coalescing/x.cxx b/unit-tests/test-cases/dtrace-static-probes-coalescing/x.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes/Makefile b/unit-tests/test-cases/dtrace-static-probes/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes/bar.d b/unit-tests/test-cases/dtrace-static-probes/bar.d old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes/comment.txt b/unit-tests/test-cases/dtrace-static-probes/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes/foo.d b/unit-tests/test-cases/dtrace-static-probes/foo.d old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dtrace-static-probes/main.c b/unit-tests/test-cases/dtrace-static-probes/main.c old mode 100755 new mode 100644 index 8a417e9..79ce4eb --- a/unit-tests/test-cases/dtrace-static-probes/main.c +++ b/unit-tests/test-cases/dtrace-static-probes/main.c @@ -10,7 +10,8 @@ typedef int weirdType2; int deadwood() { - BAR_COUNT1(2); + if ( BAR_COUNT1_ENABLED() ) + BAR_COUNT1(2); return 0; } @@ -19,9 +20,11 @@ int main() { int a = 1; while(a) { - FOO_COUNT1(1); + if ( FOO_COUNT1_ENABLED() ) + FOO_COUNT1(1); printf("test\n"); - BAR_COUNT1(2); + if ( BAR_COUNT1_ENABLED() ) + BAR_COUNT1(2); sleep(1); } diff --git a/unit-tests/test-cases/dwarf-archive-all_load/Makefile b/unit-tests/test-cases/dwarf-archive-all_load/Makefile old mode 100755 new mode 100644 index 8d38d99..aa02b11 --- a/unit-tests/test-cases/dwarf-archive-all_load/Makefile +++ b/unit-tests/test-cases/dwarf-archive-all_load/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -36,7 +36,7 @@ run: ${CC} ${CCFLAGS} -gdwarf-2 baz.c -c -o baz.o ${FAIL_IF_BAD_OBJ} baz.o libtool -static bar.o baz.o foo.o -o liball.a - ${CC} ${CCFLAGS} liball.a -all_load -dynamiclib -o liball.dylib -nodefaultlibs + ${CC} ${CCFLAGS} liball.a -all_load -dynamiclib -o liball.dylib -nodefaultlibs -lSystem ${FAIL_IF_BAD_MACHO} liball.dylib nm -fap liball.dylib | ./stabs-filter.pl > liball.dylib.stabs ${PASS_IFF} diff liball.dylib.stabs expected-stabs diff --git a/unit-tests/test-cases/dwarf-archive-all_load/bar.c b/unit-tests/test-cases/dwarf-archive-all_load/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-archive-all_load/baz.c b/unit-tests/test-cases/dwarf-archive-all_load/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-archive-all_load/comment.txt b/unit-tests/test-cases/dwarf-archive-all_load/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-archive-all_load/expected-stabs b/unit-tests/test-cases/dwarf-archive-all_load/expected-stabs old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-archive-all_load/foo.c b/unit-tests/test-cases/dwarf-archive-all_load/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/Makefile b/unit-tests/test-cases/dwarf-debug-notes-r/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/bar.cxx b/unit-tests/test-cases/dwarf-debug-notes-r/bar.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/comment.txt b/unit-tests/test-cases/dwarf-debug-notes-r/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/expected-stabs b/unit-tests/test-cases/dwarf-debug-notes-r/expected-stabs old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/foo.cxx b/unit-tests/test-cases/dwarf-debug-notes-r/foo.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes-r/main.cxx b/unit-tests/test-cases/dwarf-debug-notes-r/main.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes/Makefile b/unit-tests/test-cases/dwarf-debug-notes/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes/comment.txt b/unit-tests/test-cases/dwarf-debug-notes/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes/expected-stabs b/unit-tests/test-cases/dwarf-debug-notes/expected-stabs old mode 100755 new mode 100644 index 4ab634d..0ef639d --- a/unit-tests/test-cases/dwarf-debug-notes/expected-stabs +++ b/unit-tests/test-cases/dwarf-debug-notes/expected-stabs @@ -23,11 +23,11 @@ 0000 FUN 0000 ENSYM 0000 GSYM _init -0000 STSYM .my_non_standard_name 0000 STSYM .my_non_standard_name_static +0000 STSYM .my_non_standard_name 0000 STSYM __ZZ3bariE8bar_init 0000 GSYM _uninit -0000 STSYM _sinit -0000 STSYM _suninit +0000 STSYM __ZL7suninit +0000 STSYM __ZL5sinit 0000 STSYM __ZZ3bariE10bar_uninit 0000 SO diff --git a/unit-tests/test-cases/dwarf-debug-notes/header.h b/unit-tests/test-cases/dwarf-debug-notes/header.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes/hello.cxx b/unit-tests/test-cases/dwarf-debug-notes/hello.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-debug-notes/other.cxx b/unit-tests/test-cases/dwarf-debug-notes/other.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-ignore/Makefile b/unit-tests/test-cases/dwarf-ignore/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-ignore/comment.txt b/unit-tests/test-cases/dwarf-ignore/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-ignore/hello.c b/unit-tests/test-cases/dwarf-ignore/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-strip/Makefile b/unit-tests/test-cases/dwarf-strip/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-strip/comment.txt b/unit-tests/test-cases/dwarf-strip/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dwarf-strip/hello.c b/unit-tests/test-cases/dwarf-strip/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-aliases/Makefile b/unit-tests/test-cases/dylib-aliases/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-aliases/bar.c b/unit-tests/test-cases/dylib-aliases/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-aliases/foo.c b/unit-tests/test-cases/dylib-aliases/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-aliases/main.c b/unit-tests/test-cases/dylib-aliases/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-re-export-cycle/Makefile b/unit-tests/test-cases/dylib-re-export-cycle/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-re-export-cycle/bar.c b/unit-tests/test-cases/dylib-re-export-cycle/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-re-export-cycle/foo.c b/unit-tests/test-cases/dylib-re-export-cycle/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib-re-export-cycle/main.c b/unit-tests/test-cases/dylib-re-export-cycle/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file-missing/Makefile b/unit-tests/test-cases/dylib_file-missing/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file-missing/bar.c b/unit-tests/test-cases/dylib_file-missing/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file-missing/foo.c b/unit-tests/test-cases/dylib_file-missing/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file-missing/main.c b/unit-tests/test-cases/dylib_file-missing/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file/Makefile b/unit-tests/test-cases/dylib_file/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file/bar.c b/unit-tests/test-cases/dylib_file/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file/comment.txt b/unit-tests/test-cases/dylib_file/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file/foo.c b/unit-tests/test-cases/dylib_file/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_file/main.c b/unit-tests/test-cases/dylib_file/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_init/Makefile b/unit-tests/test-cases/dylib_init/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/dylib_init/foo.c b/unit-tests/test-cases/dylib_init/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing-no-labels/Makefile b/unit-tests/test-cases/eh-coalescing-no-labels/Makefile new file mode 100644 index 0000000..27cd180 --- /dev/null +++ b/unit-tests/test-cases/eh-coalescing-no-labels/Makefile @@ -0,0 +1,51 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + +SHELL = bash # use bash shell so we can redirect just stderr + + +# +# Verify label in __eh_frame can be removed with no impact +# +run: all + +all: + ${CC} ${CCXXFLAGS} foo.c -c -o foo.o -fexceptions + ${CC} ${CCXXFLAGS} bar.c -c -o bar.o -fexceptions + ${CC} ${CCXXFLAGS} baz.c -c -o baz.o -fexceptions + ${LD} -r foo.o -no_eh_labels -o foo.no.o + ${LD} -r bar.o -no_eh_labels -o bar.no.o + ${LD} -r baz.o -no_eh_labels -o baz.no.o + ${LD} -r foo.o bar.o baz.o -o foobarbaz.o + ${LD} -r foo.no.o bar.no.o baz.no.o -o foobarbaz.no.o + ${OBJECTDUMP} -no_content -no_sort foobarbaz.o > foobarbaz.dump + ${OBJECTDUMP} -no_content -no_sort foobarbaz.no.o > foobarbaz.no.dump + ${FAIL_IF_ERROR} dwarfdump --eh-frame --verify foobarbaz.no.o >/dev/null + ${PASS_IFF_SUCCESS} diff foobarbaz.dump foobarbaz.no.dump + + +clean: + rm -f foo.o bar.o baz.o foo.no.o bar.no.o baz.no.o foobarbaz.* diff --git a/unit-tests/test-cases/eh-coalescing-no-labels/bar.c b/unit-tests/test-cases/eh-coalescing-no-labels/bar.c new file mode 100644 index 0000000..9bdd4f4 --- /dev/null +++ b/unit-tests/test-cases/eh-coalescing-no-labels/bar.c @@ -0,0 +1,18 @@ + +extern void other(); + +void bar() { + other(); + other(); +} + +void __attribute__((weak)) my_weak() { + other(); + other(); +} + +void bar2() { + other(); + other(); +} + diff --git a/unit-tests/test-cases/eh-coalescing-no-labels/baz.c b/unit-tests/test-cases/eh-coalescing-no-labels/baz.c new file mode 100644 index 0000000..fcc3490 --- /dev/null +++ b/unit-tests/test-cases/eh-coalescing-no-labels/baz.c @@ -0,0 +1,18 @@ + +extern void other(); + +void baz() { + other(); + other(); +} + +void __attribute__((weak)) my_weak() { + other(); + other(); +} + +void baz2() { + other(); + other(); +} + diff --git a/unit-tests/test-cases/eh-coalescing-no-labels/foo.c b/unit-tests/test-cases/eh-coalescing-no-labels/foo.c new file mode 100644 index 0000000..22123ae --- /dev/null +++ b/unit-tests/test-cases/eh-coalescing-no-labels/foo.c @@ -0,0 +1,18 @@ + +extern void other(); + +void foo() { + other(); + other(); +} + +void __attribute__((weak)) my_weak() { + other(); + other(); +} + +void foo2() { + other(); + other(); +} + diff --git a/unit-tests/test-cases/eh-coalescing-r/Makefile b/unit-tests/test-cases/eh-coalescing-r/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing-r/bar.cxx b/unit-tests/test-cases/eh-coalescing-r/bar.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing-r/baz.cxx b/unit-tests/test-cases/eh-coalescing-r/baz.cxx new file mode 100644 index 0000000..3b2e31d --- /dev/null +++ b/unit-tests/test-cases/eh-coalescing-r/baz.cxx @@ -0,0 +1,32 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ +#include +#include "func.h" + +void baz() +{ + func(); +} + + diff --git a/unit-tests/test-cases/eh-coalescing-r/foo.cxx b/unit-tests/test-cases/eh-coalescing-r/foo.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing-r/func.h b/unit-tests/test-cases/eh-coalescing-r/func.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing/Makefile b/unit-tests/test-cases/eh-coalescing/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing/bar.cxx b/unit-tests/test-cases/eh-coalescing/bar.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing/foo.cxx b/unit-tests/test-cases/eh-coalescing/foo.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing/foo2.cxx b/unit-tests/test-cases/eh-coalescing/foo2.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-coalescing/func.h b/unit-tests/test-cases/eh-coalescing/func.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-strip-test/Makefile b/unit-tests/test-cases/eh-strip-test/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-strip-test/comment.txt b/unit-tests/test-cases/eh-strip-test/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-strip-test/main.cxx b/unit-tests/test-cases/eh-strip-test/main.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh-stripped-symbols/Makefile b/unit-tests/test-cases/eh-stripped-symbols/Makefile new file mode 100644 index 0000000..107400e --- /dev/null +++ b/unit-tests/test-cases/eh-stripped-symbols/Makefile @@ -0,0 +1,23 @@ + +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# verify that if symbols are stripped out of .o files +# the linker can still process unwind info from .o files +# correctly + +run: all + +all: + ${CXX} ${CCXXFLAGS} main.cxx -c -o main1.o -Os + #strip main1.o -u -s keep.exp -o main2.o + ${LD} main1.o -r -x -exported_symbols_list keep.exp -o main2.o + ${CXX} ${CCXXFLAGS} main1.o -Wl,-x -o main1 -exported_symbols_list keep.exp + ${CXX} ${CCXXFLAGS} main2.o -o main2 + unwinddump -arch ${ARCH} main1 > main1.unwind + unwinddump -arch ${ARCH} main2 > main2.unwind + ${PASS_IFF} diff main1.unwind main2.unwind + +clean: + rm -f main1* main2* diff --git a/unit-tests/test-cases/eh-stripped-symbols/keep.exp b/unit-tests/test-cases/eh-stripped-symbols/keep.exp new file mode 100644 index 0000000..70669ab --- /dev/null +++ b/unit-tests/test-cases/eh-stripped-symbols/keep.exp @@ -0,0 +1,3 @@ +_main +__Z3barv + diff --git a/unit-tests/test-cases/eh-stripped-symbols/main.cxx b/unit-tests/test-cases/eh-stripped-symbols/main.cxx new file mode 100644 index 0000000..325937d --- /dev/null +++ b/unit-tests/test-cases/eh-stripped-symbols/main.cxx @@ -0,0 +1,52 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2008 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ +#include +#include + +void bar() +{ +} + + +void foo2() +{ + int a = arc4random(); + int b = arc4random(); + fprintf(stderr, "hello %d %d\n", a, b); +} + +void foo1() +{ + foo2(); + fprintf(stderr, "world\n"); +} + + + +int main() +{ + foo1(); + bar(); + return 0; +} \ No newline at end of file diff --git a/unit-tests/test-cases/eh_frame/Makefile b/unit-tests/test-cases/eh_frame/Makefile old mode 100755 new mode 100644 index 6216d8e..f13626f --- a/unit-tests/test-cases/eh_frame/Makefile +++ b/unit-tests/test-cases/eh_frame/Makefile @@ -41,6 +41,7 @@ all: ${FAIL_IF_BAD_OBJ} foo2.o ${CXX} ${CCXXFLAGS} foo2.o bar.cxx -dynamiclib -o libfoobar.dylib ${FAIL_IF_BAD_MACHO} libfoobar.dylib + dwarfdump --eh-frame --verify libfoobar.dylib > /dev/null nm libfoobar.dylib | grep '.eh' | ${PASS_IFF_EMPTY} clean: diff --git a/unit-tests/test-cases/eh_frame/bar.cxx b/unit-tests/test-cases/eh_frame/bar.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/eh_frame/foo.cxx b/unit-tests/test-cases/eh_frame/foo.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/empty-object/Makefile b/unit-tests/test-cases/empty-object/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/empty-object/main.c b/unit-tests/test-cases/empty-object/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/end-label/Makefile b/unit-tests/test-cases/end-label/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/end-label/bar.s b/unit-tests/test-cases/end-label/bar.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/end-label/foo.s b/unit-tests/test-cases/end-label/foo.s old mode 100755 new mode 100644 index 888af5f..de19a05 --- a/unit-tests/test-cases/end-label/foo.s +++ b/unit-tests/test-cases/end-label/foo.s @@ -3,9 +3,11 @@ .globl _start .globl _end + .globl _endAlias _start: .long 0 .long 0 _end: +_endAlias: diff --git a/unit-tests/test-cases/exported-symbols-wildcards-dead_strip/Makefile b/unit-tests/test-cases/exported-symbols-wildcards-dead_strip/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards-dead_strip/foo.c b/unit-tests/test-cases/exported-symbols-wildcards-dead_strip/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/Makefile b/unit-tests/test-cases/exported-symbols-wildcards/Makefile old mode 100755 new mode 100644 index 10d1eb1..7b000e4 --- a/unit-tests/test-cases/exported-symbols-wildcards/Makefile +++ b/unit-tests/test-cases/exported-symbols-wildcards/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -31,47 +31,47 @@ run: all all: ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_foo*bar' - nm -j -g -f libfoo.dylib | diff - expect1 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect1 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f?o' - nm -j -g -f libfoo.dylib | diff - expect2 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect2 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_foo*' - nm -j -g -f libfoo.dylib | diff - expect3 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect3 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f*o*' - nm -j -g -f libfoo.dylib | diff - expect4 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect4 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,_foo -Wl,-exported_symbol -Wl,'_*bar' - nm -j -g -f libfoo.dylib | diff - expect5 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect5 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -exported_symbols_list list5 - nm -j -g -f libfoo.dylib | diff - expect5 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect5 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-unexported_symbol -Wl,'_*2*' - nm -j -g -f libfoo.dylib | diff - expect6 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect6 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f[abcdef]o' - nm -j -g -f libfoo.dylib | diff - expect7 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect7 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f[a-f]o' - nm -j -g -f libfoo.dylib | diff - expect7 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect7 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f[a-z]o' - nm -j -g -f libfoo.dylib | diff - expect8 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect8 | ${FAIL_IF_STDIN} ${FAIL_IF_BAD_MACHO} libfoo.dylib ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -Wl,-exported_symbol -Wl,'_f[a-fnop]o' - nm -j -g -f libfoo.dylib | diff - expect8 | ${FAIL_IF_STDIN} + nm -j -g -f -s __TEXT __text libfoo.dylib | diff - expect8 | ${FAIL_IF_STDIN} ${PASS_IFF_GOOD_MACHO} libfoo.dylib clean: diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect1 b/unit-tests/test-cases/exported-symbols-wildcards/expect1 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect2 b/unit-tests/test-cases/exported-symbols-wildcards/expect2 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect3 b/unit-tests/test-cases/exported-symbols-wildcards/expect3 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect4 b/unit-tests/test-cases/exported-symbols-wildcards/expect4 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect5 b/unit-tests/test-cases/exported-symbols-wildcards/expect5 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect6 b/unit-tests/test-cases/exported-symbols-wildcards/expect6 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect7 b/unit-tests/test-cases/exported-symbols-wildcards/expect7 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/expect8 b/unit-tests/test-cases/exported-symbols-wildcards/expect8 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/foo.c b/unit-tests/test-cases/exported-symbols-wildcards/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported-symbols-wildcards/list5 b/unit-tests/test-cases/exported-symbols-wildcards/list5 old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-eol/Makefile b/unit-tests/test-cases/exported_symbols_list-eol/Makefile old mode 100755 new mode 100644 index 25a50b4..6c9456e --- a/unit-tests/test-cases/exported_symbols_list-eol/Makefile +++ b/unit-tests/test-cases/exported_symbols_list-eol/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -33,7 +33,7 @@ run: all all: ${CC} ${CCFLAGS} test.c -dynamiclib -exported_symbols_list test.exp -o libtest.dylib - nm -jg libtest.dylib | grep _ > test.nm + nm -jg libtest.dylib | grep '^_' > test.nm diff test.nm expected.nm ${PASS_IFF_GOOD_MACHO} libtest.dylib diff --git a/unit-tests/test-cases/exported_symbols_list-eol/expected.nm b/unit-tests/test-cases/exported_symbols_list-eol/expected.nm old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-eol/test.c b/unit-tests/test-cases/exported_symbols_list-eol/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-eol/test.exp b/unit-tests/test-cases/exported_symbols_list-eol/test.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-hidden/Makefile b/unit-tests/test-cases/exported_symbols_list-hidden/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-hidden/test.c b/unit-tests/test-cases/exported_symbols_list-hidden/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-hidden/test.exp b/unit-tests/test-cases/exported_symbols_list-hidden/test.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-r/Makefile b/unit-tests/test-cases/exported_symbols_list-r/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-r/test-bad.exp b/unit-tests/test-cases/exported_symbols_list-r/test-bad.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-r/test.c b/unit-tests/test-cases/exported_symbols_list-r/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/exported_symbols_list-r/test.exp b/unit-tests/test-cases/exported_symbols_list-r/test.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/external-reloc-sorting/Makefile b/unit-tests/test-cases/external-reloc-sorting/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/external-reloc-sorting/foo.c b/unit-tests/test-cases/external-reloc-sorting/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/external-reloc-sorting/main.c b/unit-tests/test-cases/external-reloc-sorting/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/filelist/Makefile b/unit-tests/test-cases/filelist/Makefile old mode 100755 new mode 100644 index 0b1a743..95a0541 --- a/unit-tests/test-cases/filelist/Makefile +++ b/unit-tests/test-cases/filelist/Makefile @@ -27,21 +27,23 @@ include ${TESTROOT}/include/common.makefile PWD = $(shell pwd) # -# The point of this test is to check the two forms of the -# -filelist option +# Check the two forms of the -filelist option # run: all all: - ${CC} ${CCFLAGS} -c hello.c -o hello-${ARCH}.o - ${FAIL_IF_BAD_OBJ} hello-${ARCH}.o - echo "${PWD}/hello-${ARCH}.o" > "${PWD}/filelist1" - cd /tmp && ${CC} ${CCFLAGS} -filelist "${PWD}/filelist1" -o "${PWD}/hello-${ARCH}" - ${FAIL_IF_BAD_MACHO} hello-${ARCH} - echo "hello-${ARCH}.o" > "${PWD}/filelist2" - cd /tmp && ${CC} ${CCFLAGS} -filelist "${PWD}/filelist2,${PWD}" -o "${PWD}/hello-${ARCH}" - ${PASS_IFF_GOOD_MACHO} hello-${ARCH} + ${CC} ${CCFLAGS} -c hello.c -o hello.o + ${FAIL_IF_BAD_OBJ} hello.o + echo "${PWD}/hello.o" > "${PWD}/filelist1" + cd /tmp && ${CC} ${CCFLAGS} -filelist "${PWD}/filelist1" -o "${PWD}/hello" + ${FAIL_IF_BAD_MACHO} hello + echo "hello.o" > "${PWD}/filelist2" + cd /tmp && ${CC} ${CCFLAGS} -filelist "${PWD}/filelist2,${PWD}" -o "${PWD}/hello" + ${FAIL_IF_BAD_MACHO} hello + echo "${PWD}/hello.o" > "${PWD}/filelist,withComma" + cd /tmp && ${CC} ${CCFLAGS} -filelist "${PWD}/filelist,withComma" -o "${PWD}/hello" + ${PASS_IFF_GOOD_MACHO} hello clean: - rm hello-* *.o filelist1 filelist2 + rm -f hello.o hello filelist1 filelist2 filelist,withComma diff --git a/unit-tests/test-cases/filelist/comment.txt b/unit-tests/test-cases/filelist/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/filelist/hello.c b/unit-tests/test-cases/filelist/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-dylib/Makefile b/unit-tests/test-cases/flat-dylib/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-dylib/main.c b/unit-tests/test-cases/flat-dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-indirect-undefines/Makefile b/unit-tests/test-cases/flat-indirect-undefines/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-indirect-undefines/bar.c b/unit-tests/test-cases/flat-indirect-undefines/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-indirect-undefines/foo.c b/unit-tests/test-cases/flat-indirect-undefines/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-indirect-undefines/main.c b/unit-tests/test-cases/flat-indirect-undefines/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-main/Makefile b/unit-tests/test-cases/flat-main/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/flat-main/main.c b/unit-tests/test-cases/flat-main/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/got-elimination/Makefile b/unit-tests/test-cases/got-elimination/Makefile old mode 100755 new mode 100644 index 3f70e74..6fae5ee --- a/unit-tests/test-cases/got-elimination/Makefile +++ b/unit-tests/test-cases/got-elimination/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -42,7 +42,7 @@ all-true: all-x86_64: ${CC} ${CCFLAGS} foo.c bar.c -dynamiclib -o libfoobar.dylib - otool -Iv libfoobar.dylib | grep 0x | ${FAIL_IF_STDIN} + otool -Iv libfoobar.dylib | grep 0x | grep _ | ${FAIL_IF_STDIN} ${CC} ${CCFLAGS} foo.c bar.c -dynamiclib -o libfoobar.dylib -flat_namespace otool -Iv libfoobar.dylib | grep 0x | ${PASS_IFF_STDIN} diff --git a/unit-tests/test-cases/got-elimination/bar.c b/unit-tests/test-cases/got-elimination/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/got-elimination/foo.c b/unit-tests/test-cases/got-elimination/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/header-pad/Makefile b/unit-tests/test-cases/header-pad/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/header-pad/comment.txt b/unit-tests/test-cases/header-pad/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/header-pad/hello.c b/unit-tests/test-cases/header-pad/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/hello-world/Makefile b/unit-tests/test-cases/hello-world/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/hello-world/comment.txt b/unit-tests/test-cases/hello-world/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/hello-world/hello.c b/unit-tests/test-cases/hello-world/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common2/Makefile.newtest b/unit-tests/test-cases/implicit-common2/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common2/a.c b/unit-tests/test-cases/implicit-common2/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common2/comment.txt b/unit-tests/test-cases/implicit-common2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common2/test.c b/unit-tests/test-cases/implicit-common2/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common3/a.c b/unit-tests/test-cases/implicit-common3/a.c deleted file mode 100755 index 110842f..0000000 --- a/unit-tests/test-cases/implicit-common3/a.c +++ /dev/null @@ -1,8 +0,0 @@ -extern int common_var; -int *fn(); - -int -main(int argc, char **argv) -{ - return 0!=&common_var; -} diff --git a/unit-tests/test-cases/implicit-common3/comment.txt b/unit-tests/test-cases/implicit-common3/comment.txt deleted file mode 100755 index a1710c1..0000000 --- a/unit-tests/test-cases/implicit-common3/comment.txt +++ /dev/null @@ -1 +0,0 @@ -The point of this test is a sanity check that ld can link a program with a large zero-fill section diff --git a/unit-tests/test-cases/implicit-common4/Makefile.newtest b/unit-tests/test-cases/implicit-common4/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common4/a.c b/unit-tests/test-cases/implicit-common4/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common4/comment.txt b/unit-tests/test-cases/implicit-common4/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common4/test.c b/unit-tests/test-cases/implicit-common4/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common5/Makefile.newtest b/unit-tests/test-cases/implicit-common5/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common5/a.c b/unit-tests/test-cases/implicit-common5/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common5/comment.txt b/unit-tests/test-cases/implicit-common5/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit-common5/test.c b/unit-tests/test-cases/implicit-common5/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit_dylib/Makefile b/unit-tests/test-cases/implicit_dylib/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit_dylib/bar.c b/unit-tests/test-cases/implicit_dylib/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit_dylib/foo.c b/unit-tests/test-cases/implicit_dylib/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/implicit_dylib/main.c b/unit-tests/test-cases/implicit_dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-dylib/Makefile b/unit-tests/test-cases/indirect-dylib/Makefile old mode 100755 new mode 100644 index e3056a5..126d736 --- a/unit-tests/test-cases/indirect-dylib/Makefile +++ b/unit-tests/test-cases/indirect-dylib/Makefile @@ -43,4 +43,4 @@ all: grep ordinal fail.log | ${PASS_IFF_EMPTY} clean: - rm *.dylib main fail.log + rm -f *.dylib main fail.log diff --git a/unit-tests/test-cases/indirect-dylib/bar.c b/unit-tests/test-cases/indirect-dylib/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-dylib/comment.txt b/unit-tests/test-cases/indirect-dylib/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-dylib/foo.c b/unit-tests/test-cases/indirect-dylib/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-dylib/main.c b/unit-tests/test-cases/indirect-dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-path-search/Makefile b/unit-tests/test-cases/indirect-path-search/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-path-search/bar.c b/unit-tests/test-cases/indirect-path-search/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-path-search/baz.c b/unit-tests/test-cases/indirect-path-search/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-path-search/foo.c b/unit-tests/test-cases/indirect-path-search/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/indirect-path-search/main.c b/unit-tests/test-cases/indirect-path-search/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/init-order/Makefile b/unit-tests/test-cases/init-order/Makefile new file mode 100644 index 0000000..7e8c6e1 --- /dev/null +++ b/unit-tests/test-cases/init-order/Makefile @@ -0,0 +1,42 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that initializers are automatically sorted to start of __text +# and terminators are sorted to end of __text +# +# automatically order initializers to start of __TEXT +# + +run: all + +all: + ${CXX} ${CXXFLAGS} main.cxx foo.cxx bar.cxx -o main -dead_strip + nm -s __TEXT __text -nj main | grep -v dyld_stub_binding_helper | c++filt > actual-order.txt + ${PASS_IFF} diff actual-order.txt expected-order.txt + + +clean: + rm -rf main actual-order.txt diff --git a/unit-tests/test-cases/init-order/bar.cxx b/unit-tests/test-cases/init-order/bar.cxx new file mode 100644 index 0000000..43783a8 --- /dev/null +++ b/unit-tests/test-cases/init-order/bar.cxx @@ -0,0 +1,16 @@ + + + +class Bar { +public: + Bar() : a(20) {} + ~Bar() {} +private: + int a; +}; + + +Bar b1; +Bar b2; + + diff --git a/unit-tests/test-cases/init-order/expected-order.txt b/unit-tests/test-cases/init-order/expected-order.txt new file mode 100644 index 0000000..9a303d3 --- /dev/null +++ b/unit-tests/test-cases/init-order/expected-order.txt @@ -0,0 +1,20 @@ +M::M() +__static_initialization_and_destruction_0(int, int) +global constructors keyed to m1 +Foo::Foo() +__static_initialization_and_destruction_0(int, int) +global constructors keyed to f1 +Bar::Bar() +__static_initialization_and_destruction_0(int, int) +global constructors keyed to b1 +start +_main +M::~M() +Foo::~Foo() +Bar::~Bar() +___tcf_0 +___tcf_1 +___tcf_0 +___tcf_1 +___tcf_0 +___tcf_1 diff --git a/unit-tests/test-cases/init-order/foo.cxx b/unit-tests/test-cases/init-order/foo.cxx new file mode 100644 index 0000000..b593670 --- /dev/null +++ b/unit-tests/test-cases/init-order/foo.cxx @@ -0,0 +1,14 @@ + + + +class Foo { +public: + Foo() : a(20) {} + ~Foo() {} +private: + int a; +}; + + +Foo f1; +Foo f2; diff --git a/unit-tests/test-cases/init-order/main.cxx b/unit-tests/test-cases/init-order/main.cxx new file mode 100644 index 0000000..3e92107 --- /dev/null +++ b/unit-tests/test-cases/init-order/main.cxx @@ -0,0 +1,18 @@ +#include + +class M { +public: + M() : a(20) {} + ~M() {} +private: + int a; +}; + + +M m1; +M m2; + +int main() +{ + return 0; +} diff --git a/unit-tests/test-cases/interposable_list/Makefile b/unit-tests/test-cases/interposable_list/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/interposable_list/test.c b/unit-tests/test-cases/interposable_list/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/interposable_list/test.exp b/unit-tests/test-cases/interposable_list/test.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/kext-basic/Makefile b/unit-tests/test-cases/kext-basic/Makefile new file mode 100644 index 0000000..d233171 --- /dev/null +++ b/unit-tests/test-cases/kext-basic/Makefile @@ -0,0 +1,29 @@ + +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Sanity check that ld can link a kext +# + +ifeq (${ARCH},x86_64) + FILE_TYPE = KEXTBUNDLE +else + FILE_TYPE = OBJECT +endif + + +run: all + +all: + ${CC} ${CCFLAGS} -static -fno-common -mkernel -c mykext.c -o mykext.o + ${CC} ${CCFLAGS} -static -fno-common -mkernel -c mykextinfo.c -o mykextinfo.o + ${CC} ${CCFLAGS} -Wl,-kext mykext.o mykextinfo.o -nostdlib -lkmodc++ -lkmod -lcc_kext -o mykext + otool -hv mykext | grep ${FILE_TYPE} | ${FAIL_IF_EMPTY} + nm -nm mykext | grep '(undefined) external _extern_global' | ${FAIL_IF_EMPTY} + nm -nm mykext | grep '(__DATA,__data) external _my_global' | ${FAIL_IF_EMPTY} + otool -rv mykext | grep '_extern_global' | ${FAIL_IF_EMPTY} + ${PASS_IFF} true + +clean: + rm -f mykext.o mykextinfo.o mykext diff --git a/unit-tests/test-cases/kext-basic/mykext.c b/unit-tests/test-cases/kext-basic/mykext.c new file mode 100644 index 0000000..51de101 --- /dev/null +++ b/unit-tests/test-cases/kext-basic/mykext.c @@ -0,0 +1,18 @@ +#include + + +int my_global = 3; +extern int extern_global; + +kern_return_t mykext_start (kmod_info_t * ki, void * d) { + ++my_global; + ++extern_global; + return KERN_SUCCESS; +} + + +kern_return_t mykext_stop (kmod_info_t * ki, void * d) { + --my_global; + --extern_global; + return KERN_SUCCESS; +} diff --git a/unit-tests/test-cases/kext-basic/mykextinfo.c b/unit-tests/test-cases/kext-basic/mykextinfo.c new file mode 100644 index 0000000..fe31e7b --- /dev/null +++ b/unit-tests/test-cases/kext-basic/mykextinfo.c @@ -0,0 +1,12 @@ +#include + +extern kern_return_t _start(kmod_info_t *ki, void *data); +extern kern_return_t _stop(kmod_info_t *ki, void *data); +__private_extern__ kern_return_t mykext_start(kmod_info_t *ki, void *data); +__private_extern__ kern_return_t mykext_stop(kmod_info_t *ki, void *data); + +KMOD_EXPLICIT_DECL(com.yourcompany.kext.mykext, "1.0.0d1", _start, _stop) +__private_extern__ kmod_start_func_t *_realmain = mykext_start; +__private_extern__ kmod_stop_func_t *_antimain = mykext_stop; +__private_extern__ int _kext_apple_cc = __APPLE_CC__ ; + diff --git a/unit-tests/test-cases/large-data/Makefile b/unit-tests/test-cases/large-data/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/large-data/test1.c b/unit-tests/test-cases/large-data/test1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/large-data/test2.c b/unit-tests/test-cases/large-data/test2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/large-data/test3.c b/unit-tests/test-cases/large-data/test3.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/large-data/test4.c b/unit-tests/test-cases/large-data/test4.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/late-link-error/Makefile b/unit-tests/test-cases/late-link-error/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/late-link-error/comment.txt b/unit-tests/test-cases/late-link-error/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/late-link-error/link_error.s b/unit-tests/test-cases/late-link-error/link_error.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib-objc/Makefile b/unit-tests/test-cases/lazy-dylib-objc/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib-objc/foo.h b/unit-tests/test-cases/lazy-dylib-objc/foo.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib-objc/foo.m b/unit-tests/test-cases/lazy-dylib-objc/foo.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib-objc/main.m b/unit-tests/test-cases/lazy-dylib-objc/main.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib/Makefile b/unit-tests/test-cases/lazy-dylib/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib/bad.c b/unit-tests/test-cases/lazy-dylib/bad.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib/bad2.c b/unit-tests/test-cases/lazy-dylib/bad2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib/foo.c b/unit-tests/test-cases/lazy-dylib/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lazy-dylib/main.c b/unit-tests/test-cases/lazy-dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment/Makefile b/unit-tests/test-cases/literals-coalesce-alignment/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment/cstring-align-0.s b/unit-tests/test-cases/literals-coalesce-alignment/cstring-align-0.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment/cstring-align-3.s b/unit-tests/test-cases/literals-coalesce-alignment/cstring-align-3.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment2/Makefile b/unit-tests/test-cases/literals-coalesce-alignment2/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment2/comment.txt b/unit-tests/test-cases/literals-coalesce-alignment2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-0.s b/unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-0.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-3.s b/unit-tests/test-cases/literals-coalesce-alignment2/cstring-align-3.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment3/Makefile b/unit-tests/test-cases/literals-coalesce-alignment3/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment3/comment.txt b/unit-tests/test-cases/literals-coalesce-alignment3/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-0.s b/unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-0.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-3.s b/unit-tests/test-cases/literals-coalesce-alignment3/cstring-align-3.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce/Makefile b/unit-tests/test-cases/literals-coalesce/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce/literals.s b/unit-tests/test-cases/literals-coalesce/literals.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce2/Makefile.newtest b/unit-tests/test-cases/literals-coalesce2/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce2/comment.txt b/unit-tests/test-cases/literals-coalesce2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/literals-coalesce2/literals.s b/unit-tests/test-cases/literals-coalesce2/literals.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/Makefile b/unit-tests/test-cases/llvm-integration/Makefile old mode 100755 new mode 100644 index 42c71e4..30376df --- a/unit-tests/test-cases/llvm-integration/Makefile +++ b/unit-tests/test-cases/llvm-integration/Makefile @@ -43,8 +43,7 @@ run: all: zero one two three four five six seven eight nine ten \ eleven twelve thirteen fourteen fifteen sixteen seventeen \ - eighteen nineteen twenty - + eighteen nineteen zero: # @@ -117,7 +116,7 @@ five: # llvm : b5.c : Dfoo2 # MachO : main5.c : Dfoo3, Ufoo1 # - #echo "Five..." + #echo "verify that if call to mach-o is optimized away, mach-o func is dead stripped" ${LLVMGCC} ${CCFLAGS} --emit-llvm a5.c -c -o a5.o ${LLVMGCC} ${CCFLAGS} --emit-llvm b5.c -c -o b5.o ${LLVMGCC} ${CCFLAGS} main5.c -c -o main5.o @@ -204,7 +203,7 @@ twelve: # llvm : a12.c # MachO : main12.c # - #echo "Tweleve..." + #echo "verify tentative def in llvm .o referenced from mach-o" ${LLVMGCC} ${CCFLAGS} --emit-llvm a12.c -c -o a12.o ${LLVMGCC} ${CCFLAGS} main12.c -c -o main12.o ${LLVMGCC} ${CCFLAGS} a12.o main12.o -o main12.exe @@ -275,15 +274,16 @@ nineteen: twenty: #echo verify bitcode files in archives works - ${LLVMGCC} ${CCFLAGS} --emit-llvm a20.c -c -o a20.o - ${LLVMGCC} ${CCFLAGS} --emit-llvm b20.c -c -o b20.o - ar cru lib20.a a20.o b20.o - ${LLVMGCC} ${CCFLAGS} main20.c lib20.a -all_load -o main20.exe - nm main20.exe | grep _foo | ${PASS_IFF_STDIN} - + #${LLVMGCC} ${CCFLAGS} --emit-llvm a20.c -c -o a20.o + #${LLVMGCC} ${CCFLAGS} --emit-llvm b20.c -c -o b20.o + #libtool -static a20.o b20.o -o lib20.a + #${LLVMGCC} ${CCFLAGS} main20.c lib20.a -all_load -o main20.exe + #nm main20.exe | grep _foo | ${PASS_IFF_STDIN} + + clean: - rm -rf *.o main*.exe big.* *.dylib main16.exe.lto.bc fail.log lib20.a + rm -rf *.o main*.exe big.* *.dylib main16.exe.lto.bc fail.log lib20.a main21.preload lib21.a diff --git a/unit-tests/test-cases/llvm-integration/a.c b/unit-tests/test-cases/llvm-integration/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a1.c b/unit-tests/test-cases/llvm-integration/a1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a10.c b/unit-tests/test-cases/llvm-integration/a10.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a11.c b/unit-tests/test-cases/llvm-integration/a11.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a12.c b/unit-tests/test-cases/llvm-integration/a12.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a12.h b/unit-tests/test-cases/llvm-integration/a12.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a13.cc b/unit-tests/test-cases/llvm-integration/a13.cc old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a13.h b/unit-tests/test-cases/llvm-integration/a13.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a14.c b/unit-tests/test-cases/llvm-integration/a14.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a15.c b/unit-tests/test-cases/llvm-integration/a15.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a17.c b/unit-tests/test-cases/llvm-integration/a17.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a18.c b/unit-tests/test-cases/llvm-integration/a18.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a2.c b/unit-tests/test-cases/llvm-integration/a2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a20.c b/unit-tests/test-cases/llvm-integration/a20.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a3.c b/unit-tests/test-cases/llvm-integration/a3.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a4.c b/unit-tests/test-cases/llvm-integration/a4.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a5.c b/unit-tests/test-cases/llvm-integration/a5.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a6.c b/unit-tests/test-cases/llvm-integration/a6.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a7.c b/unit-tests/test-cases/llvm-integration/a7.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a8.c b/unit-tests/test-cases/llvm-integration/a8.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a9.c b/unit-tests/test-cases/llvm-integration/a9.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/a9.list b/unit-tests/test-cases/llvm-integration/a9.list old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b.c b/unit-tests/test-cases/llvm-integration/b.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b1.c b/unit-tests/test-cases/llvm-integration/b1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b10.c b/unit-tests/test-cases/llvm-integration/b10.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b10.h b/unit-tests/test-cases/llvm-integration/b10.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b14.c b/unit-tests/test-cases/llvm-integration/b14.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b15.c b/unit-tests/test-cases/llvm-integration/b15.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b17.c b/unit-tests/test-cases/llvm-integration/b17.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b2.c b/unit-tests/test-cases/llvm-integration/b2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b20.c b/unit-tests/test-cases/llvm-integration/b20.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b3.c b/unit-tests/test-cases/llvm-integration/b3.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b4.c b/unit-tests/test-cases/llvm-integration/b4.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b5.c b/unit-tests/test-cases/llvm-integration/b5.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/b7.c b/unit-tests/test-cases/llvm-integration/b7.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/c15.c b/unit-tests/test-cases/llvm-integration/c15.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main.c b/unit-tests/test-cases/llvm-integration/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main1.c b/unit-tests/test-cases/llvm-integration/main1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main10.c b/unit-tests/test-cases/llvm-integration/main10.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main11.c b/unit-tests/test-cases/llvm-integration/main11.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main12.c b/unit-tests/test-cases/llvm-integration/main12.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main13.cc b/unit-tests/test-cases/llvm-integration/main13.cc old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main16.c b/unit-tests/test-cases/llvm-integration/main16.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main19.c b/unit-tests/test-cases/llvm-integration/main19.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main2.c b/unit-tests/test-cases/llvm-integration/main2.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main20.c b/unit-tests/test-cases/llvm-integration/main20.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main3.c b/unit-tests/test-cases/llvm-integration/main3.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main4.c b/unit-tests/test-cases/llvm-integration/main4.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main5.c b/unit-tests/test-cases/llvm-integration/main5.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main6.c b/unit-tests/test-cases/llvm-integration/main6.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main7.c b/unit-tests/test-cases/llvm-integration/main7.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main8.c b/unit-tests/test-cases/llvm-integration/main8.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/llvm-integration/main9.c b/unit-tests/test-cases/llvm-integration/main9.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/loader_path/Makefile b/unit-tests/test-cases/loader_path/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/loader_path/bar.c b/unit-tests/test-cases/loader_path/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/loader_path/foo.c b/unit-tests/test-cases/loader_path/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/loader_path/main.c b/unit-tests/test-cases/loader_path/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/Makefile b/unit-tests/test-cases/local-symbol-partial-stripping/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/a.expect b/unit-tests/test-cases/local-symbol-partial-stripping/a.expect old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/a.list b/unit-tests/test-cases/local-symbol-partial-stripping/a.list old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/b.expect b/unit-tests/test-cases/local-symbol-partial-stripping/b.expect old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/b.list b/unit-tests/test-cases/local-symbol-partial-stripping/b.list old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/c.list b/unit-tests/test-cases/local-symbol-partial-stripping/c.list old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/foo.c b/unit-tests/test-cases/local-symbol-partial-stripping/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/local-symbol-partial-stripping/main.c b/unit-tests/test-cases/local-symbol-partial-stripping/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/lto-archive-dylib/Makefile b/unit-tests/test-cases/lto-archive-dylib/Makefile new file mode 100644 index 0000000..e538ee1 --- /dev/null +++ b/unit-tests/test-cases/lto-archive-dylib/Makefile @@ -0,0 +1,46 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# LTO : 176.gcc and 177.mesa build failure at -O4 +# +# Check that LTO can bring in an archive member and that member needs a +# symbol from a dylib. +# + +LLVMGCC = /Developer/usr/bin/llvm-gcc-4.2 -arch ${ARCH} +LLVMGXX = /Developer/usr/bin/llvm-g++-4.2 -arch ${ARCH} + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + libtool -static foo.o -o libfoo.a + ${LLVMGCC} ${CCFLAGS} --emit-llvm main.c -c -o main.o + ${LLVMGCC} ${CCFLAGS} main.o -o main libfoo.a + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm -rf main foo.o libfoo.a main.o diff --git a/unit-tests/test-cases/lto-archive-dylib/foo.c b/unit-tests/test-cases/lto-archive-dylib/foo.c new file mode 100644 index 0000000..1592c76 --- /dev/null +++ b/unit-tests/test-cases/lto-archive-dylib/foo.c @@ -0,0 +1,5 @@ +#include +void foo() +{ + fprintf(stderr, "hello\n"); +} diff --git a/unit-tests/test-cases/lto-archive-dylib/main.c b/unit-tests/test-cases/lto-archive-dylib/main.c new file mode 100644 index 0000000..ae2f956 --- /dev/null +++ b/unit-tests/test-cases/lto-archive-dylib/main.c @@ -0,0 +1,8 @@ +extern void foo(); + +int main() +{ + foo(); + return 0; +} + diff --git a/unit-tests/test-cases/lto-llvm-options/Makefile b/unit-tests/test-cases/lto-llvm-options/Makefile new file mode 100644 index 0000000..5d4e991 --- /dev/null +++ b/unit-tests/test-cases/lto-llvm-options/Makefile @@ -0,0 +1,45 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that -mllvm optiions work. Verify --disable-inlining +# results in foo() not being inlined +# + +LLVMGCC = /Developer/usr/bin/llvm-gcc-4.2 -arch ${ARCH} +LLVMGXX = /Developer/usr/bin/llvm-g++-4.2 -arch ${ARCH} + +run: all + +all: + ${LLVMGCC} ${CCFLAGS} --emit-llvm main.c -c -o main.o + ${LLVMGCC} ${CCFLAGS} main.o -o main + nm main | grep _foo | ${FAIL_IF_STDIN} + ${LLVMGCC} ${CCFLAGS} main.o -o main2 -Wl,-mllvm -Wl,--disable-inlining + nm main2 | grep _foo | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm main main.o main2 diff --git a/unit-tests/test-cases/lto-llvm-options/main.c b/unit-tests/test-cases/lto-llvm-options/main.c new file mode 100644 index 0000000..578d24b --- /dev/null +++ b/unit-tests/test-cases/lto-llvm-options/main.c @@ -0,0 +1,15 @@ + +#include + + +void foo(int x) +{ + printf("hello, world %d\n", x); +} + +int main() +{ + foo(10); + return 0; +} + diff --git a/unit-tests/test-cases/lto-preload-pie/Makefile b/unit-tests/test-cases/lto-preload-pie/Makefile new file mode 100644 index 0000000..063bc33 --- /dev/null +++ b/unit-tests/test-cases/lto-preload-pie/Makefile @@ -0,0 +1,47 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# verify -preload -pie produces relocations +# + +LLVMGCC = /Developer/usr/bin/llvm-gcc-4.2 -arch ${ARCH} +LLVMGXX = /Developer/usr/bin/llvm-g++-4.2 -arch ${ARCH} + +run: all + +all: + ${LLVMGCC} ${CCFLAGS} --emit-llvm a.c -c -o a.o + ${LLVMGCC} ${CCFLAGS} --emit-llvm b.c -c -o b.o + ${LLVMGCC} ${CCFLAGS} --emit-llvm main.c -c -o main.o + ${LLVMGCC} ${CCFLAGS} main.o a.o b.o -Wl,-preload -Wl,-pie -o main.preload \ + -e _entry -nostdlib -Wl,-segalign,0x20 -Wl,-seg1addr,0x200 + otool -rv main.preload | grep "Local relocation information" | ${PASS_IFF_STDIN} + + + + +clean: + rm a.o b.o main.o main.preload diff --git a/unit-tests/test-cases/lto-preload-pie/a.c b/unit-tests/test-cases/lto-preload-pie/a.c new file mode 100644 index 0000000..c17b3e3 --- /dev/null +++ b/unit-tests/test-cases/lto-preload-pie/a.c @@ -0,0 +1,4 @@ + +extern const char* mystring; + +const char** myp = &mystring; diff --git a/unit-tests/test-cases/lto-preload-pie/b.c b/unit-tests/test-cases/lto-preload-pie/b.c new file mode 100644 index 0000000..b7ad5e1 --- /dev/null +++ b/unit-tests/test-cases/lto-preload-pie/b.c @@ -0,0 +1 @@ + const char* mystring = "hello"; diff --git a/unit-tests/test-cases/lto-preload-pie/main.c b/unit-tests/test-cases/lto-preload-pie/main.c new file mode 100644 index 0000000..8c9c61e --- /dev/null +++ b/unit-tests/test-cases/lto-preload-pie/main.c @@ -0,0 +1,11 @@ + +extern const char** myp; + + +const char** entry(int i) { + if ( i ) { + *myp = "help"; + } + return myp; +} + diff --git a/unit-tests/test-cases/lto-weak-native-override/Makefile b/unit-tests/test-cases/lto-weak-native-override/Makefile new file mode 100644 index 0000000..55ac0f1 --- /dev/null +++ b/unit-tests/test-cases/lto-weak-native-override/Makefile @@ -0,0 +1,45 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that LTO works when a llvm bitcode has a weak symbol _foo +# and mach-o has a strong _foo. +# + +LLVMGCC = /Developer/usr/bin/llvm-gcc-4.2 -arch ${ARCH} +LLVMGXX = /Developer/usr/bin/llvm-g++-4.2 -arch ${ARCH} + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + ${LLVMGCC} ${CCFLAGS} --emit-llvm main.c -c -o main.o + ${LLVMGCC} ${CCFLAGS} main.o foo.o -o main + otool -Iv main | grep _abort | ${FAIL_IF_STDIN} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm main foo.o main.o + \ No newline at end of file diff --git a/unit-tests/test-cases/lto-weak-native-override/foo.c b/unit-tests/test-cases/lto-weak-native-override/foo.c new file mode 100644 index 0000000..f65d830 --- /dev/null +++ b/unit-tests/test-cases/lto-weak-native-override/foo.c @@ -0,0 +1,6 @@ + + +void foo() +{ + // do nothing +} diff --git a/unit-tests/test-cases/lto-weak-native-override/main.c b/unit-tests/test-cases/lto-weak-native-override/main.c new file mode 100644 index 0000000..6a433db --- /dev/null +++ b/unit-tests/test-cases/lto-weak-native-override/main.c @@ -0,0 +1,17 @@ + +#include + +static void die() { abort(); } + + +__attribute__((visibility("hidden"),weak)) void foo() +{ + die(); +} + +int main() +{ + foo(); + +} + diff --git a/unit-tests/test-cases/main-stripped/Makefile b/unit-tests/test-cases/main-stripped/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/main-stripped/main.c b/unit-tests/test-cases/main-stripped/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/main-stripped/main.exp b/unit-tests/test-cases/main-stripped/main.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/missing-option-args/Makefile b/unit-tests/test-cases/missing-option-args/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/missing-option-args/comment.txt b/unit-tests/test-cases/missing-option-args/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/multiple-entry-points/Makefile b/unit-tests/test-cases/multiple-entry-points/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/multiple-entry-points/comment.txt b/unit-tests/test-cases/multiple-entry-points/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/multiple-entry-points/test.s b/unit-tests/test-cases/multiple-entry-points/test.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-data-bundle/Makefile b/unit-tests/test-cases/no-data-bundle/Makefile new file mode 100644 index 0000000..e1417fd --- /dev/null +++ b/unit-tests/test-cases/no-data-bundle/Makefile @@ -0,0 +1,38 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Check that a bundle built with no data links +# gcc DejaGnu failure: building longcall/dylib library +# + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -bundle -o foo.bundle + ${PASS_IFF_GOOD_MACHO} foo.bundle + +clean: + rm foo.bundle diff --git a/unit-tests/test-cases/no-data-bundle/foo.c b/unit-tests/test-cases/no-data-bundle/foo.c new file mode 100644 index 0000000..5cb3e31 --- /dev/null +++ b/unit-tests/test-cases/no-data-bundle/foo.c @@ -0,0 +1,6 @@ +#include + +void foo() +{ + rand(); +} \ No newline at end of file diff --git a/unit-tests/test-cases/no-dynamic-common/Makefile.newtest b/unit-tests/test-cases/no-dynamic-common/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-dynamic-common/a.c b/unit-tests/test-cases/no-dynamic-common/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-dynamic-common/comment.txt b/unit-tests/test-cases/no-dynamic-common/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-dynamic-common/test.c b/unit-tests/test-cases/no-dynamic-common/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-object-symbols/Makefile b/unit-tests/test-cases/no-object-symbols/Makefile new file mode 100644 index 0000000..b213511 --- /dev/null +++ b/unit-tests/test-cases/no-object-symbols/Makefile @@ -0,0 +1,46 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that when ld creates an object file with no symbols +# and no section content, that the segment size is zero +# and the LC_SYMTAB is empty. +# +# LC_SEGMENT_64 filesize incorrect for MH_OBJECT filetype +# + +run: all + +all: + as -arch ${ARCH} -n empty.s -o empty.o + ${LD} -r empty.o -x -o empty2.o + otool -lv empty2.o | egrep 'vmsize 0x0[0]+$$' | ${FAIL_IF_EMPTY} + otool -lv empty2.o | grep 'filesize 0' | ${FAIL_IF_EMPTY} + otool -lv empty2.o | grep 'nsyms 0' | ${FAIL_IF_EMPTY} + otool -lv empty2.o | grep 'symoff 0' | ${FAIL_IF_EMPTY} + ${PASS_IFF} true + +clean: + rm empty.o empty2.o diff --git a/unit-tests/test-cases/no-object-symbols/empty.s b/unit-tests/test-cases/no-object-symbols/empty.s new file mode 100644 index 0000000..83fd519 --- /dev/null +++ b/unit-tests/test-cases/no-object-symbols/empty.s @@ -0,0 +1,2 @@ + + .text diff --git a/unit-tests/test-cases/no-uuid/Makefile b/unit-tests/test-cases/no-uuid/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-uuid/bar.c b/unit-tests/test-cases/no-uuid/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-uuid/comment.txt b/unit-tests/test-cases/no-uuid/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/no-uuid/foo.c b/unit-tests/test-cases/no-uuid/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/non-lazy-r/Makefile b/unit-tests/test-cases/non-lazy-r/Makefile old mode 100755 new mode 100644 index 3c14103..d581048 --- a/unit-tests/test-cases/non-lazy-r/Makefile +++ b/unit-tests/test-cases/non-lazy-r/Makefile @@ -49,12 +49,14 @@ hasnl: ${CC} ${CCFLAGS} -c other.c -o other.o ${LD} -r -arch ${ARCH} foo.o other.o -o fooall.o -exported_symbol _foo # make sure there are two indirect symbols: _foo and LOCAL - otool -Iv fooall.o | grep "2 entries" | ${FAIL_IF_EMPTY} - otool -Iv fooall.o | grep _foo | ${FAIL_IF_EMPTY} + otool -Iv fooall.o | grep "3 entries" | ${FAIL_IF_EMPTY} + otool -Iv fooall.o | grep _foo | ${FAIL_IF_EMPTY} + otool -Iv fooall.o | grep _tent | ${FAIL_IF_EMPTY} otool -Iv fooall.o | grep _other | ${FAIL_IF_STDIN} # make sure re-parsed correctly ${OBJECTDUMP} fooall.o | grep name: | grep '_foo$$non_lazy_ptr' | ${FAIL_IF_EMPTY} ${OBJECTDUMP} fooall.o | grep name: | grep '_other$$non_lazy_ptr' | ${FAIL_IF_EMPTY} + ${OBJECTDUMP} fooall.o | grep name: | grep '_tent$$non_lazy_ptr' | ${FAIL_IF_EMPTY} ${PASS_IFF} true clean: diff --git a/unit-tests/test-cases/non-lazy-r/foo.c b/unit-tests/test-cases/non-lazy-r/foo.c old mode 100755 new mode 100644 index 1fa325e..9d21475 --- a/unit-tests/test-cases/non-lazy-r/foo.c +++ b/unit-tests/test-cases/non-lazy-r/foo.c @@ -10,3 +10,8 @@ extern int other; int getother() { return other; } + +extern int tent; + +int gettent() { return tent; } + diff --git a/unit-tests/test-cases/non-lazy-r/other.c b/unit-tests/test-cases/non-lazy-r/other.c old mode 100755 new mode 100644 index 6420437..68eb01d --- a/unit-tests/test-cases/non-lazy-r/other.c +++ b/unit-tests/test-cases/non-lazy-r/other.c @@ -1,2 +1,3 @@ int foo = 2; int other = 3; +int tent; diff --git a/unit-tests/test-cases/objc-category-debug-notes/Makefile b/unit-tests/test-cases/objc-category-debug-notes/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-category-debug-notes/test.m b/unit-tests/test-cases/objc-category-debug-notes/test.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-exported_symbols_list/Makefile b/unit-tests/test-cases/objc-exported_symbols_list/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-exported_symbols_list/foo.exp b/unit-tests/test-cases/objc-exported_symbols_list/foo.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-exported_symbols_list/foo.m b/unit-tests/test-cases/objc-exported_symbols_list/foo.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-gc-checks/Makefile b/unit-tests/test-cases/objc-gc-checks/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-gc-checks/bar.m b/unit-tests/test-cases/objc-gc-checks/bar.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-gc-checks/comment.txt b/unit-tests/test-cases/objc-gc-checks/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-gc-checks/foo.m b/unit-tests/test-cases/objc-gc-checks/foo.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-gc-checks/runtime.c b/unit-tests/test-cases/objc-gc-checks/runtime.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-literal-pointers-strip/Makefile b/unit-tests/test-cases/objc-literal-pointers-strip/Makefile new file mode 100644 index 0000000..76a7347 --- /dev/null +++ b/unit-tests/test-cases/objc-literal-pointers-strip/Makefile @@ -0,0 +1,57 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + +# +# Verify an Objective-C object file when run through +# ld -r -x +# x86_64 obj-c runtime confused when static lib is stripped +# +# + +SELECTOR_REFS = "__OBJC,__message_refs" + +ifeq ($(ARCH),x86_64) + SELECTOR_REFS = "__DATA,__objc_selrefs" +endif +ifeq ($(ARCH),armv6) + SELECTOR_REFS = "__DATA,__objc_selrefs" +endif + + + +run: all + +all: + ${CC} ${CCFLAGS} test.m -c -o test.o + ${OBJECTDUMP} -no_content test.o | grep -B3 -A6 ${SELECTOR_REFS} > test.dump + + ${LD} -arch ${ARCH} -r test.o -x -o test-r.o + ${OBJECTDUMP} -no_content test-r.o | grep -B3 -A6 ${SELECTOR_REFS} > test-r.dump + + diff test.dump test-r.dump | ${PASS_IFF_EMPTY} + +clean: + rm -rf test.o test.dump test-r.o test-r.dump diff --git a/unit-tests/test-cases/objc-literal-pointers-strip/test.m b/unit-tests/test-cases/objc-literal-pointers-strip/test.m new file mode 100644 index 0000000..4837911 --- /dev/null +++ b/unit-tests/test-cases/objc-literal-pointers-strip/test.m @@ -0,0 +1,46 @@ +/* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- + * + * Copyright (c) 2009 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ + + +#include +#include + +@interface Foo @end +@implementation Foo ++(void)initialize { } ++(void)foo { + fprintf(stderr, "GOOD\n"); + exit(0); +} ++(void)bar { + fprintf(stderr, "BAD\n"); + abort(); +} +@end + +void PublicFunction(void) +{ + [Foo foo]; + [Foo bar]; +} diff --git a/unit-tests/test-cases/objc-literal-pointers/Makefile b/unit-tests/test-cases/objc-literal-pointers/Makefile old mode 100755 new mode 100644 index 9edc357..c0b9081 --- a/unit-tests/test-cases/objc-literal-pointers/Makefile +++ b/unit-tests/test-cases/objc-literal-pointers/Makefile @@ -36,10 +36,10 @@ run: all all: ${CC} ${CCFLAGS} test.m -c -o test.o - ObjectDump -no_content test.o | grep -v zero-fill-at> test.dump + ${OBJECTDUMP} -no_content test.o | grep -v zero-fill-at> test.dump - ${LD} -arch ${ARCH} -r test.o -o test-r.o - ObjectDump -no_content test-r.o | grep -v zero-fill-at > test-r.dump + ${LD} -arch ${ARCH} -r test.o -keep_private_externs -o test-r.o + ${OBJECTDUMP} -no_content test-r.o | grep -v zero-fill-at > test-r.dump diff test.dump test-r.dump | ${PASS_IFF_EMPTY} diff --git a/unit-tests/test-cases/objc-literal-pointers/test.m b/unit-tests/test-cases/objc-literal-pointers/test.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-references/Makefile b/unit-tests/test-cases/objc-references/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-references/comment.txt b/unit-tests/test-cases/objc-references/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-references/test.m b/unit-tests/test-cases/objc-references/test.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-selector-coalescing/Makefile b/unit-tests/test-cases/objc-selector-coalescing/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-selector-coalescing/main.m b/unit-tests/test-cases/objc-selector-coalescing/main.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/objc-selector-coalescing/other.m b/unit-tests/test-cases/objc-selector-coalescing/other.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/operator-new/Makefile b/unit-tests/test-cases/operator-new/Makefile old mode 100755 new mode 100644 index 8abf3e1..447ee87 --- a/unit-tests/test-cases/operator-new/Makefile +++ b/unit-tests/test-cases/operator-new/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2006-2007 Apple Inc. All rights reserved. +# Copyright (c) 2006-2009 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -30,6 +30,9 @@ all: # verify if operator new is overridden that WEAK_DEFINES is set ${CXX} ${CXXFLAGS} -DOP_NEW -I${TESTROOT}/include -o main main.cxx otool -hv main | grep WEAK_DEFINES | ${FAIL_IF_EMPTY} + # verify if operator new is overridden but not exported, WEAK_DEFINES is not set + ${CXX} ${CXXFLAGS} -DOP_NEW -I${TESTROOT}/include -o main main.cxx -Wl,-exported_symbol,_main + otool -hv main | grep WEAK_DEFINES | ${FAIL_IF_STDIN} # verify if operator new is not overridden that WEAK_DEFINES is not set ${CXX} ${CXXFLAGS} -I${TESTROOT}/include -o main main.cxx otool -hv main | grep WEAK_DEFINES | ${PASS_IFF_EMPTY} diff --git a/unit-tests/test-cases/operator-new/main.cxx b/unit-tests/test-cases/operator-new/main.cxx old mode 100755 new mode 100644 index 3c99e35..b5d3272 --- a/unit-tests/test-cases/operator-new/main.cxx +++ b/unit-tests/test-cases/operator-new/main.cxx @@ -36,7 +36,7 @@ #if OP_NEW void* operator new(size_t s) throw (std::bad_alloc) { - return malloc(s);; + return malloc(s); } #endif diff --git a/unit-tests/test-cases/order_file-ans/Makefile b/unit-tests/test-cases/order_file-ans/Makefile old mode 100755 new mode 100644 index 23fe568..a2e0b1d --- a/unit-tests/test-cases/order_file-ans/Makefile +++ b/unit-tests/test-cases/order_file-ans/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -30,9 +30,9 @@ include ${TESTROOT}/include/common.makefile run: all all: - ${CXX} ${CXXFLAGS} main.cxx -DANCHOR=1 -o main -Wl,-order_file -Wl,main.order + ${CXX} ${CXXFLAGS} main.cxx -o main -Wl,-order_file -Wl,main.order ${FAIL_IF_BAD_MACHO} main - nm -n -g -j main | grep "_GLOBAL__N" > main.actual + nm -n -j main | grep "_GLOBAL__N" > main.actual ${PASS_IFF} diff main.actual main.expected diff --git a/unit-tests/test-cases/order_file-ans/main.cxx b/unit-tests/test-cases/order_file-ans/main.cxx old mode 100755 new mode 100644 index b0412f9..b3c1edd --- a/unit-tests/test-cases/order_file-ans/main.cxx +++ b/unit-tests/test-cases/order_file-ans/main.cxx @@ -1,6 +1,6 @@ /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*- * - * Copyright (c) 2007 Apple Inc. All rights reserved. + * Copyright (c) 2007-2008 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * @@ -24,9 +24,6 @@ #include -#if ANCHOR - int anchor = 4; -#endif namespace { struct myanonstruct { int a; }; diff --git a/unit-tests/test-cases/order_file-ans/main.expected b/unit-tests/test-cases/order_file-ans/main.expected old mode 100755 new mode 100644 index 75e104f..4c510ae --- a/unit-tests/test-cases/order_file-ans/main.expected +++ b/unit-tests/test-cases/order_file-ans/main.expected @@ -1,4 +1,4 @@ -__Z3barPN17_GLOBAL__N_anchor12myanonstructE -__ZN3wow17_GLOBAL__N_anchor5innerEv -__ZN17_GLOBAL__N_anchor3bazEPNS_12myanonstructE -__ZN17_GLOBAL__N_anchor3fooEv +__Z3barPN12_GLOBAL__N_112myanonstructE +__ZN3wow12_GLOBAL__N_15innerEv +__ZN12_GLOBAL__N_13bazEPNS_12myanonstructE +__ZN12_GLOBAL__N_13fooEv diff --git a/unit-tests/test-cases/order_file-ans/main.order b/unit-tests/test-cases/order_file-ans/main.order old mode 100755 new mode 100644 index 36dd786..4c510ae --- a/unit-tests/test-cases/order_file-ans/main.order +++ b/unit-tests/test-cases/order_file-ans/main.order @@ -1,4 +1,4 @@ -__Z3barPN95_GLOBAL__N__Volumes_my_src_ld64_unit_tests_test_cases_order_file_ans_main.cxx_00000000_38BA812C12myanonstructE -__ZN3wow95_GLOBAL__N__Volumes_my_src_ld64_unit_tests_test_cases_order_file_ans_main.cxx_00000000_38BA812C5innerEv -__ZN95_GLOBAL__N__Volumes_my_src_ld64_unit_tests_test_cases_order_file_ans_main.cxx_00000000_38BA812C3bazEPNS_12myanonstructE -__ZN95_GLOBAL__N__Volumes_my_src_ld64_unit_tests_test_cases_order_file_ans_main.cxx_00000000_38BA812C3fooEv +__Z3barPN12_GLOBAL__N_112myanonstructE +__ZN3wow12_GLOBAL__N_15innerEv +__ZN12_GLOBAL__N_13bazEPNS_12myanonstructE +__ZN12_GLOBAL__N_13fooEv diff --git a/unit-tests/test-cases/order_file/Makefile b/unit-tests/test-cases/order_file/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/extra.s b/unit-tests/test-cases/order_file/extra.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main.c b/unit-tests/test-cases/order_file/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main1.expected b/unit-tests/test-cases/order_file/main1.expected old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main1.order b/unit-tests/test-cases/order_file/main1.order old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main2.expected b/unit-tests/test-cases/order_file/main2.expected old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main2.order b/unit-tests/test-cases/order_file/main2.order old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main3.expected b/unit-tests/test-cases/order_file/main3.expected old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/order_file/main3.order b/unit-tests/test-cases/order_file/main3.order old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/prebound-main/Makefile b/unit-tests/test-cases/prebound-main/Makefile old mode 100755 new mode 100644 index 79ef53e..285d767 --- a/unit-tests/test-cases/prebound-main/Makefile +++ b/unit-tests/test-cases/prebound-main/Makefile @@ -1,25 +1,4 @@ -## -# Copyright (c) 2006 Apple Computer, Inc. All rights reserved. -# -# @APPLE_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. 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_LICENSE_HEADER_END@ -## + TESTROOT = ../.. include ${TESTROOT}/include/common.makefile @@ -43,7 +22,8 @@ endif run: all all: - ${CC} ${CCFLAGS} main.c -o main -prebind -mmacosx-version-min=10.3 + # SnowLeopard is missing libmx.dylib which gcc thinks it needs + ${CC} ${CCFLAGS} main.c -o main -prebind -mmacosx-version-min=10.3 -nostdlib -lcrt1.o -lSystem otool -hv main | grep ${KEYWORD} | ${FAIL_IF_EMPTY} ${PASS_IFF_GOOD_MACHO} main diff --git a/unit-tests/test-cases/prebound-main/main.c b/unit-tests/test-cases/prebound-main/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/prebound-split-seg/Makefile b/unit-tests/test-cases/prebound-split-seg/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/prebound-split-seg/address_table b/unit-tests/test-cases/prebound-split-seg/address_table old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/prebound-split-seg/bar.c b/unit-tests/test-cases/prebound-split-seg/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/private-non-lazy/Makefile b/unit-tests/test-cases/private-non-lazy/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/private-non-lazy/bar.c b/unit-tests/test-cases/private-non-lazy/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/private-non-lazy/comment.txt b/unit-tests/test-cases/private-non-lazy/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/private-non-lazy/foo.c b/unit-tests/test-cases/private-non-lazy/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/private-non-lazy/hello.c b/unit-tests/test-cases/private-non-lazy/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-cases/Makefile b/unit-tests/test-cases/re-export-cases/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-cases/bar.c b/unit-tests/test-cases/re-export-cases/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-cases/baz.c b/unit-tests/test-cases/re-export-cases/baz.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-cases/foo.c b/unit-tests/test-cases/re-export-cases/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-flag/Makefile b/unit-tests/test-cases/re-export-flag/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-flag/bar.c b/unit-tests/test-cases/re-export-flag/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-flag/foo.c b/unit-tests/test-cases/re-export-flag/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/Makefile b/unit-tests/test-cases/re-export-optimizations-indirect/Makefile new file mode 100644 index 0000000..fdb13d5 --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/Makefile @@ -0,0 +1,64 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that a public re-exported library is automatically added as a dependent +# unless nothing is used from it. +# + + +run: all + +all: + +# -sub_library for 10.4 + ${CC} ${CCFLAGS} -dynamiclib bar.c -o libbar.dylib -install_name /usr/lib/libbar.dylib -mmacosx-version-min=10.4 + ${FAIL_IF_BAD_MACHO} libbar.dylib + ${CC} ${CCFLAGS} -dynamiclib middle.c -o libmiddle.dylib -lbar -L. -sub_library libbar -install_name /mid/libmiddle.dylib -mmacosx-version-min=10.4 + ${FAIL_IF_BAD_MACHO} libmiddle.dylib + ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -lmiddle -L. -sub_library libmiddle -install_name /usr/lib/libfoo.dylib -mmacosx-version-min=10.4 + ${FAIL_IF_BAD_MACHO} libfoo.dylib + ${CC} ${CCFLAGS} -dynamiclib other.c -o libother.dylib -lbar -L. -sub_library libbar -install_name /usr/lib/libother.dylib -mmacosx-version-min=10.4 + ${FAIL_IF_BAD_MACHO} libother.dylib + ${CC} ${CCFLAGS} main.c -DCALL_BAR libfoo.dylib libother.dylib -o main -L. -mmacosx-version-min=10.4 + nm -m main | grep _bar | grep libbar | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +# -sub_library for 10.5 + ${CC} ${CCFLAGS} -dynamiclib bar.c -o libbar.dylib -install_name /usr/lib/libbar.dylib -mmacosx-version-min=10.5 + ${FAIL_IF_BAD_MACHO} libbar.dylib + ${CC} ${CCFLAGS} -dynamiclib middle.c -o libmiddle.dylib -lbar -L. -sub_library libbar -install_name /mid/libmiddle.dylib -mmacosx-version-min=10.5 + ${FAIL_IF_BAD_MACHO} libmiddle.dylib + ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib -lmiddle -L. -sub_library libmiddle -install_name /usr/lib/libfoo.dylib -mmacosx-version-min=10.5 + ${FAIL_IF_BAD_MACHO} libfoo.dylib + ${CC} ${CCFLAGS} -dynamiclib other.c -o libother.dylib -lbar -L. -sub_library libbar -install_name /usr/lib/libother.dylib -mmacosx-version-min=10.5 + ${FAIL_IF_BAD_MACHO} libother.dylib + ${CC} ${CCFLAGS} main.c -DCALL_BAR libfoo.dylib libother.dylib -o main -L. -mmacosx-version-min=10.5 + nm -m main | grep _bar | grep libbar | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + + +clean: + rm -rf libbar.dylib libfoo.dylib libmiddle.dylib libother.dylib main diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/bar.c b/unit-tests/test-cases/re-export-optimizations-indirect/bar.c new file mode 100644 index 0000000..9c18401 --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/bar.c @@ -0,0 +1,5 @@ + +int bar (void) +{ + return 1; +} diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/foo.c b/unit-tests/test-cases/re-export-optimizations-indirect/foo.c new file mode 100644 index 0000000..d0cdf47 --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/foo.c @@ -0,0 +1,4 @@ +int foo (void) +{ + return 1; +} diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/main.c b/unit-tests/test-cases/re-export-optimizations-indirect/main.c new file mode 100644 index 0000000..672ef9a --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/main.c @@ -0,0 +1,8 @@ + +extern void bar(); + +int main() +{ + bar(); + return 0; +} diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/middle.c b/unit-tests/test-cases/re-export-optimizations-indirect/middle.c new file mode 100644 index 0000000..d3578a6 --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/middle.c @@ -0,0 +1,3 @@ + +void middle() {} + diff --git a/unit-tests/test-cases/re-export-optimizations-indirect/other.c b/unit-tests/test-cases/re-export-optimizations-indirect/other.c new file mode 100644 index 0000000..0cd6dda --- /dev/null +++ b/unit-tests/test-cases/re-export-optimizations-indirect/other.c @@ -0,0 +1 @@ +void other() {} diff --git a/unit-tests/test-cases/re-export-optimizations/Makefile b/unit-tests/test-cases/re-export-optimizations/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-optimizations/bar.c b/unit-tests/test-cases/re-export-optimizations/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-optimizations/foo.c b/unit-tests/test-cases/re-export-optimizations/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-optimizations/main.c b/unit-tests/test-cases/re-export-optimizations/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-relative-paths/Makefile b/unit-tests/test-cases/re-export-relative-paths/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-relative-paths/bar.c b/unit-tests/test-cases/re-export-relative-paths/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-relative-paths/foo.c b/unit-tests/test-cases/re-export-relative-paths/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-relative-paths/main.c b/unit-tests/test-cases/re-export-relative-paths/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/re-export-relative-paths/wrap.c b/unit-tests/test-cases/re-export-relative-paths/wrap.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/read-only-relocs/Makefile b/unit-tests/test-cases/read-only-relocs/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/read-only-relocs/foo.c b/unit-tests/test-cases/read-only-relocs/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/read-only-relocs/test.c b/unit-tests/test-cases/read-only-relocs/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/rebase-basic/Makefile b/unit-tests/test-cases/rebase-basic/Makefile old mode 100755 new mode 100644 index ba262aa..9373aa3 --- a/unit-tests/test-cases/rebase-basic/Makefile +++ b/unit-tests/test-cases/rebase-basic/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2006 Apple Computer, Inc. All rights reserved. +# Copyright (c) 2006-2008 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -38,16 +38,16 @@ all: ${CC} ${CCFLAGS} -c bar.m -o bar.${ARCH}.o ${FAIL_IF_BAD_OBJ} bar.${ARCH}.o - ${CC} ${CCFLAGS} foo.${ARCH}.o bar.${ARCH}.o -dynamiclib -Wl,-no_uuid -o libfoo.${ARCH}.dylib -framework Foundation -framework CoreFoundation + ${CC} ${CCFLAGS} foo.${ARCH}.o bar.${ARCH}.o -dynamiclib -Wl,-no_uuid -Wl,-no_order_data -o libfoo.${ARCH}.dylib -framework Foundation -framework CoreFoundation ${FAIL_IF_BAD_MACHO} libfoo.${ARCH}.dylib - ${CC} ${CCFLAGS} foo.${ARCH}.o bar.${ARCH}.o -dynamiclib -Wl,-no_uuid -o libfoo-alt.${ARCH}.dylib -framework Foundation -framework CoreFoundation -seg1addr 0x12340000 -install_name libfoo.${ARCH}.dylib + ${CC} ${CCFLAGS} foo.${ARCH}.o bar.${ARCH}.o -dynamiclib -Wl,-no_uuid -Wl,-no_order_data -o libfoo-alt.${ARCH}.dylib -framework Foundation -framework CoreFoundation -seg1addr 0x12340000 -install_name libfoo.${ARCH}.dylib ${FAIL_IF_BAD_MACHO} libfoo-alt.${ARCH}.dylib - - rebase -arch ${ARCH} -low_address 0x12340000 libfoo.${ARCH}.dylib + + ${REBASE} -arch ${ARCH} -low_address 0x12340000 libfoo.${ARCH}.dylib ${FAIL_IF_BAD_MACHO} libfoo.${ARCH}.dylib ${PASS_IFF} diff libfoo.${ARCH}.dylib libfoo-alt.${ARCH}.dylib clean: - rm *.o *.dylib + rm -f *.o *.dylib diff --git a/unit-tests/test-cases/rebase-basic/bar.m b/unit-tests/test-cases/rebase-basic/bar.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/rebase-basic/comment.txt b/unit-tests/test-cases/rebase-basic/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/rebase-basic/foo.c b/unit-tests/test-cases/rebase-basic/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-asm/Makefile b/unit-tests/test-cases/relocs-asm/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-asm/comment.txt b/unit-tests/test-cases/relocs-asm/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-asm/relocs-asm.s b/unit-tests/test-cases/relocs-asm/relocs-asm.s old mode 100755 new mode 100644 index 06e10e8..73c31ea --- a/unit-tests/test-cases/relocs-asm/relocs-asm.s +++ b/unit-tests/test-cases/relocs-asm/relocs-asm.s @@ -21,6 +21,8 @@ * @APPLE_LICENSE_HEADER_END@ */ + + #if __arm__ .text .align 2 @@ -85,6 +87,18 @@ _test_branches: @ call external + addend bne _external+16 + +_pointer_diffs: + nop + bl 1f +1: nop + .long _foo-1b + .long _foo+10-1b + .long _test_branches-1b + .long _test_branches+3-1b + .long (_test_branches - _test_loads) + -2097152 + .long (_test_calls - _test_loads) + -2097152 + #endif #if __ppc__ || __ppc64__ @@ -249,6 +263,12 @@ _test_calls: # call internal + addend call _test_branches+0x19000 + # 16-bit call internal + callw _test_branches + + # 16-bit call internal + addend + callw _test_branches+13 + # call external call _external @@ -276,6 +296,9 @@ _pointer_diffs: movl _foo+10-1b(%eax),%esi movl _test_branches-1b(%eax),%esi movl _test_branches+3-1b(%eax),%esi + cmpl $(( (_test_branches - _test_loads) + -2097152 )),(%esp) + cmpl $(( (_test_calls - _test_loads) + -2097152 )),(%esp) + _word_relocs: callw _pointer_diffs @@ -426,6 +449,9 @@ L1: .quad _test_branches - _test_diffs .quad _test_branches - . .quad _test_branches - L1 .quad L1 - _prev + #tests support for 32-bit absolute pointers + .long _prev + .long L1 # the following generates: _foo cannot be undefined in a subtraction expression # but it should be ok (it will be a linker error if _foo and _bar are not in same linkage unit) diff --git a/unit-tests/test-cases/relocs-c/Makefile b/unit-tests/test-cases/relocs-c/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-c/test.c b/unit-tests/test-cases/relocs-c/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-c2/Makefile b/unit-tests/test-cases/relocs-c2/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-c2/comment.txt b/unit-tests/test-cases/relocs-c2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-c2/test.c b/unit-tests/test-cases/relocs-c2/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals/Makefile b/unit-tests/test-cases/relocs-literals/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals/test.c b/unit-tests/test-cases/relocs-literals/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals2/Makefile b/unit-tests/test-cases/relocs-literals2/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals2/test.c b/unit-tests/test-cases/relocs-literals2/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals3/Makefile b/unit-tests/test-cases/relocs-literals3/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals3/comment.txt b/unit-tests/test-cases/relocs-literals3/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-literals3/test.c b/unit-tests/test-cases/relocs-literals3/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-neg-from-local/Makefile b/unit-tests/test-cases/relocs-neg-from-local/Makefile new file mode 100644 index 0000000..36fb47b --- /dev/null +++ b/unit-tests/test-cases/relocs-neg-from-local/Makefile @@ -0,0 +1,51 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# i386 relocation error with negative offsets from local labels +# + +ifeq (${ARCH},i386) + TARGET = run-i386 +else + TARGET = run-other +endif + +run: ${TARGET} + +run-other: + ${PASS_IFF} /usr/bin/true + + +run-i386: + ${CC} ${ASMFLAGS} test.s -c -o test.o + ${OBJECTDUMP} test.o | grep "__data@0 plus 0xFFFFFFE2" | ${FAIL_IF_EMPTY} + + ${LD} -arch ${ARCH} -r -keep_private_externs test.o -o test-r.o + ${OBJECTDUMP} test-r.o | grep "__data@0 plus 0xFFFFFFE2" | ${PASS_IFF_STDIN} + + +clean: + rm -rf *.o diff --git a/unit-tests/test-cases/relocs-neg-from-local/test.s b/unit-tests/test-cases/relocs-neg-from-local/test.s new file mode 100644 index 0000000..3890f35 --- /dev/null +++ b/unit-tests/test-cases/relocs-neg-from-local/test.s @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2009 Apple Inc. All rights reserved. + * + * @APPLE_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. 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_LICENSE_HEADER_END@ + */ + + + +#if __i386__ + .text + .align 2 + +_negative_offset_from_local_label: + nop + .space 100 + movl -80+L3(,%eax,4), %edx + ret + + .data +L2: .space 50 +L3: .space 50 +_d: .long 0 + +#endif + + diff --git a/unit-tests/test-cases/relocs-objc/Makefile b/unit-tests/test-cases/relocs-objc/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-objc/comment.txt b/unit-tests/test-cases/relocs-objc/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/relocs-objc/test.m b/unit-tests/test-cases/relocs-objc/test.m old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/section-names-long/Makefile b/unit-tests/test-cases/section-names-long/Makefile new file mode 100644 index 0000000..f31d9d6 --- /dev/null +++ b/unit-tests/test-cases/section-names-long/Makefile @@ -0,0 +1,42 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Validate long section names are preserved +# corrupt metaclass entry in dynamic library +# + +all: + ${CC} ${CCFLAGS} main.c a.s c.s b.s -o main + nm -m main | grep __aaaaaaaaaaaaaa | grep __TEXT | grep _at | ${FAIL_IF_EMPTY} + nm -m main | grep __bbbbbbbbbbbbbb | grep __TEXT | grep _bt | ${FAIL_IF_EMPTY} + nm -m main | grep __cccccccccccccc | grep __TEXT | grep _ct | ${FAIL_IF_EMPTY} + nm -m main | grep __aaaaaaaaaaaaaa | grep __DATA | grep _ad | ${FAIL_IF_EMPTY} + nm -m main | grep __bbbbbbbbbbbbbb | grep __DATA | grep _bd | ${FAIL_IF_EMPTY} + nm -m main | grep __cccccccccccccc | grep __DATA | grep _cd | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm -rf main diff --git a/unit-tests/test-cases/section-names-long/a.s b/unit-tests/test-cases/section-names-long/a.s new file mode 100644 index 0000000..d7e5847 --- /dev/null +++ b/unit-tests/test-cases/section-names-long/a.s @@ -0,0 +1,9 @@ + + .section __TEXT,__aaaaaaaaaaaaaa +_at: .space 128 + + .section __DATA,__aaaaaaaaaaaaaa +_ad: .space 128 + + + diff --git a/unit-tests/test-cases/section-names-long/b.s b/unit-tests/test-cases/section-names-long/b.s new file mode 100644 index 0000000..a31d414 --- /dev/null +++ b/unit-tests/test-cases/section-names-long/b.s @@ -0,0 +1,9 @@ + + .section __TEXT,__bbbbbbbbbbbbbb +_bt: .space 128 + + .section __DATA,__bbbbbbbbbbbbbb +_bd: .space 128 + + + diff --git a/unit-tests/test-cases/section-names-long/c.s b/unit-tests/test-cases/section-names-long/c.s new file mode 100644 index 0000000..383b159 --- /dev/null +++ b/unit-tests/test-cases/section-names-long/c.s @@ -0,0 +1,11 @@ + + .section __TEXT,__cccccccccccccc +_ct: .space 128 + + + .section __DATA,__cccccccccccccc +_cd: .space 128 + + + + diff --git a/unit-tests/test-cases/section-names-long/main.c b/unit-tests/test-cases/section-names-long/main.c new file mode 100644 index 0000000..df77448 --- /dev/null +++ b/unit-tests/test-cases/section-names-long/main.c @@ -0,0 +1,4 @@ + + +int main() { return 0; } + diff --git a/unit-tests/test-cases/segment-order/Makefile b/unit-tests/test-cases/segment-order/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/segment-order/expected.order b/unit-tests/test-cases/segment-order/expected.order old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/segment-order/main.c b/unit-tests/test-cases/segment-order/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/segment-order/segJJJ.s b/unit-tests/test-cases/segment-order/segJJJ.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/segment-order/segKKK.s b/unit-tests/test-cases/segment-order/segKKK.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/segment-order/segLLL.s b/unit-tests/test-cases/segment-order/segLLL.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/shared-cache-dylib/Makefile b/unit-tests/test-cases/shared-cache-dylib/Makefile new file mode 100644 index 0000000..cd6dc04 --- /dev/null +++ b/unit-tests/test-cases/shared-cache-dylib/Makefile @@ -0,0 +1,46 @@ +## +# Copyright (c) 2009 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Verify only dylibs with install paths in /System/Library or /usr/lib +# get LC_SEGMENT_SPLIT_INFO +# + + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -dynamiclib -o libfoo.dylib -install_name /usr/lib/libfoo.dylib + otool -lv libfoo.dylib | grep LC_SEGMENT_SPLIT_INFO | ${FAIL_IF_EMPTY} + ${CC} ${CCFLAGS} foo.c -dynamiclib -o libfoo.dylib -install_name /System/Library/Frameworks/Foo.framework/Foo + otool -lv libfoo.dylib | grep LC_SEGMENT_SPLIT_INFO | ${FAIL_IF_EMPTY} + ${CC} ${CCFLAGS} foo.c -dynamiclib -o libfoo.dylib -install_name /usr/local/lib/libfoo.dylib + otool -lv libfoo.dylib | grep LC_SEGMENT_SPLIT_INFO | ${FAIL_IF_STDIN} + ${CC} ${CCFLAGS} foo.c -dynamiclib -o libfoo.dylib + otool -lv libfoo.dylib | grep LC_SEGMENT_SPLIT_INFO | ${FAIL_IF_STDIN} + ${PASS_IFF_GOOD_MACHO} libfoo.dylib + +clean: + rm libfoo.dylib diff --git a/unit-tests/test-cases/shared-cache-dylib/foo.c b/unit-tests/test-cases/shared-cache-dylib/foo.c new file mode 100644 index 0000000..6924ac6 --- /dev/null +++ b/unit-tests/test-cases/shared-cache-dylib/foo.c @@ -0,0 +1,3 @@ + +void foo() {} + diff --git a/unit-tests/test-cases/slow-x86-stubs/Makefile b/unit-tests/test-cases/slow-x86-stubs/Makefile old mode 100755 new mode 100644 index ee6a0e5..e9c09c4 --- a/unit-tests/test-cases/slow-x86-stubs/Makefile +++ b/unit-tests/test-cases/slow-x86-stubs/Makefile @@ -24,7 +24,7 @@ TESTROOT = ../.. include ${TESTROOT}/include/common.makefile # -# Sanity check that -slow_stubs for i386 leaves no __IMPORT segment +# Sanity check that i386 for 10.6 does not use __IMPORT segment # run: all @@ -32,9 +32,9 @@ run: all all: - ${CC} ${CCFLAGS} hello.c -o hello -Wl,-slow_stubs + ${CC} ${CCFLAGS} hello.c -o hello size -l hello | grep __IMPORT | ${FAIL_IF_STDIN} - ${CC} ${CCFLAGS} hello.c -dynamiclib -o libhello.dylib -Wl,-slow_stubs + ${CC} ${CCFLAGS} hello.c -dynamiclib -o libhello.dylib size -l libhello.dylib | grep __IMPORT | ${FAIL_IF_STDIN} ${PASS_IFF_GOOD_MACHO} hello diff --git a/unit-tests/test-cases/slow-x86-stubs/hello.c b/unit-tests/test-cases/slow-x86-stubs/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/special-labels/Makefile b/unit-tests/test-cases/special-labels/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/special-labels/extra.s b/unit-tests/test-cases/special-labels/extra.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/special-labels/main.c b/unit-tests/test-cases/special-labels/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-coalesce/Makefile b/unit-tests/test-cases/stabs-coalesce/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-coalesce/comment.txt b/unit-tests/test-cases/stabs-coalesce/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-coalesce/header.h b/unit-tests/test-cases/stabs-coalesce/header.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-coalesce/hello.cxx b/unit-tests/test-cases/stabs-coalesce/hello.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-coalesce/other.cxx b/unit-tests/test-cases/stabs-coalesce/other.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-directory-slash/Makefile b/unit-tests/test-cases/stabs-directory-slash/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stabs-directory-slash/main.c b/unit-tests/test-cases/stabs-directory-slash/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_no_size/Makefile.newtest b/unit-tests/test-cases/stack_addr_no_size/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_no_size/comment.txt b/unit-tests/test-cases/stack_addr_no_size/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_no_size/main.c b/unit-tests/test-cases/stack_addr_no_size/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_size/Makefile b/unit-tests/test-cases/stack_addr_size/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_size/comment.txt b/unit-tests/test-cases/stack_addr_size/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_addr_size/main.c b/unit-tests/test-cases/stack_addr_size/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_size_no_addr/Makefile b/unit-tests/test-cases/stack_size_no_addr/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_size_no_addr/comment.txt b/unit-tests/test-cases/stack_size_no_addr/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stack_size_no_addr/main.c b/unit-tests/test-cases/stack_size_no_addr/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/static-executable/Makefile b/unit-tests/test-cases/static-executable/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/static-executable/test.c b/unit-tests/test-cases/static-executable/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/static-strip/Makefile.newtest b/unit-tests/test-cases/static-strip/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/static-strip/comment.txt b/unit-tests/test-cases/static-strip/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/static-strip/test.c b/unit-tests/test-cases/static-strip/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test2/Makefile b/unit-tests/test-cases/strip-test2/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test2/comment.txt b/unit-tests/test-cases/strip-test2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test2/main.cxx b/unit-tests/test-cases/strip-test2/main.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test3/Makefile.newtest b/unit-tests/test-cases/strip-test3/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test3/comment.txt b/unit-tests/test-cases/strip-test3/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip-test3/main.cxx b/unit-tests/test-cases/strip-test3/main.cxx old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip_local/Makefile b/unit-tests/test-cases/strip_local/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip_local/foo.c b/unit-tests/test-cases/strip_local/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/strip_local/hello.c b/unit-tests/test-cases/strip_local/hello.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/Makefile b/unit-tests/test-cases/stripped-indirect-symbol-table/Makefile old mode 100755 new mode 100644 index c0647b3..fcb7e7d --- a/unit-tests/test-cases/stripped-indirect-symbol-table/Makefile +++ b/unit-tests/test-cases/stripped-indirect-symbol-table/Makefile @@ -1,5 +1,5 @@ ## -# Copyright (c) 2007 Apple Inc. All rights reserved. +# Copyright (c) 2007-2009 Apple Inc. All rights reserved. # # @APPLE_LICENSE_HEADER_START@ # @@ -23,18 +23,14 @@ TESTROOT = ../.. include ${TESTROOT}/include/common.makefile -ifeq "${ARCH}" "i386" - POINTER_SEGMENT = __IMPORT - POINTER_SECTION = __pointers -else - POINTER_SEGMENT = __DATA - POINTER_SECTION = __nl_symbol_ptr -endif +POINTER_SEGMENT = __DATA +POINTER_SECTION = __nl_symbol_ptr # # Test that using strip -R to selectively strip symbol names # of of a .o file still works with ld. +# And for i386 that there are no __IMPORT/__pointers left # run: all @@ -51,6 +47,8 @@ all: ${CC} ${CCFLAGS} all.o -dynamiclib -o dylib2 otool -X -s ${POINTER_SEGMENT} ${POINTER_SECTION} dylib1 >dylib1.pointers otool -X -s ${POINTER_SEGMENT} ${POINTER_SECTION} dylib2 >dylib2.pointers + size -l dylib1 | grep __IMPORT | ${FAIL_IF_STDIN} + size -l dylib2 | grep __IMPORT | ${FAIL_IF_STDIN} ${PASS_IFF} diff dylib1.pointers dylib2.pointers clean: diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/a.c b/unit-tests/test-cases/stripped-indirect-symbol-table/a.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/b.c b/unit-tests/test-cases/stripped-indirect-symbol-table/b.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/c.c b/unit-tests/test-cases/stripped-indirect-symbol-table/c.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/func.c b/unit-tests/test-cases/stripped-indirect-symbol-table/func.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stripped-indirect-symbol-table/strip.list b/unit-tests/test-cases/stripped-indirect-symbol-table/strip.list old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stub-generation-weak/Makefile b/unit-tests/test-cases/stub-generation-weak/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stub-generation-weak/foo.c b/unit-tests/test-cases/stub-generation-weak/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stub-generation-weak/main.c b/unit-tests/test-cases/stub-generation-weak/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stub-generation/Makefile b/unit-tests/test-cases/stub-generation/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/stub-generation/test.c b/unit-tests/test-cases/stub-generation/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/switch-jump-table/Makefile b/unit-tests/test-cases/switch-jump-table/Makefile old mode 100755 new mode 100644 index aacd78d..847dc78 --- a/unit-tests/test-cases/switch-jump-table/Makefile +++ b/unit-tests/test-cases/switch-jump-table/Makefile @@ -25,14 +25,23 @@ include ${TESTROOT}/include/common.makefile # # Test that -mdynamic-no-pic jump table in the middle of -# a function does not cause relocations. +# a function does not cause relocations. # # SPEC2000/eon built with -mdynamic-no-pic won't run # -run: all +run: test-run-${ARCH} -all: + +test-run-ppc: + ${PASS_IFF} true + +test-run-x86_64: + ${PASS_IFF} true + +test-run-armv6: test-run-i386 + +test-run-i386: # check jump table in a weak function ${CC} ${CCFLAGS} main.c switch.s -o main otool -rv main | grep _foo | ${FAIL_IF_STDIN} @@ -48,7 +57,7 @@ all: # check jump table with -pie, should have no external and some local relocations ${CC} ${CCFLAGS} main.c switch.s -o main -Wl,-pie -read_only_relocs suppress otool -rv main | grep "External relocation" | ${FAIL_IF_STDIN} - otool -rv main | grep "Local relocation" | ${FAIL_IF_EMPTY} +# otool -rv main | grep "Local relocation" | ${FAIL_IF_EMPTY} ${PASS_IFF_GOOD_MACHO} main diff --git a/unit-tests/test-cases/switch-jump-table/interpose.exp b/unit-tests/test-cases/switch-jump-table/interpose.exp old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/switch-jump-table/main.c b/unit-tests/test-cases/switch-jump-table/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/switch-jump-table/switch.s b/unit-tests/test-cases/switch-jump-table/switch.s old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/Makefile b/unit-tests/test-cases/symbol-moving/Makefile old mode 100755 new mode 100644 index fc85d7b..9e63ee5 --- a/unit-tests/test-cases/symbol-moving/Makefile +++ b/unit-tests/test-cases/symbol-moving/Makefile @@ -90,4 +90,4 @@ all: clean: - rm -rf libbar.dylib libfoo.dylib main-10.4 main-10.5 main-10.4a main-10.5a + rm -rf libbar.dylib libfoo.dylib main-10.4 main-10.5 main-10.4a main-10.5a Frameworks diff --git a/unit-tests/test-cases/symbol-moving/aaa.c b/unit-tests/test-cases/symbol-moving/aaa.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/anotb.c b/unit-tests/test-cases/symbol-moving/anotb.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/bar.c b/unit-tests/test-cases/symbol-moving/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/bbb.c b/unit-tests/test-cases/symbol-moving/bbb.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/bnota.c b/unit-tests/test-cases/symbol-moving/bnota.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/foo.c b/unit-tests/test-cases/symbol-moving/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/symbol-moving/main.c b/unit-tests/test-cases/symbol-moving/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-and-archive/Makefile b/unit-tests/test-cases/tentative-and-archive/Makefile old mode 100755 new mode 100644 index e8a4a0e..ee5341d --- a/unit-tests/test-cases/tentative-and-archive/Makefile +++ b/unit-tests/test-cases/tentative-and-archive/Makefile @@ -29,22 +29,31 @@ SHELL = bash # use bash shell so we can redirect just stderr # # Test how tentative definitions interact with archives # main.c has a tenative definition for _var which -# should *not* cause libfoo.a(foo.o) to be loaded. +# should cause libfoo.a(foo.o) to be loaded which in turn +# should cause _bar from libbar.dylib to be used. # # ld crashes building XsanFS # -undefined dynamic_lookup causes spurious extra symbols +# need to search for definitions for common symbols # run: all all: + ${CC} ${CCFLAGS} bar.c -dynamiclib -o libbar.dylib ${CC} ${CCFLAGS} foo.c -c -o foo.o - libtool -static foo.o -o libfoo.a - ${CC} ${CCFLAGS} main.c libfoo.a -o main + libtool -static foo.o -o libfoo.a + ${CC} ${CCFLAGS} main.c libfoo.a libbar.dylib -o main + # verify _foo got pulled in because _var was a tentative in main.o + nm main | grep "_foo" | ${FAIL_IF_EMPTY} + # verify -dead_strip pulls in non-tentative _var from libfoo.a + ${CC} ${CCFLAGS} main.c libfoo.a libbar.dylib -o main -dead_strip + nm -m main | grep "_var" | grep __data | ${FAIL_IF_EMPTY} + # verify dynamic_lookup works and has no duplicate symbols ${CC} ${CCFLAGS} main.c libfoo.a -o main -undefined dynamic_lookup - nm -m main | grep "looked up" | ${FAIL_IF_STDIN} + nm -m main | grep "looked up" | ${FAIL_IF_EMPTY} ${PASS_IFF_GOOD_MACHO} main clean: - rm -rf main libfoo.a foo.o + rm -rf main libfoo.a foo.o libbar.dylib diff --git a/unit-tests/test-cases/tentative-and-archive/bar.c b/unit-tests/test-cases/tentative-and-archive/bar.c new file mode 100644 index 0000000..e425999 --- /dev/null +++ b/unit-tests/test-cases/tentative-and-archive/bar.c @@ -0,0 +1 @@ +void bar() {} diff --git a/unit-tests/test-cases/tentative-and-archive/foo.c b/unit-tests/test-cases/tentative-and-archive/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-and-archive/main.c b/unit-tests/test-cases/tentative-and-archive/main.c old mode 100755 new mode 100644 index e5046a0..a01e6b0 --- a/unit-tests/test-cases/tentative-and-archive/main.c +++ b/unit-tests/test-cases/tentative-and-archive/main.c @@ -1,5 +1,6 @@ int var; +int other_tent; int main() { diff --git a/unit-tests/test-cases/tentative-and-dylib/Makefile b/unit-tests/test-cases/tentative-and-dylib/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-and-dylib/bar.c b/unit-tests/test-cases/tentative-and-dylib/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-and-dylib/foo.c b/unit-tests/test-cases/tentative-and-dylib/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-and-dylib/main.c b/unit-tests/test-cases/tentative-and-dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-to-real-hidden/Makefile b/unit-tests/test-cases/tentative-to-real-hidden/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-to-real-hidden/test.c b/unit-tests/test-cases/tentative-to-real-hidden/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-to-real/Makefile b/unit-tests/test-cases/tentative-to-real/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-to-real/comment.txt b/unit-tests/test-cases/tentative-to-real/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/tentative-to-real/test.c b/unit-tests/test-cases/tentative-to-real/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/thumb-blx/Makefile b/unit-tests/test-cases/thumb-blx/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/thumb-blx/test.c b/unit-tests/test-cases/thumb-blx/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/thumb-pointer/Makefile b/unit-tests/test-cases/thumb-pointer/Makefile new file mode 100644 index 0000000..b4364b8 --- /dev/null +++ b/unit-tests/test-cases/thumb-pointer/Makefile @@ -0,0 +1,49 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + +# +# pointers to thumb symbols can be mangled +# + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + ${CC} ${CCFLAGS} bar.c -c -o bar.o + # verify no +1 thumb errors + ${FAIL_IF_ERROR} ${OBJECTDUMP} foo.o | grep "plus 0x00000001" | ${FAIL_IF_STDIN} + ${FAIL_IF_ERROR} ${OBJECTDUMP} bar.o | grep "plus 0x00000001" | ${FAIL_IF_STDIN} + ${LD} -arch ${ARCH} -r -keep_private_externs foo.o bar.o -o foobar.o + ${LD} -arch ${ARCH} -r -keep_private_externs foobar.o -o foobar2.o + ${FAIL_IF_ERROR} ${OBJECTDUMP} -no_content foobar.o > foobar.o.dump + ${FAIL_IF_ERROR} ${OBJECTDUMP} -no_content foobar2.o > foobar2.o.dump + # verify no +1 thumb errors in merged result + grep "plus 0x00000001" foobar.o.dump | ${FAIL_IF_STDIN} + # verify round trip though ld -r works + ${PASS_IFF} diff foobar.o.dump foobar2.o.dump + +clean: + rm -rf foo.o bar.o foobar.o foobar2.o foobar.o.dump foobar2.o.dump diff --git a/unit-tests/test-cases/thumb-pointer/bar.c b/unit-tests/test-cases/thumb-pointer/bar.c new file mode 100644 index 0000000..202a0b3 --- /dev/null +++ b/unit-tests/test-cases/thumb-pointer/bar.c @@ -0,0 +1,5 @@ + +void bar1() {} +void bar2() {} +char bar_array[3] = { 1,2,3 }; + diff --git a/unit-tests/test-cases/thumb-pointer/foo.c b/unit-tests/test-cases/thumb-pointer/foo.c new file mode 100644 index 0000000..96a8a33 --- /dev/null +++ b/unit-tests/test-cases/thumb-pointer/foo.c @@ -0,0 +1,14 @@ + + +extern void bar1(); +extern void bar2(); +extern char bar_array[]; + +void foo1() {} +void foo2() {} +char foo_array[3] = { 1,2,3 }; + + + +void* foostuff[] = { &foo1, &foo2, foo_array, &foo_array[3] }; +void* barstuff[] = { &bar1, &bar2, bar_array, &bar_array[3] }; diff --git a/unit-tests/test-cases/undefined-dynamic-lookup/Makefile b/unit-tests/test-cases/undefined-dynamic-lookup/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/undefined-dynamic-lookup/main.c b/unit-tests/test-cases/undefined-dynamic-lookup/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/unexported_symbols_list-r/Makefile b/unit-tests/test-cases/unexported_symbols_list-r/Makefile new file mode 100644 index 0000000..7aba765 --- /dev/null +++ b/unit-tests/test-cases/unexported_symbols_list-r/Makefile @@ -0,0 +1,40 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + +# +# Verify -unexported_symbols_list works with -r +# Building kext x86_64 with unexported symbols file causes linking problems +# + +run: all + +all: + ${CC} ${CCFLAGS} foo.c -c -o foo.o + ${LD} -arch ${ARCH} foo.o -r -unexported_symbols_list foo.exp -o foo2.o + nm -m foo2.o | grep _foo | grep "non-external" | ${PASS_IFF_STDIN} + +clean: + rm -rf foo.o foo2.o diff --git a/unit-tests/test-cases/unexported_symbols_list-r/foo.c b/unit-tests/test-cases/unexported_symbols_list-r/foo.c new file mode 100644 index 0000000..7bb9849 --- /dev/null +++ b/unit-tests/test-cases/unexported_symbols_list-r/foo.c @@ -0,0 +1,9 @@ + +extern int fooCount; +extern int barCount; + +void foo() { fooCount++; } +void bar() { barCount++; } +int global = 4; +int googoo = 5; + diff --git a/unit-tests/test-cases/unexported_symbols_list-r/foo.exp b/unit-tests/test-cases/unexported_symbols_list-r/foo.exp new file mode 100644 index 0000000..c39774c --- /dev/null +++ b/unit-tests/test-cases/unexported_symbols_list-r/foo.exp @@ -0,0 +1,3 @@ +_foo +_global + diff --git a/unit-tests/test-cases/visibility-warning-dylib-v-archive/Makefile b/unit-tests/test-cases/visibility-warning-dylib-v-archive/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning-dylib-v-archive/bar.c b/unit-tests/test-cases/visibility-warning-dylib-v-archive/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning-dylib-v-archive/foo.c b/unit-tests/test-cases/visibility-warning-dylib-v-archive/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning-dylib-v-archive/main.c b/unit-tests/test-cases/visibility-warning-dylib-v-archive/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning/Makefile b/unit-tests/test-cases/visibility-warning/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning/foo.c b/unit-tests/test-cases/visibility-warning/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning/foo_hidden.c b/unit-tests/test-cases/visibility-warning/foo_hidden.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning/foo_weak.c b/unit-tests/test-cases/visibility-warning/foo_weak.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/visibility-warning/foo_weak_hidden.c b/unit-tests/test-cases/visibility-warning/foo_weak_hidden.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak-def-flag/Makefile b/unit-tests/test-cases/weak-def-flag/Makefile new file mode 100644 index 0000000..71d5db6 --- /dev/null +++ b/unit-tests/test-cases/weak-def-flag/Makefile @@ -0,0 +1,46 @@ +## +# Copyright (c) 2008 Apple Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + + +# +# +# Tests that a main executable with a weak symbol has MH_WEAK_DEFINES +# Tests that a main executable with a weak symbol made non-global by +# an export list does not has MH_WEAK_DEFINES +# + +run: all + +all: + ${CC} ${CCFLAGS} main.c -o main + otool -hv main | grep WEAK_DEFINES | ${FAIL_IF_EMPTY} + ${CC} ${CCFLAGS} main.c -o main -Wl,-exported_symbol,_main + otool -hv main | grep WEAK_DEFINES | ${FAIL_IF_STDIN} + ${CC} ${CCFLAGS} main.c -o main -Wl,-exported_symbol,_my_weak + otool -hv main | grep WEAK_DEFINES | ${FAIL_IF_EMPTY} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm main diff --git a/unit-tests/test-cases/weak-def-flag/main.c b/unit-tests/test-cases/weak-def-flag/main.c new file mode 100644 index 0000000..9cb4dfb --- /dev/null +++ b/unit-tests/test-cases/weak-def-flag/main.c @@ -0,0 +1,13 @@ +#include + +void __attribute__((weak)) my_weak() +{ + +} + +int main() +{ + my_weak(); + return 0; +} + diff --git a/unit-tests/test-cases/weak-def-ordinal/Makefile b/unit-tests/test-cases/weak-def-ordinal/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak-def-ordinal/bar.c b/unit-tests/test-cases/weak-def-ordinal/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak-def-ordinal/foo.c b/unit-tests/test-cases/weak-def-ordinal/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak-def-ordinal/main.c b/unit-tests/test-cases/weak-def-ordinal/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/Makefile b/unit-tests/test-cases/weak_dylib/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/bar.c b/unit-tests/test-cases/weak_dylib/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/bar.h b/unit-tests/test-cases/weak_dylib/bar.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/foo.c b/unit-tests/test-cases/weak_dylib/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/foo.h b/unit-tests/test-cases/weak_dylib/foo.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_dylib/main.c b/unit-tests/test-cases/weak_dylib/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import-force/Makefile b/unit-tests/test-cases/weak_import-force/Makefile new file mode 100644 index 0000000..79ce07c --- /dev/null +++ b/unit-tests/test-cases/weak_import-force/Makefile @@ -0,0 +1,44 @@ +## +# Copyright (c) 2008 Apple Computer, Inc. All rights reserved. +# +# @APPLE_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. 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_LICENSE_HEADER_END@ +## +TESTROOT = ../.. +include ${TESTROOT}/include/common.makefile + +# +# Test that -weak_library marks all symbols used as weak +# + + +run: all + +all: + ${CC} ${CCFLAGS} -dynamiclib foo.c -o libfoo.dylib + ${FAIL_IF_BAD_MACHO} libfoo.dylib + ${CC} ${CCFLAGS} -dynamiclib bar.c -o libbar.dylib + ${FAIL_IF_BAD_MACHO} libbar.dylib + ${CC} ${CCFLAGS} main.c -o main -weak_library libfoo.dylib libbar.dylib + nm -m main | grep _foo1 | grep weak | ${FAIL_IF_EMPTY} + nm -m main | grep _bar | grep weak | ${FAIL_IF_STDIN} + ${PASS_IFF_GOOD_MACHO} main + +clean: + rm -rf libfoo.dylib libbar.dylib main diff --git a/unit-tests/test-cases/weak_import-force/bar.c b/unit-tests/test-cases/weak_import-force/bar.c new file mode 100644 index 0000000..611f2d9 --- /dev/null +++ b/unit-tests/test-cases/weak_import-force/bar.c @@ -0,0 +1,9 @@ + + + +void bar1() {} +void bar2() {} + + +int bar_data1 = 0; +int bar_data2 = 0; diff --git a/unit-tests/test-cases/weak_import-force/foo.c b/unit-tests/test-cases/weak_import-force/foo.c new file mode 100644 index 0000000..c0bbc1e --- /dev/null +++ b/unit-tests/test-cases/weak_import-force/foo.c @@ -0,0 +1,9 @@ + + + +void foo1() {} +void foo2() {} + + +int foo_data1 = 0; +int foo_data2 = 0; diff --git a/unit-tests/test-cases/weak_import-force/main.c b/unit-tests/test-cases/weak_import-force/main.c new file mode 100644 index 0000000..3b9cdff --- /dev/null +++ b/unit-tests/test-cases/weak_import-force/main.c @@ -0,0 +1,31 @@ + +extern void foo1(); +extern void foo2(); +extern void bar1(); +extern void bar2(); + +extern int foo_data1; +extern int foo_data2; +extern int bar_data1; +extern int bar_data2; + + + +// make external relocation to foo_data1 and bar_data1 +int* pfoo = &foo_data1; +int* pbar = &bar_data1; + + +int main (void) +{ + // make non-lazy reference to foo1 and bar1 + if ( &foo1 == &bar1 ) { + // make lazy reference to foo2 and bar2 + foo2(); + bar2(); + } + + // make non-lazy reference to foo_data2 and bar_data2 + return *pfoo + *pbar + foo_data2 + bar_data2; +} + diff --git a/unit-tests/test-cases/weak_import/Makefile b/unit-tests/test-cases/weak_import/Makefile old mode 100755 new mode 100644 index d1fa1f3..cdacfc9 --- a/unit-tests/test-cases/weak_import/Makefile +++ b/unit-tests/test-cases/weak_import/Makefile @@ -34,7 +34,7 @@ all: ${CC} ${CCFLAGS} -dynamiclib -single_module foo.c -o libfoo-${ARCH}.dylib ${FAIL_IF_BAD_MACHO} libfoo-${ARCH}.dylib - ${CC} ${CCFLAGS} -mmacosx-version-min=10.4 main.c -o main-${ARCH} libfoo-${ARCH}.dylib + ${CC} ${CCFLAGS} main.c -o main-${ARCH} libfoo-${ARCH}.dylib nm -m main-${ARCH} | grep _func1 | grep -v weak >/dev/null nm -m main-${ARCH} | grep _func2 | grep weak >/dev/null nm -m main-${ARCH} | grep _func3 | grep -v weak >/dev/null @@ -43,10 +43,12 @@ all: nm -m main-${ARCH} | grep _data2 | grep weak >/dev/null nm -m main-${ARCH} | grep _data3 | grep -v weak >/dev/null nm -m main-${ARCH} | grep _data4 | grep weak >/dev/null - otool -rv main-${ARCH} | grep _data6 > /dev/null + nm -m main-${ARCH} | grep _data5 | grep -v weak >/dev/null + nm -m main-${ARCH} | grep _data6 | grep weak >/dev/null + #otool -rv main-${ARCH} | grep _data6 > /dev/null ${FAIL_IF_BAD_MACHO} main-${ARCH} - ${CC} ${CCFLAGS} -mmacosx-version-min=10.4 main.c -dynamiclib -o main-${ARCH}.dylib libfoo-${ARCH}.dylib + ${CC} ${CCFLAGS} main.c -dynamiclib -o main-${ARCH}.dylib libfoo-${ARCH}.dylib nm -m main-${ARCH}.dylib | grep _func1 | grep -v weak >/dev/null nm -m main-${ARCH}.dylib | grep _func2 | grep weak >/dev/null nm -m main-${ARCH}.dylib | grep _func3 | grep -v weak >/dev/null @@ -55,7 +57,7 @@ all: nm -m main-${ARCH}.dylib | grep _data2 | grep weak >/dev/null nm -m main-${ARCH}.dylib | grep _data3 | grep -v weak >/dev/null nm -m main-${ARCH}.dylib | grep _data4 | grep weak >/dev/null - otool -rv main-${ARCH}.dylib | grep _data6 > /dev/null + #otool -rv main-${ARCH}.dylib | grep _data6 > /dev/null ${PASS_IFF_GOOD_MACHO} main-${ARCH}.dylib clean: diff --git a/unit-tests/test-cases/weak_import/foo.c b/unit-tests/test-cases/weak_import/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import/foo.h b/unit-tests/test-cases/weak_import/foo.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import/main.c b/unit-tests/test-cases/weak_import/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/Makefile.newtest b/unit-tests/test-cases/weak_import2/Makefile.newtest old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/comment.txt b/unit-tests/test-cases/weak_import2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/foo.c b/unit-tests/test-cases/weak_import2/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/foo.h b/unit-tests/test-cases/weak_import2/foo.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/foo1.c b/unit-tests/test-cases/weak_import2/foo1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import2/main.c b/unit-tests/test-cases/weak_import2/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/Makefile b/unit-tests/test-cases/weak_import3/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/comment.txt b/unit-tests/test-cases/weak_import3/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/foo.c b/unit-tests/test-cases/weak_import3/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/foo.h b/unit-tests/test-cases/weak_import3/foo.h old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/foo1.c b/unit-tests/test-cases/weak_import3/foo1.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/weak_import3/main.c b/unit-tests/test-cases/weak_import3/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/why_live/Makefile b/unit-tests/test-cases/why_live/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/why_live/bar.c b/unit-tests/test-cases/why_live/bar.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/why_live/foo.c b/unit-tests/test-cases/why_live/foo.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/why_live/main.c b/unit-tests/test-cases/why_live/main.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill/Makefile b/unit-tests/test-cases/zero-fill/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill/test.c b/unit-tests/test-cases/zero-fill/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill2/Makefile b/unit-tests/test-cases/zero-fill2/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill2/comment.txt b/unit-tests/test-cases/zero-fill2/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill2/test.c b/unit-tests/test-cases/zero-fill2/test.c old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill3/Makefile b/unit-tests/test-cases/zero-fill3/Makefile old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill3/comment.txt b/unit-tests/test-cases/zero-fill3/comment.txt old mode 100755 new mode 100644 diff --git a/unit-tests/test-cases/zero-fill3/test.c b/unit-tests/test-cases/zero-fill3/test.c old mode 100755 new mode 100644 -- 2.45.2