summaryrefslogtreecommitdiffstats
path: root/lld/lib/ReaderWriter/ELF/ArrayOrderPass.cpp
blob: b74c6dd6a8dcda92ba426f7b8c3f017e432b2182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//===- lib/ReaderWriter/ELF/ArrayOrderPass.cpp ----------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ArrayOrderPass.h"
#include <algorithm>
#include <limits>

namespace lld {
namespace elf {
void ArrayOrderPass::perform(std::unique_ptr<MutableFile> &f) {
  auto definedAtoms = f->definedAtoms();

  // Move sections need to be sorted into the separate continious group.
  // That reduces a number of sorting elements and simplifies conditions
  // in the sorting predicate.
  auto last = std::stable_partition(definedAtoms.begin(), definedAtoms.end(),
                                    [](const DefinedAtom *atom) {
    if (atom->sectionChoice() != DefinedAtom::sectionCustomRequired)
      return false;

    StringRef name = atom->customSectionName();
    return name.startswith(".init_array") || name.startswith(".fini_array");
  });

  std::stable_sort(definedAtoms.begin(), last,
                   [](const DefinedAtom *left, const DefinedAtom *right) {
    StringRef leftSec = left->customSectionName();
    StringRef rightSec = right->customSectionName();

    // Drop the front dot from the section name and get
    // an optional section's number starting after the second dot.
    StringRef leftNum = leftSec.drop_front().rsplit('.').second;
    StringRef rightNum = rightSec.drop_front().rsplit('.').second;

    // Sort {.init_array, .fini_array}[.<num>] sections
    // according to their number. Sections without optional
    // numer suffix should go last.

    uint32_t leftPriority = std::numeric_limits<uint32_t>::max();
    if (!leftNum.empty())
      leftNum.getAsInteger(10, leftPriority);

    uint32_t rightPriority = std::numeric_limits<uint32_t>::max();
    if (!rightNum.empty())
      rightNum.getAsInteger(10, rightPriority);

    return leftPriority < rightPriority;
  });
}
} // end namespace elf
} // end namespace lld
OpenPOWER on IntegriCloud