1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2009 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
30 #include <mach/machine.h>
36 #include "order_file.h"
40 namespace order_file
{
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).
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.
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.
73 Layout(const Options
& opts
, ld::Internal
& state
);
79 Comparer(const Layout
& l
) : _layout(l
) {}
80 bool operator()(const ld::Atom
* left
, const ld::Atom
* right
);
82 const Layout
& _layout
;
87 bool operator()(const char* left
, const char* right
) const { return (strcmp(left
, right
) == 0); }
89 typedef __gnu_cxx::hash_map
<const char*, const ld::Atom
*, __gnu_cxx::hash
<const char*>, CStringEquals
> NameToAtom
;
91 typedef std::map
<const ld::Atom
*, const ld::Atom
*> AtomToAtom
;
93 typedef std::map
<const ld::Atom
*, uint32_t> AtomToOrdinal
;
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
*);
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
;
116 bool Layout::_s_log
= false;
118 Layout::Layout(const Options
& opts
, ld::Internal
& state
)
119 : _options(opts
), _state(state
), _comparer(*this), _haveOrderFile(opts
.orderedSymbolsCount() != 0)
124 bool Layout::Comparer::operator()(const ld::Atom
* left
, const ld::Atom
* right
)
129 // magic section$start symbol always sorts to the start of its section
130 if ( left
->contentType() == ld::Atom::typeSectionStart
)
132 if ( right
->contentType() == ld::Atom::typeSectionStart
)
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
;
146 // left is overridden and right is not, so left < right
151 if ( rightPos
!= end
) {
152 // right is overridden and left is not, so right < left
156 // neither are overridden,
157 // fall into default sorting below
162 // magic section$end symbol always sorts to the end of its section
163 if ( left
->contentType() == ld::Atom::typeSectionEnd
)
165 if ( right
->contentType() == ld::Atom::typeSectionEnd
)
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
)
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
)
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
)
194 uint32_t leftFileOrdinal
= left
->file()->ordinal();
195 uint32_t rightFileOrdinal
= right
->file()->ordinal();
196 if ( leftFileOrdinal
!= rightFileOrdinal
)
197 return leftFileOrdinal
< rightFileOrdinal
;
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);
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
)
212 // both at same address, sort by name
213 return (strcmp(left
->name(), right
->name()) < 0);
215 return (addrDiff
< 0);
218 bool Layout::matchesObjectFile(const ld::Atom
* atom
, const char* objectFileLeafName
)
220 if ( objectFileLeafName
== NULL
)
222 const char* atomFullPath
= atom
->file()->path();
223 const char* lastSlash
= strrchr(atomFullPath
, '/');
224 if ( lastSlash
!= NULL
) {
225 if ( strcmp(&lastSlash
[1], objectFileLeafName
) == 0 )
229 if ( strcmp(atomFullPath
, objectFileLeafName
) == 0 )
236 bool Layout::orderableSection(const ld::Internal::FinalSection
* sect
)
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
:
244 case ld::Section::typeImportProxies
:
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() )
260 void Layout::buildNameTable()
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
) )
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();
272 // static function or data
273 NameToAtom::iterator pos
= _nameTable
.find(name
);
274 if ( pos
== _nameTable
.end() )
275 _nameTable
[name
] = atom
;
277 _nameTable
[name
] = NULL
; // collision, denote with NULL
278 _nameCollisionAtoms
.push_back(atom
);
287 const ld::Atom
* Layout::findAtom(const Options::OrderedSymbol
& orderedSymbol
)
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);
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
);
315 const ld::Atom
* Layout::follower(const ld::Atom
* atom
)
317 for (const ld::Atom
* a
= _followOnStarts
[atom
]; a
!= NULL
; a
= _followOnNexts
[a
]) {
319 if ( _followOnNexts
[a
] == atom
) {
323 // no follower, first in chain
327 void Layout::buildFollowOnTables()
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
) )
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());
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());
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
;
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() )
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
];
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
;
393 // is previous, insert into existing chain before previous
394 _followOnNexts
[curPrevPrevToFollowOn
] = atom
;
395 _followOnNexts
[atom
] = curPrevToFollowOnAtom
;
396 _followOnStarts
[atom
] = _followOnStarts
[curPrevToFollowOnAtom
];
407 for(AtomToAtom::iterator it
= _followOnStarts
.begin(); it
!= _followOnStarts
.end(); ++it
)
408 fprintf(stderr
, "start %s -> %s\n", it
->first
->name(), it
->second
->name());
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");
415 void Layout::buildOrdinalOverrideMap()
417 // if no -order_file, then skip building override map
418 if ( ! _haveOrderFile
)
421 // build fast name->atom table
422 this->buildNameTable();
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
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());
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
] );
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());
453 if ( _options
.printOrderFileStatistics() ) {
454 if ( it
->objectFileName
== NULL
)
455 warning("can't find match for order_file entry: %s", it
->symbolName
);
457 warning("can't find match for order_file entry: %s/%s", it
->objectFileName
, it
->symbolName
);
462 if ( _options
.printOrderFileStatistics() && (_options
.orderedSymbolsCount() != matchCount
) ) {
463 warning("only %u out of %lu order_file symbols were applicable", matchCount
, _options
.orderedSymbolsCount() );
469 void Layout::doPass()
471 // handle .o files that cannot have their atoms rearranged
472 this->buildFollowOnTables();
475 this->buildOrdinalOverrideMap();
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
);
485 // bubble sort any typeSectionStart atom to the beginning
487 for (int i
=sect
->atoms
.size()-1; i
>= 0; --i
) {
489 const ld::Atom
* temp
= sect
->atoms
[i
];
490 sect
->atoms
[i
] = sect
->atoms
[i
+1];
491 sect
->atoms
[i
+1] = temp
;
493 if ( sect
->atoms
[i
]->contentType() == ld::Atom::typeSectionStart
)
496 // bubble sort any typeSectionEnd atom to the end
498 for (unsigned int i
=sect
->atoms
.size(); i
< sect
->atoms
.size(); ++i
) {
500 const ld::Atom
* temp
= sect
->atoms
[i
];
501 sect
->atoms
[i
] = sect
->atoms
[i
-1];
502 sect
->atoms
[i
-1] = temp
;
504 if ( sect
->atoms
[i
]->contentType() == ld::Atom::typeSectionEnd
)
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());
522 void doPass(const Options
& opts
, ld::Internal
& state
)
524 Layout
layout(opts
, state
);
529 } // namespace order_file
530 } // namespace passes