1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-*
3 * Copyright (c) 2009-2010 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@
25 #ifndef __LINKEDIT_HPP__
26 #define __LINKEDIT_HPP__
29 #include <sys/types.h>
38 #include "Architectures.hpp"
39 #include "MachOFileAbstraction.hpp"
40 #include "code-sign-blobs/superblob.h"
47 std::vector<uint8_t> _data;
49 std::vector<uint8_t>& bytes() { return _data; }
50 unsigned long size() const { return _data.size(); }
51 void reserve(unsigned long l) { _data.reserve(l); }
52 const uint8_t* start() const { return &_data[0]; }
54 void append_uleb128(uint64_t value) {
61 _data.push_back(byte);
63 } while( byte >= 0x80 );
66 void append_sleb128(int64_t value) {
67 bool isNeg = ( value < 0 );
74 more = ( (value != -1) || ((byte & 0x40) == 0) );
76 more = ( (value != 0) || ((byte & 0x40) != 0) );
79 _data.push_back(byte);
84 void append_string(const char* str) {
85 for (const char* s = str; *s != '\0'; ++s)
87 _data.push_back('\0');
90 void append_byte(uint8_t byte) {
91 _data.push_back(byte);
94 static unsigned int uleb128_size(uint64_t value) {
99 } while ( value != 0 );
103 void pad_to_size(unsigned int alignment) {
104 while ( (_data.size() % alignment) != 0 )
110 class LinkEditAtom : public ld::Atom
114 // overrides of ld::Atom
115 virtual ld::File* file() const { return NULL; }
116 virtual uint64_t objectAddress() const { return 0; }
117 virtual uint64_t size() const;
118 virtual void copyRawContent(uint8_t buffer[]) const;
120 virtual void encode() const = 0;
122 LinkEditAtom(const Options& opts, ld::Internal& state,
123 OutputFile& writer, const ld::Section& sect,
124 unsigned int pointerSize)
125 : ld::Atom(sect, ld::Atom::definitionRegular,
126 ld::Atom::combineNever, ld::Atom::scopeTranslationUnit,
127 ld::Atom::typeUnclassified, ld::Atom::symbolTableNotIn,
128 false, false, false, ld::Atom::Alignment(log2(pointerSize))),
129 _options(opts), _state(state), _writer(writer),
132 const Options& _options;
133 ld::Internal& _state;
135 mutable ByteStream _encodedData;
136 mutable bool _encoded;
139 uint64_t LinkEditAtom::size() const
142 return _encodedData.size();
145 void LinkEditAtom::copyRawContent(uint8_t buffer[]) const
148 memcpy(buffer, _encodedData.start(), _encodedData.size());
154 template <typename A>
155 class RebaseInfoAtom : public LinkEditAtom
158 RebaseInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
159 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { _encoded = true; }
161 // overrides of ld::Atom
162 virtual const char* name() const { return "rebase info"; }
163 // overrides of LinkEditAtom
164 virtual void encode() const;
169 rebase_tmp(uint8_t op, uint64_t p1, uint64_t p2=0) : opcode(op), operand1(p1), operand2(p2) {}
175 typedef typename A::P P;
176 typedef typename A::P::E E;
177 typedef typename A::P::uint_t pint_t;
179 static ld::Section _s_section;
182 template <typename A>
183 ld::Section RebaseInfoAtom<A>::_s_section("__LINKEDIT", "__rebase", ld::Section::typeLinkEdit, true);
186 template <typename A>
187 void RebaseInfoAtom<A>::encode() const
189 // omit relocs if this was supposed to be PIE but PIE not possible
190 if ( _options.positionIndependentExecutable() && this->_writer.pieDisabled )
193 // sort rebase info by type, then address
194 std::vector<OutputFile::RebaseInfo>& info = this->_writer._rebaseInfo;
195 std::sort(info.begin(), info.end());
197 // convert to temp encoding that can be more easily optimized
198 std::vector<rebase_tmp> mid;
199 uint64_t curSegStart = 0;
200 uint64_t curSegEnd = 0;
201 uint32_t curSegIndex = 0;
203 uint64_t address = (uint64_t)(-1);
204 for (std::vector<OutputFile::RebaseInfo>::iterator it = info.begin(); it != info.end(); ++it) {
205 if ( type != it->_type ) {
206 mid.push_back(rebase_tmp(REBASE_OPCODE_SET_TYPE_IMM, it->_type));
209 if ( address != it->_address ) {
210 if ( (it->_address < curSegStart) || ( it->_address >= curSegEnd) ) {
211 if ( ! this->_writer.findSegment(this->_state, it->_address, &curSegStart, &curSegEnd, &curSegIndex) )
212 throw "binding address outside range of any segment";
213 mid.push_back(rebase_tmp(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, curSegIndex, it->_address - curSegStart));
216 mid.push_back(rebase_tmp(REBASE_OPCODE_ADD_ADDR_ULEB, it->_address-address));
218 address = it->_address;
220 mid.push_back(rebase_tmp(REBASE_OPCODE_DO_REBASE_ULEB_TIMES, 1));
221 address += sizeof(pint_t);
223 mid.push_back(rebase_tmp(REBASE_OPCODE_DONE, 0));
225 // optimize phase 1, compress packed runs of pointers
226 rebase_tmp* dst = &mid[0];
227 for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) {
228 if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES) && (src->operand1 == 1) ) {
230 while (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES ) {
231 dst->operand1 += src->operand1;
241 dst->opcode = REBASE_OPCODE_DONE;
243 // optimize phase 2, combine rebase/add pairs
245 for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) {
246 if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES)
247 && (src->operand1 == 1)
248 && (src[1].opcode == REBASE_OPCODE_ADD_ADDR_ULEB)) {
249 dst->opcode = REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB;
250 dst->operand1 = src[1].operand1;
258 dst->opcode = REBASE_OPCODE_DONE;
260 // optimize phase 3, compress packed runs of REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB with
261 // same addr delta into one REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB
263 for (const rebase_tmp* src = &mid[0]; src->opcode != REBASE_OPCODE_DONE; ++src) {
264 uint64_t delta = src->operand1;
265 if ( (src->opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB)
266 && (src[1].opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB)
267 && (src[2].opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB)
268 && (src[1].operand1 == delta)
269 && (src[2].operand1 == delta) ) {
270 // found at least three in a row, this is worth compressing
271 dst->opcode = REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB;
273 dst->operand2 = delta;
275 while ( (src->opcode == REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB)
276 && (src->operand1 == delta) ) {
287 dst->opcode = REBASE_OPCODE_DONE;
289 // optimize phase 4, use immediate encodings
290 for (rebase_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) {
291 if ( (p->opcode == REBASE_OPCODE_ADD_ADDR_ULEB)
292 && (p->operand1 < (15*sizeof(pint_t)))
293 && ((p->operand1 % sizeof(pint_t)) == 0) ) {
294 p->opcode = REBASE_OPCODE_ADD_ADDR_IMM_SCALED;
295 p->operand1 = p->operand1/sizeof(pint_t);
297 else if ( (p->opcode == REBASE_OPCODE_DO_REBASE_ULEB_TIMES) && (p->operand1 < 15) ) {
298 p->opcode = REBASE_OPCODE_DO_REBASE_IMM_TIMES;
302 // convert to compressed encoding
303 const static bool log = false;
304 this->_encodedData.reserve(info.size()*2);
306 for (typename std::vector<rebase_tmp>::iterator it = mid.begin(); !done && it != mid.end() ; ++it) {
307 switch ( it->opcode ) {
308 case REBASE_OPCODE_DONE:
309 if ( log ) fprintf(stderr, "REBASE_OPCODE_DONE()\n");
312 case REBASE_OPCODE_SET_TYPE_IMM:
313 if ( log ) fprintf(stderr, "REBASE_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1);
314 this->_encodedData.append_byte(REBASE_OPCODE_SET_TYPE_IMM | it->operand1);
316 case REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
317 if ( log ) fprintf(stderr, "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2);
318 this->_encodedData.append_byte(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1);
319 this->_encodedData.append_uleb128(it->operand2);
321 case REBASE_OPCODE_ADD_ADDR_ULEB:
322 if ( log ) fprintf(stderr, "REBASE_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
323 this->_encodedData.append_byte(REBASE_OPCODE_ADD_ADDR_ULEB);
324 this->_encodedData.append_uleb128(it->operand1);
326 case REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
327 if ( log ) fprintf(stderr, "REBASE_OPCODE_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t));
328 this->_encodedData.append_byte(REBASE_OPCODE_ADD_ADDR_IMM_SCALED | it->operand1 );
330 case REBASE_OPCODE_DO_REBASE_IMM_TIMES:
331 if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_IMM_TIMES(%lld)\n", it->operand1);
332 this->_encodedData.append_byte(REBASE_OPCODE_DO_REBASE_IMM_TIMES | it->operand1);
334 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
335 if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ULEB_TIMES(%lld)\n", it->operand1);
336 this->_encodedData.append_byte(REBASE_OPCODE_DO_REBASE_ULEB_TIMES);
337 this->_encodedData.append_uleb128(it->operand1);
339 case REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
340 if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
341 this->_encodedData.append_byte(REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB);
342 this->_encodedData.append_uleb128(it->operand1);
344 case REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
345 if ( log ) fprintf(stderr, "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2);
346 this->_encodedData.append_byte(REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB);
347 this->_encodedData.append_uleb128(it->operand1);
348 this->_encodedData.append_uleb128(it->operand2);
354 // align to pointer size
355 this->_encodedData.pad_to_size(sizeof(pint_t));
357 this->_encoded = true;
359 if (log) fprintf(stderr, "total rebase info size = %ld\n", this->_encodedData.size());
363 template <typename A>
364 class BindingInfoAtom : public LinkEditAtom
367 BindingInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
368 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { }
370 // overrides of ld::Atom
371 virtual const char* name() const { return "binding info"; }
372 // overrides of LinkEditAtom
373 virtual void encode() const;
377 typedef typename A::P P;
378 typedef typename A::P::E E;
379 typedef typename A::P::uint_t pint_t;
383 binding_tmp(uint8_t op, uint64_t p1, uint64_t p2=0, const char* s=NULL)
384 : opcode(op), operand1(p1), operand2(p2), name(s) {}
391 static ld::Section _s_section;
394 template <typename A>
395 ld::Section BindingInfoAtom<A>::_s_section("__LINKEDIT", "__binding", ld::Section::typeLinkEdit, true);
398 template <typename A>
399 void BindingInfoAtom<A>::encode() const
401 // sort by library, symbol, type, then address
402 std::vector<OutputFile::BindingInfo>& info = this->_writer._bindingInfo;
403 std::sort(info.begin(), info.end());
405 // convert to temp encoding that can be more easily optimized
406 std::vector<binding_tmp> mid;
407 uint64_t curSegStart = 0;
408 uint64_t curSegEnd = 0;
409 uint32_t curSegIndex = 0;
410 int ordinal = 0x80000000;
411 const char* symbolName = NULL;
413 uint64_t address = (uint64_t)(-1);
415 for (std::vector<OutputFile::BindingInfo>::const_iterator it = info.begin(); it != info.end(); ++it) {
416 if ( ordinal != it->_libraryOrdinal ) {
417 if ( it->_libraryOrdinal <= 0 ) {
418 // special lookups are encoded as negative numbers in BindingInfo
419 mid.push_back(binding_tmp(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM, it->_libraryOrdinal));
422 mid.push_back(binding_tmp(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB, it->_libraryOrdinal));
424 ordinal = it->_libraryOrdinal;
426 if ( symbolName != it->_symbolName ) {
427 mid.push_back(binding_tmp(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, it->_flags, 0, it->_symbolName));
428 symbolName = it->_symbolName;
430 if ( type != it->_type ) {
431 mid.push_back(binding_tmp(BIND_OPCODE_SET_TYPE_IMM, it->_type));
434 if ( address != it->_address ) {
435 if ( (it->_address < curSegStart) || ( it->_address >= curSegEnd) ) {
436 if ( ! this->_writer.findSegment(this->_state, it->_address, &curSegStart, &curSegEnd, &curSegIndex) )
437 throw "binding address outside range of any segment";
438 mid.push_back(binding_tmp(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, curSegIndex, it->_address - curSegStart));
441 mid.push_back(binding_tmp(BIND_OPCODE_ADD_ADDR_ULEB, it->_address-address));
443 address = it->_address;
445 if ( addend != it->_addend ) {
446 mid.push_back(binding_tmp(BIND_OPCODE_SET_ADDEND_SLEB, it->_addend));
447 addend = it->_addend;
449 mid.push_back(binding_tmp(BIND_OPCODE_DO_BIND, 0));
450 address += sizeof(pint_t);
452 mid.push_back(binding_tmp(BIND_OPCODE_DONE, 0));
455 // optimize phase 1, combine bind/add pairs
456 binding_tmp* dst = &mid[0];
457 for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) {
458 if ( (src->opcode == BIND_OPCODE_DO_BIND)
459 && (src[1].opcode == BIND_OPCODE_ADD_ADDR_ULEB) ) {
460 dst->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB;
461 dst->operand1 = src[1].operand1;
469 dst->opcode = BIND_OPCODE_DONE;
471 // optimize phase 2, compress packed runs of BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB with
472 // same addr delta into one BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
474 for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) {
475 uint64_t delta = src->operand1;
476 if ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
477 && (src[1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
478 && (src[1].operand1 == delta) ) {
479 // found at least two in a row, this is worth compressing
480 dst->opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB;
482 dst->operand2 = delta;
484 while ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
485 && (src->operand1 == delta) ) {
496 dst->opcode = BIND_OPCODE_DONE;
498 // optimize phase 3, use immediate encodings
499 for (binding_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) {
500 if ( (p->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
501 && (p->operand1 < (15*sizeof(pint_t)))
502 && ((p->operand1 % sizeof(pint_t)) == 0) ) {
503 p->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED;
504 p->operand1 = p->operand1/sizeof(pint_t);
506 else if ( (p->opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB) && (p->operand1 <= 15) ) {
507 p->opcode = BIND_OPCODE_SET_DYLIB_ORDINAL_IMM;
510 dst->opcode = BIND_OPCODE_DONE;
512 // convert to compressed encoding
513 const static bool log = false;
514 this->_encodedData.reserve(info.size()*2);
516 for (typename std::vector<binding_tmp>::iterator it = mid.begin(); !done && it != mid.end() ; ++it) {
517 switch ( it->opcode ) {
518 case BIND_OPCODE_DONE:
519 if ( log ) fprintf(stderr, "BIND_OPCODE_DONE()\n");
522 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
523 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%lld)\n", it->operand1);
524 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | it->operand1);
526 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
527 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%lld)\n", it->operand1);
528 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
529 this->_encodedData.append_uleb128(it->operand1);
531 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
532 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%lld)\n", it->operand1);
533 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (it->operand1 & BIND_IMMEDIATE_MASK));
535 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
536 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%0llX, %s)\n", it->operand1, it->name);
537 this->_encodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | it->operand1);
538 this->_encodedData.append_string(it->name);
540 case BIND_OPCODE_SET_TYPE_IMM:
541 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1);
542 this->_encodedData.append_byte(BIND_OPCODE_SET_TYPE_IMM | it->operand1);
544 case BIND_OPCODE_SET_ADDEND_SLEB:
545 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", it->operand1);
546 this->_encodedData.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
547 this->_encodedData.append_sleb128(it->operand1);
549 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
550 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2);
551 this->_encodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1);
552 this->_encodedData.append_uleb128(it->operand2);
554 case BIND_OPCODE_ADD_ADDR_ULEB:
555 if ( log ) fprintf(stderr, "BIND_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
556 this->_encodedData.append_byte(BIND_OPCODE_ADD_ADDR_ULEB);
557 this->_encodedData.append_uleb128(it->operand1);
559 case BIND_OPCODE_DO_BIND:
560 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND()\n");
561 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND);
563 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
564 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
565 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB);
566 this->_encodedData.append_uleb128(it->operand1);
568 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
569 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t));
570 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED | it->operand1 );
572 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
573 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2);
574 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB);
575 this->_encodedData.append_uleb128(it->operand1);
576 this->_encodedData.append_uleb128(it->operand2);
581 // align to pointer size
582 this->_encodedData.pad_to_size(sizeof(pint_t));
584 this->_encoded = true;
586 if (log) fprintf(stderr, "total binding info size = %ld\n", this->_encodedData.size());
591 template <typename A>
592 class WeakBindingInfoAtom : public LinkEditAtom
595 WeakBindingInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
596 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { _encoded = true; }
598 // overrides of ld::Atom
599 virtual const char* name() const { return "weak binding info"; }
600 // overrides of LinkEditAtom
601 virtual void encode() const;
604 typedef typename A::P P;
605 typedef typename A::P::E E;
606 typedef typename A::P::uint_t pint_t;
608 struct WeakBindingSorter
610 bool operator()(const OutputFile::BindingInfo& left, const OutputFile::BindingInfo& right)
612 // sort by symbol, type, address
613 if ( left._symbolName != right._symbolName )
614 return ( strcmp(left._symbolName, right._symbolName) < 0 );
615 if ( left._type != right._type )
616 return (left._type < right._type);
617 return (left._address < right._address);
623 binding_tmp(uint8_t op, uint64_t p1, uint64_t p2=0, const char* s=NULL)
624 : opcode(op), operand1(p1), operand2(p2), name(s) {}
631 static ld::Section _s_section;
634 template <typename A>
635 ld::Section WeakBindingInfoAtom<A>::_s_section("__LINKEDIT", "__weak_binding", ld::Section::typeLinkEdit, true);
638 template <typename A>
639 void WeakBindingInfoAtom<A>::encode() const
641 // sort by symbol, type, address
642 std::vector<OutputFile::BindingInfo>& info = this->_writer._weakBindingInfo;
643 if ( info.size() == 0 ) {
644 // short circuit if no weak binding needed
645 this->_encoded = true;
648 std::sort(info.begin(), info.end(), WeakBindingSorter());
650 // convert to temp encoding that can be more easily optimized
651 std::vector<binding_tmp> mid;
652 mid.reserve(info.size());
653 uint64_t curSegStart = 0;
654 uint64_t curSegEnd = 0;
655 uint32_t curSegIndex = 0;
656 const char* symbolName = NULL;
658 uint64_t address = (uint64_t)(-1);
660 for (typename std::vector<OutputFile::BindingInfo>::const_iterator it = info.begin(); it != info.end(); ++it) {
661 if ( symbolName != it->_symbolName ) {
662 mid.push_back(binding_tmp(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, it->_flags, 0, it->_symbolName));
663 symbolName = it->_symbolName;
665 // non-weak symbols just have BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM
666 // weak symbols have SET_SEG, ADD_ADDR, SET_ADDED, DO_BIND
667 if ( it->_type != BIND_TYPE_OVERRIDE_OF_WEAKDEF_IN_DYLIB ) {
668 if ( type != it->_type ) {
669 mid.push_back(binding_tmp(BIND_OPCODE_SET_TYPE_IMM, it->_type));
672 if ( address != it->_address ) {
673 if ( (it->_address < curSegStart) || ( it->_address >= curSegEnd) ) {
674 if ( ! this->_writer.findSegment(this->_state, it->_address, &curSegStart, &curSegEnd, &curSegIndex) )
675 throw "binding address outside range of any segment";
676 mid.push_back(binding_tmp(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, curSegIndex, it->_address - curSegStart));
679 mid.push_back(binding_tmp(BIND_OPCODE_ADD_ADDR_ULEB, it->_address-address));
681 address = it->_address;
683 if ( addend != it->_addend ) {
684 mid.push_back(binding_tmp(BIND_OPCODE_SET_ADDEND_SLEB, it->_addend));
685 addend = it->_addend;
687 mid.push_back(binding_tmp(BIND_OPCODE_DO_BIND, 0));
688 address += sizeof(pint_t);
691 mid.push_back(binding_tmp(BIND_OPCODE_DONE, 0));
694 // optimize phase 1, combine bind/add pairs
695 binding_tmp* dst = &mid[0];
696 for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) {
697 if ( (src->opcode == BIND_OPCODE_DO_BIND)
698 && (src[1].opcode == BIND_OPCODE_ADD_ADDR_ULEB) ) {
699 dst->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB;
700 dst->operand1 = src[1].operand1;
708 dst->opcode = BIND_OPCODE_DONE;
710 // optimize phase 2, compress packed runs of BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB with
711 // same addr delta into one BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB
713 for (const binding_tmp* src = &mid[0]; src->opcode != BIND_OPCODE_DONE; ++src) {
714 uint64_t delta = src->operand1;
715 if ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
716 && (src[1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
717 && (src[1].operand1 == delta) ) {
718 // found at least two in a row, this is worth compressing
719 dst->opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB;
721 dst->operand2 = delta;
723 while ( (src->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
724 && (src->operand1 == delta) ) {
735 dst->opcode = BIND_OPCODE_DONE;
737 // optimize phase 3, use immediate encodings
738 for (binding_tmp* p = &mid[0]; p->opcode != REBASE_OPCODE_DONE; ++p) {
739 if ( (p->opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB)
740 && (p->operand1 < (15*sizeof(pint_t)))
741 && ((p->operand1 % sizeof(pint_t)) == 0) ) {
742 p->opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED;
743 p->operand1 = p->operand1/sizeof(pint_t);
746 dst->opcode = BIND_OPCODE_DONE;
749 // convert to compressed encoding
750 const static bool log = false;
751 this->_encodedData.reserve(info.size()*2);
753 for (typename std::vector<binding_tmp>::iterator it = mid.begin(); !done && it != mid.end() ; ++it) {
754 switch ( it->opcode ) {
755 case BIND_OPCODE_DONE:
756 if ( log ) fprintf(stderr, "BIND_OPCODE_DONE()\n");
757 this->_encodedData.append_byte(BIND_OPCODE_DONE);
760 case BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
761 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM(%lld)\n", it->operand1);
762 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | it->operand1);
764 case BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
765 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB(%lld)\n", it->operand1);
766 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
767 this->_encodedData.append_uleb128(it->operand1);
769 case BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
770 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM(%lld)\n", it->operand1);
771 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (it->operand1 & BIND_IMMEDIATE_MASK));
773 case BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
774 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM(0x%0llX, %s)\n", it->operand1, it->name);
775 this->_encodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | it->operand1);
776 this->_encodedData.append_string(it->name);
778 case BIND_OPCODE_SET_TYPE_IMM:
779 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_TYPE_IMM(%lld)\n", it->operand1);
780 this->_encodedData.append_byte(BIND_OPCODE_SET_TYPE_IMM | it->operand1);
782 case BIND_OPCODE_SET_ADDEND_SLEB:
783 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_ADDEND_SLEB(%lld)\n", it->operand1);
784 this->_encodedData.append_byte(BIND_OPCODE_SET_ADDEND_SLEB);
785 this->_encodedData.append_sleb128(it->operand1);
787 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
788 if ( log ) fprintf(stderr, "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB(%lld, 0x%llX)\n", it->operand1, it->operand2);
789 this->_encodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | it->operand1);
790 this->_encodedData.append_uleb128(it->operand2);
792 case BIND_OPCODE_ADD_ADDR_ULEB:
793 if ( log ) fprintf(stderr, "BIND_OPCODE_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
794 this->_encodedData.append_byte(BIND_OPCODE_ADD_ADDR_ULEB);
795 this->_encodedData.append_uleb128(it->operand1);
797 case BIND_OPCODE_DO_BIND:
798 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND()\n");
799 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND);
801 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
802 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB(0x%llX)\n", it->operand1);
803 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB);
804 this->_encodedData.append_uleb128(it->operand1);
806 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
807 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED(%lld=0x%llX)\n", it->operand1, it->operand1*sizeof(pint_t));
808 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED | it->operand1 );
810 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
811 if ( log ) fprintf(stderr, "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB(%lld, %lld)\n", it->operand1, it->operand2);
812 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB);
813 this->_encodedData.append_uleb128(it->operand1);
814 this->_encodedData.append_uleb128(it->operand2);
819 // align to pointer size
820 this->_encodedData.pad_to_size(sizeof(pint_t));
822 this->_encoded = true;
824 if (log) fprintf(stderr, "total weak binding info size = %ld\n", this->_encodedData.size());
830 template <typename A>
831 class LazyBindingInfoAtom : public LinkEditAtom
834 LazyBindingInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
835 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) {_encoded = true; }
837 // overrides of ld::Atom
838 virtual const char* name() const { return "lazy binding info"; }
839 // overrides of LinkEditAtom
840 virtual void encode() const;
843 typedef typename A::P P;
844 typedef typename A::P::E E;
845 typedef typename A::P::uint_t pint_t;
847 static ld::Section _s_section;
850 template <typename A>
851 ld::Section LazyBindingInfoAtom<A>::_s_section("__LINKEDIT", "__lazy_binding", ld::Section::typeLinkEdit, true);
855 template <typename A>
856 void LazyBindingInfoAtom<A>::encode() const
858 // stream all lazy bindings and record start offsets
859 std::vector<OutputFile::BindingInfo>& info = this->_writer._lazyBindingInfo;
860 for (std::vector<OutputFile::BindingInfo>::const_iterator it = info.begin(); it != info.end(); ++it) {
861 // record start offset for use by stub helper
862 this->_writer.setLazyBindingInfoOffset(it->_address, this->_encodedData.size());
864 // write address to bind
865 uint64_t segStart = 0;
867 uint32_t segIndex = 0;
868 if ( ! this->_writer.findSegment(this->_state, it->_address, &segStart, &segEnd, &segIndex) )
869 throw "lazy binding address outside range of any segment";
870 this->_encodedData.append_byte(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | segIndex);
871 this->_encodedData.append_uleb128(it->_address - segStart);
874 if ( it->_libraryOrdinal <= 0 ) {
875 // special lookups are encoded as negative numbers in BindingInfo
876 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | (it->_libraryOrdinal & BIND_IMMEDIATE_MASK) );
878 else if ( it->_libraryOrdinal <= 15 ) {
879 // small ordinals are encoded in opcode
880 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | it->_libraryOrdinal);
883 this->_encodedData.append_byte(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB);
884 this->_encodedData.append_uleb128(it->_libraryOrdinal);
887 this->_encodedData.append_byte(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | it->_flags);
888 this->_encodedData.append_string(it->_symbolName);
890 this->_encodedData.append_byte(BIND_OPCODE_DO_BIND);
891 this->_encodedData.append_byte(BIND_OPCODE_DONE);
894 // align to pointer size
895 this->_encodedData.pad_to_size(sizeof(pint_t));
897 this->_encoded = true;
898 //fprintf(stderr, "lazy binding info size = %ld, for %ld entries\n", _encodedData.size(), allLazys.size());
903 template <typename A>
904 class ExportInfoAtom : public LinkEditAtom
907 ExportInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
908 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { _encoded = true; }
910 // overrides of ld::Atom
911 virtual const char* name() const { return "export info"; }
912 // overrides of LinkEditAtom
913 virtual void encode() const;
916 typedef typename A::P P;
917 typedef typename A::P::E E;
918 typedef typename A::P::uint_t pint_t;
920 const ld::Atom* stubForResolverFunction(const ld::Atom* resolver) const;
922 struct TrieEntriesSorter
924 TrieEntriesSorter(const Options& o) : _options(o) {}
926 bool operator()(const mach_o::trie::Entry& left, const mach_o::trie::Entry& right)
928 unsigned int leftOrder;
929 unsigned int rightOrder;
930 _options.exportedSymbolOrder(left.name, &leftOrder);
931 _options.exportedSymbolOrder(right.name, &rightOrder);
932 if ( leftOrder != rightOrder )
933 return (leftOrder < rightOrder);
935 return (left.address < right.address);
938 const Options& _options;
941 static ld::Section _s_section;
944 template <typename A>
945 ld::Section ExportInfoAtom<A>::_s_section("__LINKEDIT", "__export", ld::Section::typeLinkEdit, true);
947 template <typename A>
948 const ld::Atom* ExportInfoAtom<A>::stubForResolverFunction(const ld::Atom* resolver) const
950 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _state.sections.begin(); sit != _state.sections.end(); ++sit) {
951 ld::Internal::FinalSection* sect = *sit;
952 if ( (sect->type() == ld::Section::typeStub) || (sect->type() == ld::Section::typeStubClose) ) {
953 for (std::vector<const ld::Atom*>::iterator ait = sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
954 const ld::Atom* atom = *ait;
955 if ( strcmp(atom->name(), resolver->name()) == 0 )
960 assert(0 && "no stub for resolver function");
965 template <typename A>
966 void ExportInfoAtom<A>::encode() const
968 // make vector of mach_o::trie::Entry for all exported symbols
969 std::vector<const ld::Atom*>& exports = this->_writer._exportedAtoms;
970 uint64_t imageBaseAddress = this->_writer.headerAndLoadCommandsSection->address;
971 std::vector<mach_o::trie::Entry> entries;
972 entries.reserve(exports.size());
973 for (std::vector<const ld::Atom*>::const_iterator it = exports.begin(); it != exports.end(); ++it) {
974 const ld::Atom* atom = *it;
975 mach_o::trie::Entry entry;
976 uint64_t flags = (atom->contentType() == ld::Atom::typeTLV) ? EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL : EXPORT_SYMBOL_FLAGS_KIND_REGULAR;
978 uint64_t address = atom->finalAddress() - imageBaseAddress;
979 if ( atom->definition() == ld::Atom::definitionProxy ) {
980 entry.name = atom->name();
981 entry.flags = flags | EXPORT_SYMBOL_FLAGS_REEXPORT;
982 if ( atom->combine() == ld::Atom::combineByName )
983 entry.flags |= EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
984 entry.other = this->_writer.compressedOrdinalForAtom(atom);
985 if ( entry.other == BIND_SPECIAL_DYLIB_SELF ) {
986 warning("not adding explict export for symbol %s because it is already re-exported from dylib %s", entry.name, atom->file()->path());
989 if ( atom->isAlias() ) {
990 // alias proxy means symbol was re-exported with a name change
991 const ld::Atom* aliasOf = NULL;
992 for (ld::Fixup::iterator fit = atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
993 if ( fit->kind == ld::Fixup::kindNoneFollowOn ) {
994 assert(fit->binding == ld::Fixup::bindingDirectlyBound);
995 aliasOf = fit->u.target;
998 assert(aliasOf != NULL);
999 entry.importName = aliasOf->name();
1002 // symbol name stays same as re-export
1003 entry.importName = atom->name();
1005 entries.push_back(entry);
1006 //fprintf(stderr, "re-export %s from lib %llu as %s\n", entry.importName, entry.other, entry.name);
1009 if ( (atom->definition() == ld::Atom::definitionRegular) && (atom->combine() == ld::Atom::combineByName) )
1010 flags |= EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1011 if ( atom->isThumb() )
1013 if ( atom->contentType() == ld::Atom::typeResolver ) {
1014 flags |= EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER;
1015 // set normal lookup to return stub address
1016 // and add resolver function in new location that newer dyld's can access
1018 const ld::Atom* stub = stubForResolverFunction(atom);
1019 address = stub->finalAddress() - imageBaseAddress;
1020 if ( stub->isThumb() )
1023 entry.name = atom->name();
1024 entry.flags = flags;
1025 entry.address = address;
1026 entry.other = other;
1027 entry.importName = NULL;
1028 entries.push_back(entry);
1032 // sort vector by -exported_symbols_order, and any others by address
1033 std::sort(entries.begin(), entries.end(), TrieEntriesSorter(_options));
1036 mach_o::trie::makeTrie(entries, this->_encodedData.bytes());
1038 // align to pointer size
1039 this->_encodedData.pad_to_size(sizeof(pint_t));
1041 this->_encoded = true;
1045 template <typename A>
1046 class SplitSegInfoAtom : public LinkEditAtom
1049 SplitSegInfoAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
1050 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { }
1052 // overrides of ld::Atom
1053 virtual const char* name() const { return "split seg info"; }
1054 // overrides of LinkEditAtom
1055 virtual void encode() const;
1058 typedef typename A::P P;
1059 typedef typename A::P::E E;
1060 typedef typename A::P::uint_t pint_t;
1062 void addSplitSegInfo(uint64_t address, ld::Fixup::Kind k, uint32_t) const;
1063 void uleb128EncodeAddresses(const std::vector<uint64_t>& locations) const;
1065 mutable std::vector<uint64_t> _32bitPointerLocations;
1066 mutable std::vector<uint64_t> _64bitPointerLocations;
1067 mutable std::vector<uint64_t> _thumbLo16Locations;
1068 mutable std::vector<uint64_t> _thumbHi16Locations[16];
1069 mutable std::vector<uint64_t> _armLo16Locations;
1070 mutable std::vector<uint64_t> _armHi16Locations[16];
1073 static ld::Section _s_section;
1076 template <typename A>
1077 ld::Section SplitSegInfoAtom<A>::_s_section("__LINKEDIT", "__splitSegInfo", ld::Section::typeLinkEdit, true);
1080 void SplitSegInfoAtom<x86_64>::addSplitSegInfo(uint64_t address, ld::Fixup::Kind kind, uint32_t extra) const
1083 case ld::Fixup::kindStoreX86PCRel32:
1084 case ld::Fixup::kindStoreX86PCRel32_1:
1085 case ld::Fixup::kindStoreX86PCRel32_2:
1086 case ld::Fixup::kindStoreX86PCRel32_4:
1087 case ld::Fixup::kindStoreX86PCRel32GOTLoad:
1088 case ld::Fixup::kindStoreX86PCRel32GOTLoadNowLEA:
1089 case ld::Fixup::kindStoreX86PCRel32GOT:
1090 case ld::Fixup::kindStoreLittleEndian32:
1091 case ld::Fixup::kindStoreTargetAddressLittleEndian32:
1092 case ld::Fixup::kindStoreTargetAddressX86PCRel32:
1093 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoad:
1094 case ld::Fixup::kindStoreTargetAddressX86PCRel32GOTLoadNowLEA:
1095 _32bitPointerLocations.push_back(address);
1097 case ld::Fixup::kindStoreLittleEndian64:
1098 case ld::Fixup::kindStoreTargetAddressLittleEndian64:
1099 _64bitPointerLocations.push_back(address);
1102 warning("codegen at address 0x%08llX prevents image from working in dyld shared cache", address);
1108 void SplitSegInfoAtom<x86>::addSplitSegInfo(uint64_t address, ld::Fixup::Kind kind, uint32_t extra) const
1111 case ld::Fixup::kindStoreLittleEndian32:
1112 case ld::Fixup::kindStoreTargetAddressLittleEndian32:
1113 _32bitPointerLocations.push_back(address);
1116 warning("codegen at address 0x%08llX prevents image from working in dyld shared cache", address);
1122 void SplitSegInfoAtom<arm>::addSplitSegInfo(uint64_t address, ld::Fixup::Kind kind, uint32_t extra) const
1125 case ld::Fixup::kindStoreLittleEndian32:
1126 _32bitPointerLocations.push_back(address);
1128 case ld::Fixup::kindStoreARMLow16:
1129 _armLo16Locations.push_back(address);
1131 case ld::Fixup::kindStoreThumbLow16:
1132 _thumbLo16Locations.push_back(address);
1134 case ld::Fixup::kindStoreARMHigh16:
1136 _armHi16Locations[extra].push_back(address);
1138 case ld::Fixup::kindStoreThumbHigh16:
1140 _thumbHi16Locations[extra].push_back(address);
1143 warning("codegen at address 0x%08llX prevents image from working in dyld shared cache", address);
1150 template <typename A>
1151 void SplitSegInfoAtom<A>::uleb128EncodeAddresses(const std::vector<uint64_t>& locations) const
1153 pint_t addr = this->_options.baseAddress();
1154 for(typename std::vector<uint64_t>::const_iterator it = locations.begin(); it != locations.end(); ++it) {
1155 pint_t nextAddr = *it;
1156 //fprintf(stderr, "nextAddr=0x%0llX\n", (uint64_t)nextAddr);
1157 uint64_t delta = nextAddr - addr;
1158 //fprintf(stderr, "delta=0x%0llX\n", delta);
1160 throw "double split seg info for same address";
1164 byte = delta & 0x7F;
1168 this->_encodedData.append_byte(byte);
1171 while( byte >= 0x80 );
1177 template <typename A>
1178 void SplitSegInfoAtom<A>::encode() const
1180 // sort into group by pointer adjustment kind
1181 std::vector<OutputFile::SplitSegInfoEntry>& info = this->_writer._splitSegInfos;
1182 for (std::vector<OutputFile::SplitSegInfoEntry>::const_iterator it = info.begin(); it != info.end(); ++it) {
1183 this->addSplitSegInfo(it->address, it->kind, it->extra);
1186 // delta compress runs of addresses
1187 this->_encodedData.reserve(8192);
1188 if ( _32bitPointerLocations.size() != 0 ) {
1189 this->_encodedData.append_byte(1);
1190 //fprintf(stderr, "type 1:\n");
1191 std::sort(_32bitPointerLocations.begin(), _32bitPointerLocations.end());
1192 this->uleb128EncodeAddresses(_32bitPointerLocations);
1193 this->_encodedData.append_byte(0); // terminator
1196 if ( _64bitPointerLocations.size() != 0 ) {
1197 this->_encodedData.append_byte(2);
1198 //fprintf(stderr, "type 2:\n");
1199 std::sort(_64bitPointerLocations.begin(), _64bitPointerLocations.end());
1200 this->uleb128EncodeAddresses(_64bitPointerLocations);
1201 this->_encodedData.append_byte(0); // terminator
1204 if ( _thumbLo16Locations.size() != 0 ) {
1205 this->_encodedData.append_byte(5);
1206 //fprintf(stderr, "type 5:\n");
1207 std::sort(_thumbLo16Locations.begin(), _thumbLo16Locations.end());
1208 this->uleb128EncodeAddresses(_thumbLo16Locations);
1209 this->_encodedData.append_byte(0); // terminator
1212 if ( _armLo16Locations.size() != 0 ) {
1213 this->_encodedData.append_byte(6);
1214 //fprintf(stderr, "type 6:\n");
1215 std::sort(_armLo16Locations.begin(), _armLo16Locations.end());
1216 this->uleb128EncodeAddresses(_armLo16Locations);
1217 this->_encodedData.append_byte(0); // terminator
1220 for (uint32_t i=0; i < 16; ++i) {
1221 if ( _thumbHi16Locations[i].size() != 0 ) {
1222 this->_encodedData.append_byte(16+i);
1223 //fprintf(stderr, "type 16+%d:\n", i);
1224 std::sort(_thumbHi16Locations[i].begin(), _thumbHi16Locations[i].end());
1225 this->uleb128EncodeAddresses(_thumbHi16Locations[i]);
1226 this->_encodedData.append_byte(0); // terminator
1230 for (uint32_t i=0; i < 16; ++i) {
1231 if ( _armHi16Locations[i].size() != 0 ) {
1232 this->_encodedData.append_byte(32+i);
1233 //fprintf(stderr, "type 32+%d:\n", i);
1234 std::sort(_armHi16Locations[i].begin(), _armHi16Locations[i].end());
1235 this->uleb128EncodeAddresses(_armHi16Locations[i]);
1236 this->_encodedData.append_byte(0); // terminator
1240 // always add zero byte to mark end
1241 this->_encodedData.append_byte(0);
1243 // align to pointer size
1244 this->_encodedData.pad_to_size(sizeof(pint_t));
1246 this->_encoded = true;
1248 // clean up temporaries
1249 _32bitPointerLocations.clear();
1250 _64bitPointerLocations.clear();
1253 template <typename A>
1254 class FunctionStartsAtom : public LinkEditAtom
1257 FunctionStartsAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
1258 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { }
1260 // overrides of ld::Atom
1261 virtual const char* name() const { return "function starts"; }
1262 // overrides of LinkEditAtom
1263 virtual void encode() const;
1266 typedef typename A::P P;
1267 typedef typename A::P::E E;
1268 typedef typename A::P::uint_t pint_t;
1270 static ld::Section _s_section;
1273 template <typename A>
1274 ld::Section FunctionStartsAtom<A>::_s_section("__LINKEDIT", "__funcStarts", ld::Section::typeLinkEdit, true);
1277 template <typename A>
1278 void FunctionStartsAtom<A>::encode() const
1280 this->_encodedData.reserve(8192);
1281 const uint64_t badAddress = 0xFFFFFFFFFFFFFFFF;
1282 uint64_t addr = badAddress;
1283 // delta compress all function addresses
1284 for (std::vector<ld::Internal::FinalSection*>::iterator it = this->_state.sections.begin(); it != this->_state.sections.end(); ++it) {
1285 ld::Internal::FinalSection* sect = *it;
1286 if ( sect->type() == ld::Section::typeMachHeader ) {
1287 // start with delta from start of __TEXT
1288 addr = sect->address;
1290 else if ( sect->type() == ld::Section::typeCode ) {
1291 assert(addr != badAddress);
1292 std::vector<const ld::Atom*>& atoms = sect->atoms;
1293 for (std::vector<const ld::Atom*>::iterator ait = atoms.begin(); ait != atoms.end(); ++ait) {
1294 const ld::Atom* atom = *ait;
1295 // <rdar://problem/10422823> filter out zero-length atoms, so LC_FUNCTION_STARTS address can't spill into next section
1296 if ( atom->size() == 0 )
1298 uint64_t nextAddr = atom->finalAddress();
1299 if ( atom->isThumb() )
1301 uint64_t delta = nextAddr - addr;
1303 this->_encodedData.append_uleb128(delta);
1310 this->_encodedData.append_byte(0);
1312 // align to pointer size
1313 this->_encodedData.pad_to_size(sizeof(pint_t));
1315 this->_encoded = true;
1319 // <rdar://problem/9218847> Need way to formalize data in code
1320 template <typename A>
1321 class DataInCodeAtom : public LinkEditAtom
1324 DataInCodeAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
1325 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { }
1327 // overrides of ld::Atom
1328 virtual const char* name() const { return "data-in-code info"; }
1329 // overrides of LinkEditAtom
1330 virtual void encode() const;
1333 typedef typename A::P P;
1334 typedef typename A::P::E E;
1335 typedef typename A::P::uint_t pint_t;
1337 struct FixupByAddressSorter
1339 bool operator()(const ld::Fixup* left, const ld::Fixup* right)
1341 return (left->offsetInAtom < right->offsetInAtom);
1345 void encodeEntry(uint32_t startImageOffset, int len, ld::Fixup::Kind kind) const {
1346 //fprintf(stderr, "encodeEntry(start=0x%08X, len=0x%04X, kind=%04X\n", startImageOffset, len, kind);
1348 macho_data_in_code_entry<P> entry;
1349 entry.set_offset(startImageOffset);
1350 entry.set_length(len);
1352 case ld::Fixup::kindDataInCodeStartData:
1353 entry.set_kind(DICE_KIND_DATA);
1355 case ld::Fixup::kindDataInCodeStartJT8:
1356 entry.set_kind(DICE_KIND_JUMP_TABLE8);
1358 case ld::Fixup::kindDataInCodeStartJT16:
1359 entry.set_kind(DICE_KIND_JUMP_TABLE16);
1361 case ld::Fixup::kindDataInCodeStartJT32:
1362 entry.set_kind(DICE_KIND_JUMP_TABLE32);
1364 case ld::Fixup::kindDataInCodeStartJTA32:
1365 entry.set_kind(DICE_KIND_ABS_JUMP_TABLE32);
1368 assert(0 && "bad L$start$ label to encode");
1370 uint8_t* bp = (uint8_t*)&entry;
1371 this->_encodedData.append_byte(bp[0]);
1372 this->_encodedData.append_byte(bp[1]);
1373 this->_encodedData.append_byte(bp[2]);
1374 this->_encodedData.append_byte(bp[3]);
1375 this->_encodedData.append_byte(bp[4]);
1376 this->_encodedData.append_byte(bp[5]);
1377 this->_encodedData.append_byte(bp[6]);
1378 this->_encodedData.append_byte(bp[7]);
1379 // in rare case data range is huge, create multiple entries
1381 startImageOffset += 0xFFF8;
1382 } while ( len > 0 );
1385 static ld::Section _s_section;
1388 template <typename A>
1389 ld::Section DataInCodeAtom<A>::_s_section("__LINKEDIT", "__dataInCode", ld::Section::typeLinkEdit, true);
1392 template <typename A>
1393 void DataInCodeAtom<A>::encode() const
1395 if ( this->_writer.hasDataInCode ) {
1396 uint64_t mhAddress = 0;
1397 for (std::vector<ld::Internal::FinalSection*>::iterator sit = _state.sections.begin(); sit != _state.sections.end(); ++sit) {
1398 ld::Internal::FinalSection* sect = *sit;
1399 if ( sect->type() == ld::Section::typeMachHeader )
1400 mhAddress = sect->address;
1401 if ( sect->type() != ld::Section::typeCode )
1403 for (std::vector<const ld::Atom*>::iterator ait = sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
1404 const ld::Atom* atom = *ait;
1405 // gather all code-in-data labels
1406 std::vector<const ld::Fixup*> dataInCodeLabels;
1407 for (ld::Fixup::iterator fit = atom->fixupsBegin(); fit != atom->fixupsEnd(); ++fit) {
1408 switch ( fit->kind ) {
1409 case ld::Fixup::kindDataInCodeStartData:
1410 case ld::Fixup::kindDataInCodeStartJT8:
1411 case ld::Fixup::kindDataInCodeStartJT16:
1412 case ld::Fixup::kindDataInCodeStartJT32:
1413 case ld::Fixup::kindDataInCodeStartJTA32:
1414 case ld::Fixup::kindDataInCodeEnd:
1415 dataInCodeLabels.push_back(fit);
1421 // to do: sort labels by address
1422 std::sort(dataInCodeLabels.begin(), dataInCodeLabels.end(), FixupByAddressSorter());
1424 // convert to array of struct data_in_code_entry
1425 ld::Fixup::Kind prevKind = ld::Fixup::kindDataInCodeEnd;
1426 uint32_t prevOffset = 0;
1427 for ( std::vector<const ld::Fixup*>::iterator sfit = dataInCodeLabels.begin(); sfit != dataInCodeLabels.end(); ++sfit) {
1428 if ( ((*sfit)->kind != prevKind) && (prevKind != ld::Fixup::kindDataInCodeEnd) ) {
1429 int len = (*sfit)->offsetInAtom - prevOffset;
1431 warning("multiple L$start$ labels found at same address in %s at offset 0x%04X", atom->name(), prevOffset);
1432 this->encodeEntry(atom->finalAddress()+prevOffset-mhAddress, (*sfit)->offsetInAtom - prevOffset, prevKind);
1434 prevKind = (*sfit)->kind;
1435 prevOffset = (*sfit)->offsetInAtom;
1437 if ( prevKind != ld::Fixup::kindDataInCodeEnd ) {
1438 // add entry if function ends with data
1439 this->encodeEntry(atom->finalAddress()+prevOffset-mhAddress, atom->size() - prevOffset, prevKind);
1445 this->_encoded = true;
1452 // <rdar://problem/7209249> linker needs to cache "Designated Requirements" in linked binary
1453 template <typename A>
1454 class DependentDRAtom : public LinkEditAtom
1457 DependentDRAtom(const Options& opts, ld::Internal& state, OutputFile& writer)
1458 : LinkEditAtom(opts, state, writer, _s_section, sizeof(pint_t)) { }
1460 // overrides of ld::Atom
1461 virtual const char* name() const { return "dependent dylib DR info"; }
1462 // overrides of LinkEditAtom
1463 virtual void encode() const;
1466 typedef typename A::P P;
1467 typedef typename A::P::E E;
1468 typedef typename A::P::uint_t pint_t;
1470 static ld::Section _s_section;
1474 template <typename A>
1475 ld::Section DependentDRAtom<A>::_s_section("__LINKEDIT", "__dependentDR", ld::Section::typeLinkEdit, true);
1478 template <typename A>
1479 void DependentDRAtom<A>::encode() const
1481 Security::SuperBlobCore<Security::SuperBlob<Security::kSecCodeMagicDRList>, Security::kSecCodeMagicDRList, uint32_t>::Maker maker;
1484 for(std::vector<ld::dylib::File*>::iterator it=_state.dylibs.begin(); it != _state.dylibs.end(); ++it) {
1485 const ld::dylib::File* dylib = *it;
1486 Security::BlobCore* dylibDR = (Security::BlobCore*)dylib->codeSignatureDR();
1488 if ( dylibDR != NULL ) {
1489 // <rdar://problem/11315321> Maker takes ownership of every blob added
1490 // We need to make a copy here because dylib still owns the pointer returned by codeSignatureDR()
1491 dup = ::malloc(dylibDR->length());
1492 ::memcpy(dup, dylibDR, dylibDR->length());
1494 maker.add(index, (Security::BlobCore*)dup);
1498 Security::SuperBlob<Security::kSecCodeMagicDRList>* topBlob = maker.make();
1499 const uint8_t* data = (uint8_t*)topBlob->data();
1500 for(size_t i=0; i < topBlob->length(); ++i)
1501 _encodedData.append_byte(data[i]);
1503 this->_encodedData.pad_to_size(sizeof(pint_t));
1505 this->_encoded = true;
1513 #endif // __LINKEDIT_HPP__