]> git.saurik.com Git - apple/ld64.git/blob - src/ld/passes/order_file.cpp
ld64-123.2.tar.gz
[apple/ld64.git] / src / ld / passes / order_file.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2009 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26 #include <stdint.h>
27 #include <math.h>
28 #include <unistd.h>
29 #include <dlfcn.h>
30 #include <mach/machine.h>
31
32 #include <vector>
33 #include <map>
34
35 #include "ld.hpp"
36 #include "order_file.h"
37
38 namespace ld {
39 namespace passes {
40 namespace order_file {
41
42 //
43 // The purpose of this pass is to take the graph of all Atoms and produce an ordered
44 // sequence of atoms. The constraints are that: 1) all Atoms of the same Segment must
45 // be contiguous, 2) all Atoms of the same Section must be contigous, 3) Atoms specified
46 // in an order_file are sequenced as in the order_file and before Atoms not specified,
47 // 4) Atoms in the same section from the same .o file should be contiguous and sequenced
48 // in the same order they were in the .o file, 5) Atoms in the same Section but which came
49 // from different .o files should be sequenced in the same order that the .o files
50 // were passed to the linker (i.e. command line order).
51 //
52 // The way this is implemented is that the linker passes a "base ordinal" to each File
53 // as it is constructed. Add each atom has an objectAddress() method. Then
54 // sorting is just sorting by section, then by file ordinal, then by object address.
55 //
56 // If an order_file is specified, it gets more complicated. First, an override-ordinal map
57 // is created. It causes the sort routine to ignore the value returned by ordinal() and objectAddress()
58 // and use the override value instead. Next some Atoms must be layed out consecutively
59 // (e.g. hand written assembly that does not end with return, but rather falls into
60 // the next label). This is modeled in via a kindNoneFollowOn fixup. The use of
61 // kindNoneFollowOn fixups produces "clusters" of atoms that must stay together.
62 // If an order_file tries to move one atom, it may need to move a whole cluster. The
63 // algorithm to do this models clusters using two maps. The "starts" maps maps any
64 // atom in a cluster to the first Atom in the cluster. The "nexts" maps an Atom in a
65 // cluster to the next Atom in the cluster. With this in place, while processing an
66 // order_file, if any entry is in a cluster (in "starts" map), then the entire cluster is
67 // given ordinal overrides.
68 //
69
70 class Layout
71 {
72 public:
73 Layout(const Options& opts, ld::Internal& state);
74 void doPass();
75 private:
76
77 class Comparer {
78 public:
79 Comparer(const Layout& l) : _layout(l) {}
80 bool operator()(const ld::Atom* left, const ld::Atom* right);
81 private:
82 const Layout& _layout;
83 };
84
85 class CStringEquals {
86 public:
87 bool operator()(const char* left, const char* right) const { return (strcmp(left, right) == 0); }
88 };
89 typedef __gnu_cxx::hash_map<const char*, const ld::Atom*, __gnu_cxx::hash<const char*>, CStringEquals> NameToAtom;
90
91 typedef std::map<const ld::Atom*, const ld::Atom*> AtomToAtom;
92
93 typedef std::map<const ld::Atom*, uint32_t> AtomToOrdinal;
94
95 const ld::Atom* findAtom(const Options::OrderedSymbol& orderedSymbol);
96 void buildNameTable();
97 void buildFollowOnTables();
98 void buildOrdinalOverrideMap();
99 const ld::Atom* follower(const ld::Atom* atom);
100 static bool matchesObjectFile(const ld::Atom* atom, const char* objectFileLeafName);
101 bool orderableSection(const ld::Internal::FinalSection*);
102
103 const Options& _options;
104 ld::Internal& _state;
105 AtomToAtom _followOnStarts;
106 AtomToAtom _followOnNexts;
107 NameToAtom _nameTable;
108 std::vector<const ld::Atom*> _nameCollisionAtoms;
109 AtomToOrdinal _ordinalOverrideMap;
110 Comparer _comparer;
111 bool _haveOrderFile;
112
113 static bool _s_log;
114 };
115
116 bool Layout::_s_log = false;
117
118 Layout::Layout(const Options& opts, ld::Internal& state)
119 : _options(opts), _state(state), _comparer(*this), _haveOrderFile(opts.orderedSymbolsCount() != 0)
120 {
121 }
122
123
124 bool Layout::Comparer::operator()(const ld::Atom* left, const ld::Atom* right)
125 {
126 if ( left == right )
127 return false;
128
129 // magic section$start symbol always sorts to the start of its section
130 if ( left->contentType() == ld::Atom::typeSectionStart )
131 return true;
132 if ( right->contentType() == ld::Atom::typeSectionStart )
133 return false;
134
135 // if a -order_file is specified, then sorting is altered to sort those symbols first
136 if ( _layout._haveOrderFile ) {
137 AtomToOrdinal::const_iterator leftPos = _layout._ordinalOverrideMap.find(left);
138 AtomToOrdinal::const_iterator rightPos = _layout._ordinalOverrideMap.find(right);
139 AtomToOrdinal::const_iterator end = _layout._ordinalOverrideMap.end();
140 if ( leftPos != end ) {
141 if ( rightPos != end ) {
142 // both left and right are overridden, so compare overridden ordinals
143 return leftPos->second < rightPos->second;
144 }
145 else {
146 // left is overridden and right is not, so left < right
147 return true;
148 }
149 }
150 else {
151 if ( rightPos != end ) {
152 // right is overridden and left is not, so right < left
153 return false;
154 }
155 else {
156 // neither are overridden,
157 // fall into default sorting below
158 }
159 }
160 }
161
162 // magic section$end symbol always sorts to the end of its section
163 if ( left->contentType() == ld::Atom::typeSectionEnd )
164 return false;
165 if ( right->contentType() == ld::Atom::typeSectionEnd )
166 return true;
167
168 // the __common section can have real or tentative definitions
169 // we want the real ones to sort before tentative ones
170 bool leftIsTent = (left->definition() == ld::Atom::definitionTentative);
171 bool rightIsTent = (right->definition() == ld::Atom::definitionTentative);
172 if ( leftIsTent != rightIsTent )
173 return rightIsTent;
174
175 #if 0
176 // initializers are auto sorted to start of section
177 if ( !fInitializerSet.empty() ) {
178 bool leftFirst = (fInitializerSet.count(left) != 0);
179 bool rightFirst = (fInitializerSet.count(right) != 0);
180 if ( leftFirst != rightFirst )
181 return leftFirst;
182 }
183
184 // terminators are auto sorted to end of section
185 if ( !fTerminatorSet.empty() ) {
186 bool leftLast = (fTerminatorSet.count(left) != 0);
187 bool rightLast = (fTerminatorSet.count(right) != 0);
188 if ( leftLast != rightLast )
189 return rightLast;
190 }
191 #endif
192
193 // sort by .o order
194 uint32_t leftFileOrdinal = left->file()->ordinal();
195 uint32_t rightFileOrdinal = right->file()->ordinal();
196 if ( leftFileOrdinal != rightFileOrdinal )
197 return leftFileOrdinal< rightFileOrdinal;
198
199 // tentative defintions have no address in .o file, they are traditionally laid out by name
200 if ( leftIsTent && rightIsTent )
201 return (strcmp(left->name(), right->name()) < 0);
202
203 // lastly sort by atom address
204 int64_t addrDiff = left->objectAddress() - right->objectAddress();
205 if ( addrDiff == 0 ) {
206 // have same address so one might be an alias, and aliases need to sort before target
207 bool leftIsAlias = left->isAlias();
208 bool rightIsAlias = right->isAlias();
209 if ( leftIsAlias != rightIsAlias )
210 return leftIsAlias;
211
212 // both at same address, sort by name
213 return (strcmp(left->name(), right->name()) < 0);
214 }
215 return (addrDiff < 0);
216 }
217
218 bool Layout::matchesObjectFile(const ld::Atom* atom, const char* objectFileLeafName)
219 {
220 if ( objectFileLeafName == NULL )
221 return true;
222 const char* atomFullPath = atom->file()->path();
223 const char* lastSlash = strrchr(atomFullPath, '/');
224 if ( lastSlash != NULL ) {
225 if ( strcmp(&lastSlash[1], objectFileLeafName) == 0 )
226 return true;
227 }
228 else {
229 if ( strcmp(atomFullPath, objectFileLeafName) == 0 )
230 return true;
231 }
232 return false;
233 }
234
235
236 bool Layout::orderableSection(const ld::Internal::FinalSection* sect)
237 {
238 // atoms in only some sections are ordered
239 switch ( sect->type() ) {
240 case ld::Section::typeUnclassified:
241 case ld::Section::typeCode:
242 case ld::Section::typeZeroFill:
243 return true;
244 case ld::Section::typeImportProxies:
245 return false;
246 default:
247 // if section has command line aliases, then we must apply ordering so aliases layout before targets
248 if ( _options.haveCmdLineAliases() ) {
249 for (std::vector<const ld::Atom*>::const_iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
250 const ld::Atom* atom = *ait;
251 if ( atom->isAlias() )
252 return true;
253 }
254 }
255 break;
256 }
257 return false;
258 }
259
260 void Layout::buildNameTable()
261 {
262 for (std::vector<ld::Internal::FinalSection*>::iterator sit=_state.sections.begin(); sit != _state.sections.end(); ++sit) {
263 ld::Internal::FinalSection* sect = *sit;
264 // atoms in some special sections are never ordered
265 if ( ! orderableSection(sect) )
266 continue;
267 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
268 const ld::Atom* atom = *ait;
269 if ( atom->symbolTableInclusion() == ld::Atom::symbolTableIn ) {
270 const char* name = atom->name();
271 if ( name != NULL) {
272 // static function or data
273 NameToAtom::iterator pos = _nameTable.find(name);
274 if ( pos == _nameTable.end() )
275 _nameTable[name] = atom;
276 else {
277 _nameTable[name] = NULL; // collision, denote with NULL
278 _nameCollisionAtoms.push_back(atom);
279 }
280 }
281 }
282 }
283 }
284 }
285
286
287 const ld::Atom* Layout::findAtom(const Options::OrderedSymbol& orderedSymbol)
288 {
289 // look for name in _nameTable
290 NameToAtom::iterator pos = _nameTable.find(orderedSymbol.symbolName);
291 if ( pos != _nameTable.end() ) {
292 if ( (pos->second != NULL) && matchesObjectFile(pos->second, orderedSymbol.objectFileName) ) {
293 //fprintf(stderr, "found %s in hash table\n", orderedSymbol.symbolName);
294 return pos->second;
295 }
296 if ( pos->second == NULL ) {
297 // name is in hash table, but atom is NULL, so that means there are duplicates, so we use super slow way
298 for (std::vector<const ld::Atom*>::iterator it=_nameCollisionAtoms.begin(); it != _nameCollisionAtoms.end(); it++) {
299 const ld::Atom* atom = *it;
300 if ( strcmp(atom->name(), orderedSymbol.symbolName) == 0 ) {
301 if ( matchesObjectFile(atom, orderedSymbol.objectFileName) ) {
302 if ( _options.printOrderFileStatistics() )
303 warning("%s specified in order_file but it exists in multiple .o files. "
304 "Prefix symbol with .o filename in order_file to disambiguate", orderedSymbol.symbolName);
305 return atom;
306 }
307 }
308 }
309 }
310 }
311
312 return NULL;
313 }
314
315 const ld::Atom* Layout::follower(const ld::Atom* atom)
316 {
317 for (const ld::Atom* a = _followOnStarts[atom]; a != NULL; a = _followOnNexts[a]) {
318 assert(a != NULL);
319 if ( _followOnNexts[a] == atom ) {
320 return a;
321 }
322 }
323 // no follower, first in chain
324 return NULL;
325 }
326
327 void Layout::buildFollowOnTables()
328 {
329 // first make a pass to find all follow-on references and build start/next maps
330 // which are a way to represent clusters of atoms that must layout together
331 for (std::vector<ld::Internal::FinalSection*>::iterator sit=_state.sections.begin(); sit != _state.sections.end(); ++sit) {
332 ld::Internal::FinalSection* sect = *sit;
333 if ( !orderableSection(sect) )
334 continue;
335 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
336 const ld::Atom* atom = *ait;
337 for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) {
338 if ( fit->kind == ld::Fixup::kindNoneFollowOn ) {
339 assert(fit->binding == ld::Fixup::bindingDirectlyBound);
340 const ld::Atom* followOnAtom = fit->u.target;
341 if ( _s_log ) fprintf(stderr, "ref %p %s -> %p %s\n", atom, atom->name(), followOnAtom, followOnAtom->name());
342 assert(_followOnNexts.count(atom) == 0);
343 _followOnNexts[atom] = followOnAtom;
344 if ( _followOnStarts.count(atom) == 0 ) {
345 // first time atom has been seen, make it start of chain
346 _followOnStarts[atom] = atom;
347 if ( _s_log ) fprintf(stderr, " start %s -> %s\n", atom->name(), atom->name());
348 }
349 if ( _followOnStarts.count(followOnAtom) == 0 ) {
350 // first time followOnAtom has been seen, make atom start of chain
351 _followOnStarts[followOnAtom] = _followOnStarts[atom];
352 if ( _s_log ) fprintf(stderr, " start %s -> %s\n", followOnAtom->name(), _followOnStarts[atom]->name());
353 }
354 else {
355 if ( _followOnStarts[followOnAtom] == followOnAtom ) {
356 // followOnAtom atom already start of another chain, hook together
357 // and change all to use atom as start
358 const ld::Atom* a = followOnAtom;
359 while ( true ) {
360 assert(_followOnStarts[a] == followOnAtom);
361 _followOnStarts[a] = _followOnStarts[atom];
362 if ( _s_log ) fprintf(stderr, " adjust start for %s -> %s\n", a->name(), _followOnStarts[atom]->name());
363 AtomToAtom::iterator pos = _followOnNexts.find(a);
364 if ( pos != _followOnNexts.end() )
365 a = pos->second;
366 else
367 break;
368 }
369 }
370 else {
371 // attempt to insert atom into existing followOn chain
372 const ld::Atom* curPrevToFollowOnAtom = this->follower(followOnAtom);
373 assert(curPrevToFollowOnAtom != NULL);
374 assert((atom->size() == 0) || (curPrevToFollowOnAtom->size() == 0));
375 if ( atom->size() == 0 ) {
376 // insert alias into existing chain right before followOnAtom
377 _followOnNexts[curPrevToFollowOnAtom] = atom;
378 _followOnNexts[atom] = followOnAtom;
379 _followOnStarts[atom] = _followOnStarts[followOnAtom];
380 }
381 else {
382 // insert real atom into existing chain right before alias of followOnAtom
383 const ld::Atom* curPrevPrevToFollowOn = this->follower(curPrevToFollowOnAtom);
384 if ( curPrevPrevToFollowOn == NULL ) {
385 // nothing previous, so make this a start of a new chain
386 _followOnNexts[atom] = curPrevToFollowOnAtom;
387 for (const ld::Atom* a = atom; a != NULL; a = _followOnNexts[a]) {
388 if ( _s_log ) fprintf(stderr, " adjust start for %s -> %s\n", a->name(), atom->name());
389 _followOnStarts[a] = atom;
390 }
391 }
392 else {
393 // is previous, insert into existing chain before previous
394 _followOnNexts[curPrevPrevToFollowOn] = atom;
395 _followOnNexts[atom] = curPrevToFollowOnAtom;
396 _followOnStarts[atom] = _followOnStarts[curPrevToFollowOnAtom];
397 }
398 }
399 }
400 }
401 }
402 }
403 }
404 }
405
406 if ( _s_log ) {
407 for(AtomToAtom::iterator it = _followOnStarts.begin(); it != _followOnStarts.end(); ++it)
408 fprintf(stderr, "start %s -> %s\n", it->first->name(), it->second->name());
409
410 for(AtomToAtom::iterator it = _followOnNexts.begin(); it != _followOnNexts.end(); ++it)
411 fprintf(stderr, "next %s -> %s\n", it->first->name(), (it->second != NULL) ? it->second->name() : "null");
412 }
413 }
414
415 void Layout::buildOrdinalOverrideMap()
416 {
417 // if no -order_file, then skip building override map
418 if ( ! _haveOrderFile )
419 return;
420
421 // build fast name->atom table
422 this->buildNameTable();
423
424 // handle .o files that cannot have their atoms rearranged
425 // with the start/next maps of follow-on atoms we can process the order file and produce override ordinals
426 uint32_t index = 0;
427 uint32_t matchCount = 0;
428 for(Options::OrderedSymbolsIterator it = _options.orderedSymbolsBegin(); it != _options.orderedSymbolsEnd(); ++it) {
429 const ld::Atom* atom = this->findAtom(*it);
430 if ( atom != NULL ) {
431 AtomToAtom::iterator start = _followOnStarts.find(atom);
432 if ( start != _followOnStarts.end() ) {
433 // this symbol for the order file corresponds to an atom that is in a cluster that must lay out together
434 for(const ld::Atom* nextAtom = start->second; nextAtom != NULL; nextAtom = _followOnNexts[nextAtom]) {
435 AtomToOrdinal::iterator pos = _ordinalOverrideMap.find(nextAtom);
436 if ( pos == _ordinalOverrideMap.end() ) {
437 _ordinalOverrideMap[nextAtom] = index++;
438 if (_s_log ) fprintf(stderr, "override ordinal %u assigned to %s in cluster from %s\n", index, nextAtom->name(), nextAtom->file()->path());
439 }
440 else {
441 if (_s_log ) fprintf(stderr, "could not order %s as %u because it was already laid out earlier by %s as %u\n",
442 atom->name(), index, _followOnStarts[atom]->name(), _ordinalOverrideMap[atom] );
443 }
444 }
445 }
446 else {
447 _ordinalOverrideMap[atom] = index;
448 if (_s_log ) fprintf(stderr, "override ordinal %u assigned to %s from %s\n", index, atom->name(), atom->file()->path());
449 }
450 ++matchCount;
451 }
452 else {
453 if ( _options.printOrderFileStatistics() ) {
454 if ( it->objectFileName == NULL )
455 warning("can't find match for order_file entry: %s", it->symbolName);
456 else
457 warning("can't find match for order_file entry: %s/%s", it->objectFileName, it->symbolName);
458 }
459 }
460 ++index;
461 }
462 if ( _options.printOrderFileStatistics() && (_options.orderedSymbolsCount() != matchCount) ) {
463 warning("only %u out of %lu order_file symbols were applicable", matchCount, _options.orderedSymbolsCount() );
464 }
465
466
467 }
468
469 void Layout::doPass()
470 {
471 // handle .o files that cannot have their atoms rearranged
472 this->buildFollowOnTables();
473
474 //
475 this->buildOrdinalOverrideMap();
476
477
478 // sort atoms in each section
479 for (std::vector<ld::Internal::FinalSection*>::iterator sit=_state.sections.begin(); sit != _state.sections.end(); ++sit) {
480 ld::Internal::FinalSection* sect = *sit;
481 if ( orderableSection(sect) ) {
482 std::sort(sect->atoms.begin(), sect->atoms.end(), _comparer);
483 }
484 else {
485 // bubble sort any typeSectionStart atom to the beginning
486 bool moving = false;
487 for (int i=sect->atoms.size()-1; i >= 0; --i) {
488 if ( moving ) {
489 const ld::Atom* temp = sect->atoms[i];
490 sect->atoms[i] = sect->atoms[i+1];
491 sect->atoms[i+1] = temp;
492 }
493 if ( sect->atoms[i]->contentType() == ld::Atom::typeSectionStart )
494 moving = true;
495 }
496 // bubble sort any typeSectionEnd atom to the end
497 moving = false;
498 for (unsigned int i=sect->atoms.size(); i < sect->atoms.size(); ++i) {
499 if ( moving ) {
500 const ld::Atom* temp = sect->atoms[i];
501 sect->atoms[i] = sect->atoms[i-1];
502 sect->atoms[i-1] = temp;
503 }
504 if ( sect->atoms[i]->contentType() == ld::Atom::typeSectionEnd )
505 moving = true;
506 }
507 }
508 }
509
510 //fprintf(stderr, "Sorted atoms:\n");
511 //for (std::vector<ld::Internal::FinalSection*>::iterator sit=_state.sections.begin(); sit != _state.sections.end(); ++sit) {
512 // ld::Internal::FinalSection* sect = *sit;
513 // for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
514 // const ld::Atom* atom = *ait;
515 // fprintf(stderr, "\t%s\t%s\n", sect->sectionName(), atom->name());
516 // }
517 //}
518
519 }
520
521
522 void doPass(const Options& opts, ld::Internal& state)
523 {
524 Layout layout(opts, state);
525 layout.doPass();
526 }
527
528
529 } // namespace order_file
530 } // namespace passes
531 } // namespace ld