Skip to content

Commit

Permalink
[Mach-O] Deduplicate comdat sections
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed May 21, 2022
1 parent e293d56 commit 0b6fa20
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions macho/dead-strip.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ static bool refers_live_subsection(Subsection<E> &subsec) {

template <typename E>
static void mark(Context<E> &ctx, const std::vector<Subsection<E> *> &rootset) {
for (ObjectFile<E> *file : ctx.objs)
for (std::unique_ptr<Subsection<E>> &subsec : file->subsections)
subsec->is_alive = false;

for (Subsection<E> *subsec : rootset)
visit(ctx, *subsec);

Expand Down
19 changes: 19 additions & 0 deletions macho/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,23 @@ static void create_internal_file(Context<E> &ctx) {
add("___dso_handle");
}

// Remove unreferenced subsections to eliminate code and data
// referenced by duplicated weakdef symbols.
template <typename E>
static void remove_unreferenced_subsections(Context<E> &ctx) {
for (ObjectFile<E> *file : ctx.objs)
for (Symbol<E> *sym : file->syms)
if (sym->file == file && sym->subsec)
sym->subsec->is_alive = true;

for (ObjectFile<E> *file : ctx.objs) {
std::erase_if(file->subsections,
[](const std::unique_ptr<Subsection<E>> &subsec) {
return !subsec->is_alive;
});
}
}

template <typename E>
static bool compare_segments(const std::unique_ptr<OutputSegment<E>> &a,
const std::unique_ptr<OutputSegment<E>> &b) {
Expand Down Expand Up @@ -535,6 +552,8 @@ static int do_main(int argc, char **argv) {
std::erase_if(ctx.objs, [](ObjectFile<E> *file) { return !file->is_alive; });
std::erase_if(ctx.dylibs, [](DylibFile<E> *file) { return !file->is_alive; });

remove_unreferenced_subsections(ctx);

if (ctx.arg.trace) {
for (ObjectFile<E> *file : ctx.objs)
SyncOut(ctx) << *file;
Expand Down

0 comments on commit 0b6fa20

Please sign in to comment.