GNULDBackend.cpp revision 22add6ff3426df1a85089fe6a6e1597ee3b6f300
1//===- GNULDBackend.cpp ---------------------------------------------------===// 2// 3// The MCLinker Project 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9#include <mcld/Target/GNULDBackend.h> 10 11#include <string> 12#include <cstring> 13#include <cassert> 14 15#include <mcld/Module.h> 16#include <mcld/LinkerConfig.h> 17#include <mcld/IRBuilder.h> 18#include <mcld/InputTree.h> 19#include <mcld/ADT/SizeTraits.h> 20#include <mcld/LD/LDSymbol.h> 21#include <mcld/LD/LDContext.h> 22#include <mcld/Fragment/FillFragment.h> 23#include <mcld/LD/EhFrame.h> 24#include <mcld/LD/EhFrameHdr.h> 25#include <mcld/LD/RelocData.h> 26#include <mcld/MC/Attribute.h> 27#include <mcld/Fragment/FragmentLinker.h> 28#include <mcld/Support/MemoryArea.h> 29#include <mcld/Support/MemoryRegion.h> 30#include <mcld/Support/MsgHandling.h> 31#include <mcld/Support/MemoryAreaFactory.h> 32#include <mcld/LD/BranchIslandFactory.h> 33#include <mcld/LD/StubFactory.h> 34#include <mcld/Object/ObjectBuilder.h> 35 36using namespace mcld; 37 38//===--------------------------------------------------------------------===// 39// non-member functions 40//===----------------------------------------------------------------------===// 41 42/// isCIdentifier - return if the pName is a valid C identifier 43static bool isCIdentifier(const std::string& pName) 44{ 45 std::string ident = "0123456789" 46 "ABCDEFGHIJKLMNOPWRSTUVWXYZ" 47 "abcdefghijklmnopqrstuvwxyz" 48 "_"; 49 return (pName.find_first_not_of(ident) > pName.length()); 50} 51 52//===----------------------------------------------------------------------===// 53// GNULDBackend 54//===----------------------------------------------------------------------===// 55GNULDBackend::GNULDBackend(const LinkerConfig& pConfig) 56 : TargetLDBackend(pConfig), 57 m_pObjectReader(NULL), 58 m_pDynObjFileFormat(NULL), 59 m_pExecFileFormat(NULL), 60 m_pObjectFileFormat(NULL), 61 m_ELFSegmentTable(9), // magic number 62 m_pBRIslandFactory(NULL), 63 m_pStubFactory(NULL), 64 m_pEhFrame(NULL), 65 m_pEhFrameHdr(NULL), 66 m_bHasTextRel(false), 67 m_bHasStaticTLS(false), 68 f_pPreInitArrayStart(NULL), 69 f_pPreInitArrayEnd(NULL), 70 f_pInitArrayStart(NULL), 71 f_pInitArrayEnd(NULL), 72 f_pFiniArrayStart(NULL), 73 f_pFiniArrayEnd(NULL), 74 f_pStack(NULL), 75 f_pDynamic(NULL), 76 f_pTDATA(NULL), 77 f_pTBSS(NULL), 78 f_pExecutableStart(NULL), 79 f_pEText(NULL), 80 f_p_EText(NULL), 81 f_p__EText(NULL), 82 f_pEData(NULL), 83 f_p_EData(NULL), 84 f_pBSSStart(NULL), 85 f_pEnd(NULL), 86 f_p_End(NULL) { 87 m_pSymIndexMap = new HashTableType(1024); 88} 89 90GNULDBackend::~GNULDBackend() 91{ 92 delete m_pDynObjFileFormat; 93 delete m_pExecFileFormat; 94 delete m_pSymIndexMap; 95 delete m_pEhFrame; 96 delete m_pEhFrameHdr; 97 98 if (NULL != m_pBRIslandFactory) 99 delete m_pBRIslandFactory; 100 if (NULL != m_pStubFactory) 101 delete m_pStubFactory; 102} 103 104size_t GNULDBackend::sectionStartOffset() const 105{ 106 // FIXME: use fixed offset, we need 10 segments by default 107 return sizeof(llvm::ELF::Elf64_Ehdr)+10*sizeof(llvm::ELF::Elf64_Phdr); 108} 109 110uint64_t GNULDBackend::segmentStartAddr(const FragmentLinker& pLinker) const 111{ 112 ScriptOptions::AddressMap::const_iterator mapping = 113 config().scripts().addressMap().find(".text"); 114 if (mapping != config().scripts().addressMap().end()) 115 return mapping.getEntry()->value(); 116 else if (pLinker.isOutputPIC()) 117 return 0x0; 118 else 119 return defaultTextSegmentAddr(); 120} 121 122GNUArchiveReader* 123GNULDBackend::createArchiveReader(Module& pModule) 124{ 125 assert(NULL != m_pObjectReader); 126 return new GNUArchiveReader(pModule, *m_pObjectReader); 127} 128 129ELFObjectReader* GNULDBackend::createObjectReader(FragmentLinker& pLinker) 130{ 131 m_pObjectReader = new ELFObjectReader(*this, pLinker); 132 return m_pObjectReader; 133} 134 135ELFDynObjReader* GNULDBackend::createDynObjReader(FragmentLinker& pLinker) 136{ 137 return new ELFDynObjReader(*this, pLinker); 138} 139 140ELFObjectWriter* GNULDBackend::createObjectWriter(FragmentLinker& pLinker) 141{ 142 return new ELFObjectWriter(*this, pLinker); 143} 144 145ELFDynObjWriter* GNULDBackend::createDynObjWriter(FragmentLinker& pLinker) 146{ 147 return new ELFDynObjWriter(*this, pLinker); 148} 149 150ELFExecWriter* GNULDBackend::createExecWriter(FragmentLinker& pLinker) 151{ 152 return new ELFExecWriter(*this, pLinker); 153} 154 155bool GNULDBackend::initStdSections(ObjectBuilder& pBuilder) 156{ 157 switch (config().codeGenType()) { 158 case LinkerConfig::DynObj: { 159 if (NULL == m_pDynObjFileFormat) 160 m_pDynObjFileFormat = new ELFDynObjFileFormat(); 161 m_pDynObjFileFormat->initStdSections(pBuilder, bitclass()); 162 return true; 163 } 164 case LinkerConfig::Exec: { 165 if (NULL == m_pExecFileFormat) 166 m_pExecFileFormat = new ELFExecFileFormat(); 167 m_pExecFileFormat->initStdSections(pBuilder, bitclass()); 168 return true; 169 } 170 case LinkerConfig::Object: { 171 if (NULL == m_pObjectFileFormat) 172 m_pObjectFileFormat = new ELFObjectFileFormat(); 173 m_pObjectFileFormat->initStdSections(pBuilder, bitclass()); 174 return true; 175 } 176 default: 177 fatal(diag::unrecognized_output_file) << config().codeGenType(); 178 return false; 179 } 180} 181 182/// initStandardSymbols - define and initialize standard symbols. 183/// This function is called after section merging but before read relocations. 184bool GNULDBackend::initStandardSymbols(FragmentLinker& pLinker, 185 Module& pModule) 186{ 187 if (LinkerConfig::Object == config().codeGenType()) 188 return true; 189 190 // GNU extension: define __start and __stop symbols for the sections whose 191 // name can be presented as C symbol 192 // ref: GNU gold, Layout::define_section_symbols 193 Module::iterator iter, iterEnd = pModule.end(); 194 for (iter = pModule.begin(); iter != iterEnd; ++iter) { 195 LDSection* section = *iter; 196 197 switch (section->kind()) { 198 case LDFileFormat::Relocation: 199 continue; 200 case LDFileFormat::EhFrame: 201 if (!section->hasEhFrame()) 202 continue; 203 break; 204 default: 205 if (!section->hasSectionData()) 206 continue; 207 break; 208 } // end of switch 209 210 if (isCIdentifier(section->name())) { 211 llvm::StringRef start_name = llvm::StringRef("__start_" + section->name()); 212 FragmentRef* start_fragref = FragmentRef::Create( 213 section->getSectionData()->front(), 0x0); 214 pLinker.defineSymbol<FragmentLinker::AsRefered, 215 FragmentLinker::Resolve>(start_name, 216 false, // isDyn 217 ResolveInfo::NoType, 218 ResolveInfo::Define, 219 ResolveInfo::Global, 220 0x0, // size 221 0x0, // value 222 start_fragref, // FragRef 223 ResolveInfo::Default); 224 225 llvm::StringRef stop_name = llvm::StringRef("__stop_" + section->name()); 226 FragmentRef* stop_fragref = FragmentRef::Create( 227 section->getSectionData()->front(), section->size()); 228 pLinker.defineSymbol<FragmentLinker::AsRefered, 229 FragmentLinker::Resolve>(stop_name, 230 false, // isDyn 231 ResolveInfo::NoType, 232 ResolveInfo::Define, 233 ResolveInfo::Global, 234 0x0, // size 235 0x0, // value 236 stop_fragref, // FragRef 237 ResolveInfo::Default); 238 } 239 } 240 241 ELFFileFormat* file_format = getOutputFormat(); 242 243 // ----- section symbols ----- // 244 // .preinit_array 245 FragmentRef* preinit_array = NULL; 246 if (file_format->hasPreInitArray()) { 247 preinit_array = FragmentRef::Create( 248 file_format->getPreInitArray().getSectionData()->front(), 249 0x0); 250 } 251 else { 252 preinit_array = FragmentRef::Null(); 253 } 254 f_pPreInitArrayStart = 255 pLinker.defineSymbol<FragmentLinker::AsRefered, 256 FragmentLinker::Resolve>("__preinit_array_start", 257 false, // isDyn 258 ResolveInfo::NoType, 259 ResolveInfo::Define, 260 ResolveInfo::Global, 261 0x0, // size 262 0x0, // value 263 preinit_array, // FragRef 264 ResolveInfo::Hidden); 265 f_pPreInitArrayEnd = 266 pLinker.defineSymbol<FragmentLinker::AsRefered, 267 FragmentLinker::Resolve>("__preinit_array_end", 268 false, // isDyn 269 ResolveInfo::NoType, 270 ResolveInfo::Define, 271 ResolveInfo::Global, 272 0x0, // size 273 0x0, // value 274 FragmentRef::Null(), // FragRef 275 ResolveInfo::Hidden); 276 277 // .init_array 278 FragmentRef* init_array = NULL; 279 if (file_format->hasInitArray()) { 280 init_array = FragmentRef::Create( 281 file_format->getInitArray().getSectionData()->front(), 282 0x0); 283 } 284 else { 285 init_array = FragmentRef::Null(); 286 } 287 288 f_pInitArrayStart = 289 pLinker.defineSymbol<FragmentLinker::AsRefered, 290 FragmentLinker::Resolve>("__init_array_start", 291 false, // isDyn 292 ResolveInfo::NoType, 293 ResolveInfo::Define, 294 ResolveInfo::Global, 295 0x0, // size 296 0x0, // value 297 init_array, // FragRef 298 ResolveInfo::Hidden); 299 f_pInitArrayEnd = 300 pLinker.defineSymbol<FragmentLinker::AsRefered, 301 FragmentLinker::Resolve>("__init_array_end", 302 false, // isDyn 303 ResolveInfo::NoType, 304 ResolveInfo::Define, 305 ResolveInfo::Global, 306 0x0, // size 307 0x0, // value 308 init_array, // FragRef 309 ResolveInfo::Hidden); 310 311 // .fini_array 312 FragmentRef* fini_array = NULL; 313 if (file_format->hasFiniArray()) { 314 fini_array = FragmentRef::Create( 315 file_format->getFiniArray().getSectionData()->front(), 316 0x0); 317 } 318 else { 319 fini_array = FragmentRef::Null(); 320 } 321 322 f_pFiniArrayStart = 323 pLinker.defineSymbol<FragmentLinker::AsRefered, 324 FragmentLinker::Resolve>("__fini_array_start", 325 false, // isDyn 326 ResolveInfo::NoType, 327 ResolveInfo::Define, 328 ResolveInfo::Global, 329 0x0, // size 330 0x0, // value 331 fini_array, // FragRef 332 ResolveInfo::Hidden); 333 f_pFiniArrayEnd = 334 pLinker.defineSymbol<FragmentLinker::AsRefered, 335 FragmentLinker::Resolve>("__fini_array_end", 336 false, // isDyn 337 ResolveInfo::NoType, 338 ResolveInfo::Define, 339 ResolveInfo::Global, 340 0x0, // size 341 0x0, // value 342 fini_array, // FragRef 343 ResolveInfo::Hidden); 344 345 // .stack 346 FragmentRef* stack = NULL; 347 if (file_format->hasStack()) { 348 stack = FragmentRef::Create( 349 file_format->getStack().getSectionData()->front(), 350 0x0); 351 } 352 else { 353 stack = FragmentRef::Null(); 354 } 355 356 f_pStack = 357 pLinker.defineSymbol<FragmentLinker::AsRefered, 358 FragmentLinker::Resolve>("__stack", 359 false, // isDyn 360 ResolveInfo::NoType, 361 ResolveInfo::Define, 362 ResolveInfo::Global, 363 0x0, // size 364 0x0, // value 365 stack, // FragRef 366 ResolveInfo::Hidden); 367 368 // _DYNAMIC 369 // TODO: add SectionData for .dynamic section, and then we can get the correct 370 // symbol section index for _DYNAMIC. Now it will be ABS. 371 f_pDynamic = 372 pLinker.defineSymbol<FragmentLinker::AsRefered, 373 FragmentLinker::Resolve>("_DYNAMIC", 374 false, // isDyn 375 ResolveInfo::Object, 376 ResolveInfo::Define, 377 ResolveInfo::Local, 378 0x0, // size 379 0x0, // value 380 FragmentRef::Null(), // FragRef 381 ResolveInfo::Hidden); 382 383 // ----- segment symbols ----- // 384 f_pExecutableStart = 385 pLinker.defineSymbol<FragmentLinker::AsRefered, 386 FragmentLinker::Resolve>("__executable_start", 387 false, // isDyn 388 ResolveInfo::NoType, 389 ResolveInfo::Define, 390 ResolveInfo::Absolute, 391 0x0, // size 392 0x0, // value 393 FragmentRef::Null(), // FragRef 394 ResolveInfo::Default); 395 f_pEText = 396 pLinker.defineSymbol<FragmentLinker::AsRefered, 397 FragmentLinker::Resolve>("etext", 398 false, // isDyn 399 ResolveInfo::NoType, 400 ResolveInfo::Define, 401 ResolveInfo::Absolute, 402 0x0, // size 403 0x0, // value 404 FragmentRef::Null(), // FragRef 405 ResolveInfo::Default); 406 f_p_EText = 407 pLinker.defineSymbol<FragmentLinker::AsRefered, 408 FragmentLinker::Resolve>("_etext", 409 false, // isDyn 410 ResolveInfo::NoType, 411 ResolveInfo::Define, 412 ResolveInfo::Absolute, 413 0x0, // size 414 0x0, // value 415 FragmentRef::Null(), // FragRef 416 ResolveInfo::Default); 417 f_p__EText = 418 pLinker.defineSymbol<FragmentLinker::AsRefered, 419 FragmentLinker::Resolve>("__etext", 420 false, // isDyn 421 ResolveInfo::NoType, 422 ResolveInfo::Define, 423 ResolveInfo::Absolute, 424 0x0, // size 425 0x0, // value 426 FragmentRef::Null(), // FragRef 427 ResolveInfo::Default); 428 f_pEData = 429 pLinker.defineSymbol<FragmentLinker::AsRefered, 430 FragmentLinker::Resolve>("edata", 431 false, // isDyn 432 ResolveInfo::NoType, 433 ResolveInfo::Define, 434 ResolveInfo::Absolute, 435 0x0, // size 436 0x0, // value 437 FragmentRef::Null(), // FragRef 438 ResolveInfo::Default); 439 440 f_pEnd = 441 pLinker.defineSymbol<FragmentLinker::AsRefered, 442 FragmentLinker::Resolve>("end", 443 false, // isDyn 444 ResolveInfo::NoType, 445 ResolveInfo::Define, 446 ResolveInfo::Absolute, 447 0x0, // size 448 0x0, // value 449 FragmentRef::Null(), // FragRef 450 ResolveInfo::Default); 451 452 // _edata is defined forcefully. 453 // @ref Google gold linker: defstd.cc: 186 454 f_p_EData = 455 pLinker.defineSymbol<FragmentLinker::Force, 456 FragmentLinker::Resolve>("_edata", 457 false, // isDyn 458 ResolveInfo::NoType, 459 ResolveInfo::Define, 460 ResolveInfo::Absolute, 461 0x0, // size 462 0x0, // value 463 FragmentRef::Null(), // FragRef 464 ResolveInfo::Default); 465 466 // __bss_start is defined forcefully. 467 // @ref Google gold linker: defstd.cc: 214 468 f_pBSSStart = 469 pLinker.defineSymbol<FragmentLinker::Force, 470 FragmentLinker::Resolve>("__bss_start", 471 false, // isDyn 472 ResolveInfo::NoType, 473 ResolveInfo::Define, 474 ResolveInfo::Absolute, 475 0x0, // size 476 0x0, // value 477 FragmentRef::Null(), // FragRef 478 ResolveInfo::Default); 479 480 // _end is defined forcefully. 481 // @ref Google gold linker: defstd.cc: 228 482 f_p_End = 483 pLinker.defineSymbol<FragmentLinker::Force, 484 FragmentLinker::Resolve>("_end", 485 false, // isDyn 486 ResolveInfo::NoType, 487 ResolveInfo::Define, 488 ResolveInfo::Absolute, 489 0x0, // size 490 0x0, // value 491 FragmentRef::Null(), // FragRef 492 ResolveInfo::Default); 493 494 return true; 495} 496 497bool 498GNULDBackend::finalizeStandardSymbols(FragmentLinker& pLinker) 499{ 500 if (LinkerConfig::Object == config().codeGenType()) 501 return true; 502 503 ELFFileFormat* file_format = getOutputFormat(); 504 505 // ----- section symbols ----- // 506 if (NULL != f_pPreInitArrayStart) { 507 if (!f_pPreInitArrayStart->hasFragRef()) { 508 f_pPreInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 509 f_pPreInitArrayStart->setValue(0x0); 510 } 511 } 512 513 if (NULL != f_pPreInitArrayEnd) { 514 if (f_pPreInitArrayEnd->hasFragRef()) { 515 f_pPreInitArrayEnd->setValue(f_pPreInitArrayEnd->value() + 516 file_format->getPreInitArray().size()); 517 } 518 else { 519 f_pPreInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 520 f_pPreInitArrayEnd->setValue(0x0); 521 } 522 } 523 524 if (NULL != f_pInitArrayStart) { 525 if (!f_pInitArrayStart->hasFragRef()) { 526 f_pInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 527 f_pInitArrayStart->setValue(0x0); 528 } 529 } 530 531 if (NULL != f_pInitArrayEnd) { 532 if (f_pInitArrayEnd->hasFragRef()) { 533 f_pInitArrayEnd->setValue(f_pInitArrayEnd->value() + 534 file_format->getInitArray().size()); 535 } 536 else { 537 f_pInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 538 f_pInitArrayEnd->setValue(0x0); 539 } 540 } 541 542 if (NULL != f_pFiniArrayStart) { 543 if (!f_pFiniArrayStart->hasFragRef()) { 544 f_pFiniArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 545 f_pFiniArrayStart->setValue(0x0); 546 } 547 } 548 549 if (NULL != f_pFiniArrayEnd) { 550 if (f_pFiniArrayEnd->hasFragRef()) { 551 f_pFiniArrayEnd->setValue(f_pFiniArrayEnd->value() + 552 file_format->getFiniArray().size()); 553 } 554 else { 555 f_pFiniArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 556 f_pFiniArrayEnd->setValue(0x0); 557 } 558 } 559 560 if (NULL != f_pStack) { 561 if (!f_pStack->hasFragRef()) { 562 f_pStack->resolveInfo()->setBinding(ResolveInfo::Absolute); 563 f_pStack->setValue(0x0); 564 } 565 } 566 567 if (NULL != f_pDynamic) { 568 f_pDynamic->resolveInfo()->setBinding(ResolveInfo::Local); 569 f_pDynamic->setValue(file_format->getDynamic().addr()); 570 f_pDynamic->setSize(file_format->getDynamic().size()); 571 } 572 573 // ----- segment symbols ----- // 574 if (NULL != f_pExecutableStart) { 575 ELFSegment* exec_start = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 0x0, 0x0); 576 if (NULL != exec_start) { 577 if (ResolveInfo::ThreadLocal != f_pExecutableStart->type()) { 578 f_pExecutableStart->setValue(f_pExecutableStart->value() + 579 exec_start->vaddr()); 580 } 581 } 582 else 583 f_pExecutableStart->setValue(0x0); 584 } 585 586 if (NULL != f_pEText || NULL != f_p_EText || NULL !=f_p__EText) { 587 ELFSegment* etext = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 588 llvm::ELF::PF_X, 589 llvm::ELF::PF_W); 590 if (NULL != etext) { 591 if (NULL != f_pEText && ResolveInfo::ThreadLocal != f_pEText->type()) { 592 f_pEText->setValue(f_pEText->value() + 593 etext->vaddr() + 594 etext->memsz()); 595 } 596 if (NULL != f_p_EText && ResolveInfo::ThreadLocal != f_p_EText->type()) { 597 f_p_EText->setValue(f_p_EText->value() + 598 etext->vaddr() + 599 etext->memsz()); 600 } 601 if (NULL != f_p__EText && ResolveInfo::ThreadLocal != f_p__EText->type()) { 602 f_p__EText->setValue(f_p__EText->value() + 603 etext->vaddr() + 604 etext->memsz()); 605 } 606 } 607 else { 608 if (NULL != f_pEText) 609 f_pEText->setValue(0x0); 610 if (NULL != f_p_EText) 611 f_p_EText->setValue(0x0); 612 if (NULL != f_p__EText) 613 f_p__EText->setValue(0x0); 614 } 615 } 616 617 if (NULL != f_pEData || NULL != f_p_EData || NULL != f_pBSSStart || 618 NULL != f_pEnd || NULL != f_p_End) { 619 ELFSegment* edata = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 620 llvm::ELF::PF_W, 621 0x0); 622 if (NULL != edata) { 623 if (NULL != f_pEData && ResolveInfo::ThreadLocal != f_pEData->type()) { 624 f_pEData->setValue(f_pEData->value() + 625 edata->vaddr() + 626 edata->filesz()); 627 } 628 if (NULL != f_p_EData && ResolveInfo::ThreadLocal != f_p_EData->type()) { 629 f_p_EData->setValue(f_p_EData->value() + 630 edata->vaddr() + 631 edata->filesz()); 632 } 633 if (NULL != f_pBSSStart && ResolveInfo::ThreadLocal != f_pBSSStart->type()) { 634 f_pBSSStart->setValue(f_pBSSStart->value() + 635 edata->vaddr() + 636 edata->filesz()); 637 } 638 639 if (NULL != f_pEnd && ResolveInfo::ThreadLocal != f_pEnd->type()) { 640 f_pEnd->setValue(f_pEnd->value() + 641 edata->vaddr() + 642 edata->memsz()); 643 } 644 if (NULL != f_p_End && ResolveInfo::ThreadLocal != f_p_End->type()) { 645 f_p_End->setValue(f_p_End->value() + 646 edata->vaddr() + 647 edata->memsz()); 648 } 649 } 650 else { 651 if (NULL != f_pEData) 652 f_pEData->setValue(0x0); 653 if (NULL != f_p_EData) 654 f_p_EData->setValue(0x0); 655 if (NULL != f_pBSSStart) 656 f_pBSSStart->setValue(0x0); 657 658 if (NULL != f_pEnd) 659 f_pEnd->setValue(0x0); 660 if (NULL != f_p_End) 661 f_p_End->setValue(0x0); 662 } 663 } 664 665 return true; 666} 667 668bool GNULDBackend::finalizeTLSSymbol(LDSymbol& pSymbol) 669{ 670 // ignore if symbol has no fragRef 671 if (!pSymbol.hasFragRef()) 672 return true; 673 674 // the value of a TLS symbol is the offset to the TLS segment 675 ELFSegment* tls_seg = m_ELFSegmentTable.find(llvm::ELF::PT_TLS, 676 llvm::ELF::PF_R, 0x0); 677 uint64_t value = pSymbol.fragRef()->getOutputOffset(); 678 uint64_t addr = pSymbol.fragRef()->frag()->getParent()->getSection().addr(); 679 pSymbol.setValue(value + addr - tls_seg->vaddr()); 680 return true; 681} 682 683ELFFileFormat* GNULDBackend::getOutputFormat() 684{ 685 switch (config().codeGenType()) { 686 case LinkerConfig::DynObj: 687 assert(NULL != m_pDynObjFileFormat); 688 return m_pDynObjFileFormat; 689 case LinkerConfig::Exec: 690 assert(NULL != m_pExecFileFormat); 691 return m_pExecFileFormat; 692 case LinkerConfig::Object: 693 assert(NULL != m_pObjectFileFormat); 694 return m_pObjectFileFormat; 695 default: 696 fatal(diag::unrecognized_output_file) << config().codeGenType(); 697 return NULL; 698 } 699} 700 701const ELFFileFormat* GNULDBackend::getOutputFormat() const 702{ 703 switch (config().codeGenType()) { 704 case LinkerConfig::DynObj: 705 assert(NULL != m_pDynObjFileFormat); 706 return m_pDynObjFileFormat; 707 case LinkerConfig::Exec: 708 assert(NULL != m_pExecFileFormat); 709 return m_pExecFileFormat; 710 case LinkerConfig::Object: 711 assert(NULL != m_pObjectFileFormat); 712 return m_pObjectFileFormat; 713 default: 714 fatal(diag::unrecognized_output_file) << config().codeGenType(); 715 return NULL; 716 } 717} 718 719void GNULDBackend::partialScanRelocation(Relocation& pReloc, 720 FragmentLinker& pLinker, 721 Module& pModule, 722 const LDSection& pSection) 723{ 724 // if we meet a section symbol 725 if (pReloc.symInfo()->type() == ResolveInfo::Section) { 726 LDSymbol* input_sym = pReloc.symInfo()->outSymbol(); 727 728 // 1. update the relocation target offset 729 assert(input_sym->hasFragRef()); 730 uint64_t offset = input_sym->fragRef()->getOutputOffset(); 731 pReloc.target() += offset; 732 733 // 2. get output section symbol 734 // get the output LDSection which the symbol defined in 735 const LDSection& out_sect = 736 input_sym->fragRef()->frag()->getParent()->getSection(); 737 ResolveInfo* sym_info = pModule.getSectionSymbolSet().get(out_sect)->resolveInfo(); 738 // set relocation target symbol to the output section symbol's resolveInfo 739 pReloc.setSymInfo(sym_info); 740 } 741} 742 743/// sizeNamePools - compute the size of regular name pools 744/// In ELF executable files, regular name pools are .symtab, .strtab, 745/// .dynsym, .dynstr, .hash and .shstrtab. 746void 747GNULDBackend::sizeNamePools(const Module& pModule, bool pIsStaticLink) 748{ 749 // number of entries in symbol tables starts from 1 to hold the special entry 750 // at index 0 (STN_UNDEF). See ELF Spec Book I, p1-21. 751 size_t symtab = 1; 752 size_t dynsym = pIsStaticLink ? 0 : 1; 753 754 // size of string tables starts from 1 to hold the null character in their 755 // first byte 756 size_t strtab = 1; 757 size_t dynstr = pIsStaticLink ? 0 : 1; 758 size_t shstrtab = 1; 759 size_t hash = 0; 760 761 /// compute the size of .symtab, .dynsym and .strtab 762 /// @{ 763 Module::const_sym_iterator symbol; 764 const Module::SymbolTable& symbols = pModule.getSymbolTable(); 765 size_t str_size = 0; 766 // compute the size of symbols in Local and File category 767 Module::const_sym_iterator symEnd = symbols.localEnd(); 768 for (symbol = symbols.localBegin(); symbol != symEnd; ++symbol) { 769 str_size = (*symbol)->nameSize() + 1; 770 if (!pIsStaticLink && isDynamicSymbol(**symbol)) { 771 ++dynsym; 772 if (ResolveInfo::Section != (*symbol)->type()) 773 dynstr += str_size; 774 } 775 ++symtab; 776 if (ResolveInfo::Section != (*symbol)->type()) 777 strtab += str_size; 778 } 779 // compute the size of symbols in TLS category 780 symEnd = symbols.tlsEnd(); 781 for (symbol = symbols.tlsBegin(); symbol != symEnd; ++symbol) { 782 str_size = (*symbol)->nameSize() + 1; 783 if (!pIsStaticLink) { 784 ++dynsym; 785 if (ResolveInfo::Section != (*symbol)->type()) 786 dynstr += str_size; 787 } 788 ++symtab; 789 if (ResolveInfo::Section != (*symbol)->type()) 790 strtab += str_size; 791 } 792 // compute the size of the reset of symbols 793 symEnd = pModule.sym_end(); 794 for (symbol = symbols.tlsEnd(); symbol != symEnd; ++symbol) { 795 str_size = (*symbol)->nameSize() + 1; 796 if (!pIsStaticLink && isDynamicSymbol(**symbol)) { 797 ++dynsym; 798 if (ResolveInfo::Section != (*symbol)->type()) 799 dynstr += str_size; 800 } 801 ++symtab; 802 if (ResolveInfo::Section != (*symbol)->type()) 803 strtab += str_size; 804 } 805 806 ELFFileFormat* file_format = getOutputFormat(); 807 808 switch(config().codeGenType()) { 809 // compute size of .dynstr and .hash 810 case LinkerConfig::DynObj: { 811 // soname 812 if (!pIsStaticLink) 813 dynstr += pModule.name().size() + 1; 814 } 815 /** fall through **/ 816 case LinkerConfig::Exec: { 817 // add DT_NEED strings into .dynstr and .dynamic 818 // Rules: 819 // 1. ignore --no-add-needed 820 // 2. force count in --no-as-needed 821 // 3. judge --as-needed 822 if (!pIsStaticLink) { 823 Module::const_lib_iterator lib, libEnd = pModule.lib_end(); 824 for (lib = pModule.lib_begin(); lib != libEnd; ++lib) { 825 // --add-needed 826 if ((*lib)->attribute()->isAddNeeded()) { 827 // --no-as-needed 828 if (!(*lib)->attribute()->isAsNeeded()) { 829 dynstr += (*lib)->name().size() + 1; 830 dynamic().reserveNeedEntry(); 831 } 832 // --as-needed 833 else if ((*lib)->isNeeded()) { 834 dynstr += (*lib)->name().size() + 1; 835 dynamic().reserveNeedEntry(); 836 } 837 } 838 } 839 840 // compute .hash 841 // Both Elf32_Word and Elf64_Word are 4 bytes 842 hash = (2 + getHashBucketCount(dynsym, false) + dynsym) * 843 sizeof(llvm::ELF::Elf32_Word); 844 } 845 846 // set size 847 if (32 == bitclass()) 848 file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf32_Sym)); 849 else 850 file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf64_Sym)); 851 file_format->getDynStrTab().setSize(dynstr); 852 file_format->getHashTab().setSize(hash); 853 854 } 855 /* fall through */ 856 case LinkerConfig::Object: { 857 if (32 == bitclass()) 858 file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf32_Sym)); 859 else 860 file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf64_Sym)); 861 file_format->getStrTab().setSize(strtab); 862 break; 863 } 864 default: 865 fatal(diag::fatal_illegal_codegen_type) << pModule.name(); 866 break; 867 } // end of switch 868 /// @} 869 870 /// reserve fixed entries in the .dynamic section. 871 /// @{ 872 if (LinkerConfig::DynObj == config().codeGenType() || 873 LinkerConfig::Exec == config().codeGenType()) { 874 // Because some entries in .dynamic section need information of .dynsym, 875 // .dynstr, .symtab, .strtab and .hash, we can not reserve non-DT_NEEDED 876 // entries until we get the size of the sections mentioned above 877 if (!pIsStaticLink) 878 dynamic().reserveEntries(config(), *file_format); 879 file_format->getDynamic().setSize(dynamic().numOfBytes()); 880 } 881 /// @} 882 883 /// compute the size of .shstrtab section. 884 /// @{ 885 Module::const_iterator sect, sectEnd = pModule.end(); 886 for (sect = pModule.begin(); sect != sectEnd; ++sect) { 887 // StackNote sections will always be in output! 888 if (0 != (*sect)->size() || LDFileFormat::StackNote == (*sect)->kind()) { 889 shstrtab += ((*sect)->name().size() + 1); 890 } 891 } 892 shstrtab += (strlen(".shstrtab") + 1); 893 file_format->getShStrTab().setSize(shstrtab); 894 /// @} 895} 896 897/// emitSymbol32 - emit an ELF32 symbol 898void GNULDBackend::emitSymbol32(llvm::ELF::Elf32_Sym& pSym, 899 LDSymbol& pSymbol, 900 char* pStrtab, 901 size_t pStrtabsize, 902 size_t pSymtabIdx) 903{ 904 // FIXME: check the endian between host and target 905 // write out symbol 906 if (ResolveInfo::Section != pSymbol.type()) { 907 pSym.st_name = pStrtabsize; 908 strcpy((pStrtab + pStrtabsize), pSymbol.name()); 909 } 910 else { 911 pSym.st_name = 0; 912 } 913 pSym.st_value = pSymbol.value(); 914 pSym.st_size = getSymbolSize(pSymbol); 915 pSym.st_info = getSymbolInfo(pSymbol); 916 pSym.st_other = pSymbol.visibility(); 917 pSym.st_shndx = getSymbolShndx(pSymbol); 918} 919 920/// emitSymbol64 - emit an ELF64 symbol 921void GNULDBackend::emitSymbol64(llvm::ELF::Elf64_Sym& pSym, 922 LDSymbol& pSymbol, 923 char* pStrtab, 924 size_t pStrtabsize, 925 size_t pSymtabIdx) 926{ 927 // FIXME: check the endian between host and target 928 // write out symbol 929 pSym.st_name = pStrtabsize; 930 pSym.st_value = pSymbol.value(); 931 pSym.st_size = getSymbolSize(pSymbol); 932 pSym.st_info = getSymbolInfo(pSymbol); 933 pSym.st_other = pSymbol.visibility(); 934 pSym.st_shndx = getSymbolShndx(pSymbol); 935 // write out string 936 strcpy((pStrtab + pStrtabsize), pSymbol.name()); 937} 938 939/// emitRegNamePools - emit regular name pools - .symtab, .strtab 940/// 941/// the size of these tables should be computed before layout 942/// layout should computes the start offset of these tables 943void GNULDBackend::emitRegNamePools(const Module& pModule, 944 MemoryArea& pOutput) 945{ 946 ELFFileFormat* file_format = getOutputFormat(); 947 948 LDSection& symtab_sect = file_format->getSymTab(); 949 LDSection& strtab_sect = file_format->getStrTab(); 950 951 MemoryRegion* symtab_region = pOutput.request(symtab_sect.offset(), 952 symtab_sect.size()); 953 MemoryRegion* strtab_region = pOutput.request(strtab_sect.offset(), 954 strtab_sect.size()); 955 956 // set up symtab_region 957 llvm::ELF::Elf32_Sym* symtab32 = NULL; 958 llvm::ELF::Elf64_Sym* symtab64 = NULL; 959 if (32 == bitclass()) 960 symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region->start(); 961 else if (64 == bitclass()) 962 symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region->start(); 963 else 964 llvm::report_fatal_error(llvm::Twine("unsupported bitclass ") + 965 llvm::Twine(bitclass()) + 966 llvm::Twine(".\n")); 967 // set up strtab_region 968 char* strtab = (char*)strtab_region->start(); 969 strtab[0] = '\0'; 970 971 // initialize the first ELF symbol 972 if (32 == bitclass()) { 973 symtab32[0].st_name = 0; 974 symtab32[0].st_value = 0; 975 symtab32[0].st_size = 0; 976 symtab32[0].st_info = 0; 977 symtab32[0].st_other = 0; 978 symtab32[0].st_shndx = 0; 979 } 980 else { // must 64 981 symtab64[0].st_name = 0; 982 symtab64[0].st_value = 0; 983 symtab64[0].st_size = 0; 984 symtab64[0].st_info = 0; 985 symtab64[0].st_other = 0; 986 symtab64[0].st_shndx = 0; 987 } 988 989 bool sym_exist = false; 990 HashTableType::entry_type* entry = NULL; 991 if (LinkerConfig::Object == config().codeGenType()) { 992 entry = m_pSymIndexMap->insert(NULL, sym_exist); 993 entry->setValue(0); 994 } 995 996 size_t symtabIdx = 1; 997 size_t strtabsize = 1; 998 // compute size of .symtab, .dynsym and .strtab 999 Module::const_sym_iterator symbol; 1000 Module::const_sym_iterator symEnd = pModule.sym_end(); 1001 for (symbol = pModule.sym_begin(); symbol != symEnd; ++symbol) { 1002 // maintain output's symbol and index map if building .o file 1003 if (LinkerConfig::Object == config().codeGenType()) { 1004 entry = m_pSymIndexMap->insert(*symbol, sym_exist); 1005 entry->setValue(symtabIdx); 1006 } 1007 1008 if (32 == bitclass()) 1009 emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize, 1010 symtabIdx); 1011 else 1012 emitSymbol64(symtab64[symtabIdx], **symbol, strtab, strtabsize, 1013 symtabIdx); 1014 1015 // sum up counters 1016 ++symtabIdx; 1017 if (ResolveInfo::Section != (*symbol)->type()) 1018 strtabsize += (*symbol)->nameSize() + 1; 1019 } 1020} 1021 1022/// emitDynNamePools - emit dynamic name pools - .dyntab, .dynstr, .hash 1023/// 1024/// the size of these tables should be computed before layout 1025/// layout should computes the start offset of these tables 1026void GNULDBackend::emitDynNamePools(const Module& pModule, 1027 MemoryArea& pOutput) 1028{ 1029 ELFFileFormat* file_format = getOutputFormat(); 1030 if (!file_format->hasDynSymTab() || 1031 !file_format->hasDynStrTab() || 1032 !file_format->hasHashTab() || 1033 !file_format->hasDynamic()) 1034 return; 1035 1036 bool sym_exist = false; 1037 HashTableType::entry_type* entry = 0; 1038 1039 LDSection& symtab_sect = file_format->getDynSymTab(); 1040 LDSection& strtab_sect = file_format->getDynStrTab(); 1041 LDSection& hash_sect = file_format->getHashTab(); 1042 LDSection& dyn_sect = file_format->getDynamic(); 1043 1044 MemoryRegion* symtab_region = pOutput.request(symtab_sect.offset(), 1045 symtab_sect.size()); 1046 MemoryRegion* strtab_region = pOutput.request(strtab_sect.offset(), 1047 strtab_sect.size()); 1048 MemoryRegion* hash_region = pOutput.request(hash_sect.offset(), 1049 hash_sect.size()); 1050 MemoryRegion* dyn_region = pOutput.request(dyn_sect.offset(), 1051 dyn_sect.size()); 1052 // set up symtab_region 1053 llvm::ELF::Elf32_Sym* symtab32 = NULL; 1054 llvm::ELF::Elf64_Sym* symtab64 = NULL; 1055 if (32 == bitclass()) 1056 symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region->start(); 1057 else if (64 == bitclass()) 1058 symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region->start(); 1059 else 1060 llvm::report_fatal_error(llvm::Twine("unsupported bitclass ") + 1061 llvm::Twine(bitclass()) + 1062 llvm::Twine(".\n")); 1063 1064 // initialize the first ELF symbol 1065 if (32 == bitclass()) { 1066 symtab32[0].st_name = 0; 1067 symtab32[0].st_value = 0; 1068 symtab32[0].st_size = 0; 1069 symtab32[0].st_info = 0; 1070 symtab32[0].st_other = 0; 1071 symtab32[0].st_shndx = 0; 1072 } 1073 else { // must 64 1074 symtab64[0].st_name = 0; 1075 symtab64[0].st_value = 0; 1076 symtab64[0].st_size = 0; 1077 symtab64[0].st_info = 0; 1078 symtab64[0].st_other = 0; 1079 symtab64[0].st_shndx = 0; 1080 } 1081 // set up strtab_region 1082 char* strtab = (char*)strtab_region->start(); 1083 strtab[0] = '\0'; 1084 1085 // add the first symbol into m_pSymIndexMap 1086 entry = m_pSymIndexMap->insert(NULL, sym_exist); 1087 entry->setValue(0); 1088 1089 size_t symtabIdx = 1; 1090 size_t strtabsize = 1; 1091 1092 // emit of .dynsym, and .dynstr 1093 Module::const_sym_iterator symbol; 1094 const Module::SymbolTable& symbols = pModule.getSymbolTable(); 1095 // emit symbol in File and Local category if it's dynamic symbol 1096 Module::const_sym_iterator symEnd = symbols.localEnd(); 1097 for (symbol = symbols.localBegin(); symbol != symEnd; ++symbol) { 1098 if (!isDynamicSymbol(**symbol)) 1099 continue; 1100 1101 if (32 == bitclass()) 1102 emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize, 1103 symtabIdx); 1104 else 1105 emitSymbol64(symtab64[symtabIdx], **symbol, strtab, strtabsize, 1106 symtabIdx); 1107 1108 // maintain output's symbol and index map 1109 entry = m_pSymIndexMap->insert(*symbol, sym_exist); 1110 entry->setValue(symtabIdx); 1111 // sum up counters 1112 ++symtabIdx; 1113 if (ResolveInfo::Section != (*symbol)->type()) 1114 strtabsize += (*symbol)->nameSize() + 1; 1115 } 1116 1117 // emit symbols in TLS category, all symbols in TLS category shold be emitited 1118 symEnd = symbols.tlsEnd(); 1119 for (symbol = symbols.tlsBegin(); symbol != symEnd; ++symbol) { 1120 if (32 == bitclass()) 1121 emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize, 1122 symtabIdx); 1123 else 1124 emitSymbol64(symtab64[symtabIdx], **symbol, strtab, strtabsize, 1125 symtabIdx); 1126 1127 // maintain output's symbol and index map 1128 entry = m_pSymIndexMap->insert(*symbol, sym_exist); 1129 entry->setValue(symtabIdx); 1130 // sum up counters 1131 ++symtabIdx; 1132 if (ResolveInfo::Section != (*symbol)->type()) 1133 strtabsize += (*symbol)->nameSize() + 1; 1134 } 1135 1136 // emit the reset of the symbols if the symbol is dynamic symbol 1137 symEnd = pModule.sym_end(); 1138 for (symbol = symbols.tlsEnd(); symbol != symEnd; ++symbol) { 1139 if (!isDynamicSymbol(**symbol)) 1140 continue; 1141 1142 if (32 == bitclass()) 1143 emitSymbol32(symtab32[symtabIdx], **symbol, strtab, strtabsize, 1144 symtabIdx); 1145 else 1146 emitSymbol64(symtab64[symtabIdx], **symbol, strtab, strtabsize, 1147 symtabIdx); 1148 1149 // maintain output's symbol and index map 1150 entry = m_pSymIndexMap->insert(*symbol, sym_exist); 1151 entry->setValue(symtabIdx); 1152 // sum up counters 1153 ++symtabIdx; 1154 if (ResolveInfo::Section != (*symbol)->type()) 1155 strtabsize += (*symbol)->nameSize() + 1; 1156 } 1157 1158 // emit DT_NEED 1159 // add DT_NEED strings into .dynstr 1160 // Rules: 1161 // 1. ignore --no-add-needed 1162 // 2. force count in --no-as-needed 1163 // 3. judge --as-needed 1164 ELFDynamic::iterator dt_need = dynamic().needBegin(); 1165 Module::const_lib_iterator lib, libEnd = pModule.lib_end(); 1166 for (lib = pModule.lib_begin(); lib != libEnd; ++lib) { 1167 // --add-needed 1168 if ((*lib)->attribute()->isAddNeeded()) { 1169 // --no-as-needed 1170 if (!(*lib)->attribute()->isAsNeeded()) { 1171 strcpy((strtab + strtabsize), (*lib)->name().c_str()); 1172 (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize); 1173 strtabsize += (*lib)->name().size() + 1; 1174 ++dt_need; 1175 } 1176 // --as-needed 1177 else if ((*lib)->isNeeded()) { 1178 strcpy((strtab + strtabsize), (*lib)->name().c_str()); 1179 (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize); 1180 strtabsize += (*lib)->name().size() + 1; 1181 ++dt_need; 1182 } 1183 } 1184 } 1185 1186 // initialize value of ELF .dynamic section 1187 if (LinkerConfig::DynObj == config().codeGenType()) { 1188 // set pointer to SONAME entry in dynamic string table. 1189 dynamic().applySoname(strtabsize); 1190 } 1191 dynamic().applyEntries(config(), *file_format); 1192 dynamic().emit(dyn_sect, *dyn_region); 1193 1194 // emit soname 1195 if (LinkerConfig::DynObj == config().codeGenType()) { 1196 strcpy((strtab + strtabsize), pModule.name().c_str()); 1197 strtabsize += pModule.name().size() + 1; 1198 } 1199 // emit hash table 1200 // FIXME: this verion only emit SVR4 hash section. 1201 // Please add GNU new hash section 1202 1203 // both 32 and 64 bits hash table use 32-bit entry 1204 // set up hash_region 1205 uint32_t* word_array = (uint32_t*)hash_region->start(); 1206 uint32_t& nbucket = word_array[0]; 1207 uint32_t& nchain = word_array[1]; 1208 1209 nbucket = getHashBucketCount(symtabIdx, false); 1210 nchain = symtabIdx; 1211 1212 uint32_t* bucket = (word_array + 2); 1213 uint32_t* chain = (bucket + nbucket); 1214 1215 // initialize bucket 1216 bzero((void*)bucket, nbucket); 1217 1218 StringHash<ELF> hash_func; 1219 1220 if (32 == bitclass()) { 1221 for (size_t sym_idx=0; sym_idx < symtabIdx; ++sym_idx) { 1222 llvm::StringRef name(strtab + symtab32[sym_idx].st_name); 1223 size_t bucket_pos = hash_func(name) % nbucket; 1224 chain[sym_idx] = bucket[bucket_pos]; 1225 bucket[bucket_pos] = sym_idx; 1226 } 1227 } 1228 else if (64 == bitclass()) { 1229 for (size_t sym_idx=0; sym_idx < symtabIdx; ++sym_idx) { 1230 llvm::StringRef name(strtab + symtab64[sym_idx].st_name); 1231 size_t bucket_pos = hash_func(name) % nbucket; 1232 chain[sym_idx] = bucket[bucket_pos]; 1233 bucket[bucket_pos] = sym_idx; 1234 } 1235 } 1236} 1237 1238/// sizeInterp - compute the size of the .interp section 1239void GNULDBackend::sizeInterp() 1240{ 1241 const char* dyld_name; 1242 if (config().options().hasDyld()) 1243 dyld_name = config().options().dyld().c_str(); 1244 else 1245 dyld_name = dyld(); 1246 1247 LDSection& interp = getOutputFormat()->getInterp(); 1248 interp.setSize(std::strlen(dyld_name) + 1); 1249} 1250 1251/// emitInterp - emit the .interp 1252void GNULDBackend::emitInterp(MemoryArea& pOutput) 1253{ 1254 if (getOutputFormat()->hasInterp()) { 1255 const LDSection& interp = getOutputFormat()->getInterp(); 1256 MemoryRegion *region = pOutput.request(interp.offset(), interp.size()); 1257 const char* dyld_name; 1258 if (config().options().hasDyld()) 1259 dyld_name = config().options().dyld().c_str(); 1260 else 1261 dyld_name = dyld(); 1262 1263 std::memcpy(region->start(), dyld_name, interp.size()); 1264 } 1265} 1266 1267/// getSectionOrder 1268unsigned int GNULDBackend::getSectionOrder(const LDSection& pSectHdr) const 1269{ 1270 const ELFFileFormat* file_format = getOutputFormat(); 1271 1272 // NULL section should be the "1st" section 1273 if (LDFileFormat::Null == pSectHdr.kind()) 1274 return 0; 1275 1276 if (&pSectHdr == &file_format->getStrTab()) 1277 return SHO_STRTAB; 1278 1279 // if the section is not ALLOC, lay it out until the last possible moment 1280 if (0 == (pSectHdr.flag() & llvm::ELF::SHF_ALLOC)) 1281 return SHO_UNDEFINED; 1282 1283 bool is_write = (pSectHdr.flag() & llvm::ELF::SHF_WRITE) != 0; 1284 bool is_exec = (pSectHdr.flag() & llvm::ELF::SHF_EXECINSTR) != 0; 1285 // TODO: need to take care other possible output sections 1286 switch (pSectHdr.kind()) { 1287 case LDFileFormat::Regular: 1288 if (is_exec) { 1289 if (&pSectHdr == &file_format->getInit()) 1290 return SHO_INIT; 1291 if (&pSectHdr == &file_format->getFini()) 1292 return SHO_FINI; 1293 return SHO_TEXT; 1294 } else if (!is_write) { 1295 return SHO_RO; 1296 } else { 1297 if (config().options().hasRelro()) { 1298 if (&pSectHdr == &file_format->getPreInitArray() || 1299 &pSectHdr == &file_format->getInitArray() || 1300 &pSectHdr == &file_format->getFiniArray() || 1301 &pSectHdr == &file_format->getCtors() || 1302 &pSectHdr == &file_format->getDtors() || 1303 &pSectHdr == &file_format->getJCR() || 1304 0 == pSectHdr.name().compare(".data.rel.ro")) 1305 return SHO_RELRO; 1306 if (0 == pSectHdr.name().compare(".data.rel.ro.local")) 1307 return SHO_RELRO_LOCAL; 1308 } 1309 if ((pSectHdr.flag() & llvm::ELF::SHF_TLS) != 0x0) { 1310 return SHO_TLS_DATA; 1311 } 1312 return SHO_DATA; 1313 } 1314 1315 case LDFileFormat::BSS: 1316 if ((pSectHdr.flag() & llvm::ELF::SHF_TLS) != 0x0) 1317 return SHO_TLS_BSS; 1318 return SHO_BSS; 1319 1320 case LDFileFormat::NamePool: { 1321 if (&pSectHdr == &file_format->getDynamic()) 1322 return SHO_RELRO; 1323 return SHO_NAMEPOOL; 1324 } 1325 case LDFileFormat::Relocation: 1326 if (&pSectHdr == &file_format->getRelPlt() || 1327 &pSectHdr == &file_format->getRelaPlt()) 1328 return SHO_REL_PLT; 1329 return SHO_RELOCATION; 1330 1331 // get the order from target for target specific sections 1332 case LDFileFormat::Target: 1333 return getTargetSectionOrder(pSectHdr); 1334 1335 // handle .interp 1336 case LDFileFormat::Note: 1337 return SHO_INTERP; 1338 1339 case LDFileFormat::EhFrame: 1340 case LDFileFormat::EhFrameHdr: 1341 case LDFileFormat::GCCExceptTable: 1342 return SHO_EXCEPTION; 1343 1344 case LDFileFormat::MetaData: 1345 case LDFileFormat::Debug: 1346 default: 1347 return SHO_UNDEFINED; 1348 } 1349} 1350 1351/// getSymbolSize 1352uint64_t GNULDBackend::getSymbolSize(const LDSymbol& pSymbol) const 1353{ 1354 // @ref Google gold linker: symtab.cc: 2780 1355 // undefined and dynamic symbols should have zero size. 1356 if (pSymbol.isDyn() || pSymbol.desc() == ResolveInfo::Undefined) 1357 return 0x0; 1358 return pSymbol.resolveInfo()->size(); 1359} 1360 1361/// getSymbolInfo 1362uint64_t GNULDBackend::getSymbolInfo(const LDSymbol& pSymbol) const 1363{ 1364 // set binding 1365 uint8_t bind = 0x0; 1366 if (pSymbol.resolveInfo()->isLocal()) 1367 bind = llvm::ELF::STB_LOCAL; 1368 else if (pSymbol.resolveInfo()->isGlobal()) 1369 bind = llvm::ELF::STB_GLOBAL; 1370 else if (pSymbol.resolveInfo()->isWeak()) 1371 bind = llvm::ELF::STB_WEAK; 1372 else if (pSymbol.resolveInfo()->isAbsolute()) { 1373 // (Luba) Is a absolute but not global (weak or local) symbol meaningful? 1374 bind = llvm::ELF::STB_GLOBAL; 1375 } 1376 1377 if (pSymbol.visibility() == llvm::ELF::STV_INTERNAL || 1378 pSymbol.visibility() == llvm::ELF::STV_HIDDEN) 1379 bind = llvm::ELF::STB_LOCAL; 1380 1381 uint32_t type = pSymbol.resolveInfo()->type(); 1382 // if the IndirectFunc symbol (i.e., STT_GNU_IFUNC) is from dynobj, change 1383 // its type to Function 1384 if (type == ResolveInfo::IndirectFunc && pSymbol.isDyn()) 1385 type = ResolveInfo::Function; 1386 return (type | (bind << 4)); 1387} 1388 1389/// getSymbolValue - this function is called after layout() 1390uint64_t GNULDBackend::getSymbolValue(const LDSymbol& pSymbol) const 1391{ 1392 if (pSymbol.isDyn()) 1393 return 0x0; 1394 1395 return pSymbol.value(); 1396} 1397 1398/// getSymbolShndx - this function is called after layout() 1399uint64_t 1400GNULDBackend::getSymbolShndx(const LDSymbol& pSymbol) const 1401{ 1402 if (pSymbol.resolveInfo()->isAbsolute()) 1403 return llvm::ELF::SHN_ABS; 1404 if (pSymbol.resolveInfo()->isCommon()) 1405 return llvm::ELF::SHN_COMMON; 1406 if (pSymbol.resolveInfo()->isUndef() || pSymbol.isDyn()) 1407 return llvm::ELF::SHN_UNDEF; 1408 1409 if (pSymbol.resolveInfo()->isLocal()) { 1410 switch (pSymbol.type()) { 1411 case ResolveInfo::NoType: 1412 case ResolveInfo::File: 1413 return llvm::ELF::SHN_ABS; 1414 } 1415 } 1416 1417 if (pSymbol.resolveInfo()->isDefine() && !pSymbol.hasFragRef()) 1418 return llvm::ELF::SHN_ABS; 1419 1420 assert(pSymbol.hasFragRef() && "symbols must have fragment reference to get its index"); 1421 return pSymbol.fragRef()->frag()->getParent()->getSection().index(); 1422} 1423 1424/// getSymbolIdx - called by emitRelocation to get the ouput symbol table index 1425size_t GNULDBackend::getSymbolIdx(LDSymbol* pSymbol) const 1426{ 1427 HashTableType::iterator entry = m_pSymIndexMap->find(pSymbol); 1428 return entry.getEntry()->value(); 1429} 1430 1431/// allocateCommonSymbols - allocate common symbols in the corresponding 1432/// sections. This is executed at pre-layout stage. 1433/// @refer Google gold linker: common.cc: 214 1434bool 1435GNULDBackend::allocateCommonSymbols(Module& pModule) 1436{ 1437 SymbolCategory& symbol_list = pModule.getSymbolTable(); 1438 1439 if (symbol_list.emptyCommons() && symbol_list.emptyLocals()) 1440 return true; 1441 1442 SymbolCategory::iterator com_sym, com_end; 1443 1444 // FIXME: If the order of common symbols is defined, then sort common symbols 1445 // std::sort(com_sym, com_end, some kind of order); 1446 1447 // get corresponding BSS LDSection 1448 ELFFileFormat* file_format = getOutputFormat(); 1449 LDSection& bss_sect = file_format->getBSS(); 1450 LDSection& tbss_sect = file_format->getTBSS(); 1451 1452 // get or create corresponding BSS SectionData 1453 SectionData* bss_sect_data = NULL; 1454 if (bss_sect.hasSectionData()) 1455 bss_sect_data = bss_sect.getSectionData(); 1456 else 1457 bss_sect_data = IRBuilder::CreateSectionData(bss_sect); 1458 1459 SectionData* tbss_sect_data = NULL; 1460 if (tbss_sect.hasSectionData()) 1461 tbss_sect_data = tbss_sect.getSectionData(); 1462 else 1463 tbss_sect_data = IRBuilder::CreateSectionData(tbss_sect); 1464 1465 // remember original BSS size 1466 uint64_t bss_offset = bss_sect.size(); 1467 uint64_t tbss_offset = tbss_sect.size(); 1468 1469 // allocate all local common symbols 1470 com_end = symbol_list.localEnd(); 1471 1472 for (com_sym = symbol_list.localBegin(); com_sym != com_end; ++com_sym) { 1473 if (ResolveInfo::Common == (*com_sym)->desc()) { 1474 // We have to reset the description of the symbol here. When doing 1475 // incremental linking, the output relocatable object may have common 1476 // symbols. Therefore, we can not treat common symbols as normal symbols 1477 // when emitting the regular name pools. We must change the symbols' 1478 // description here. 1479 (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define); 1480 Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size()); 1481 (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0)); 1482 1483 if (ResolveInfo::ThreadLocal == (*com_sym)->type()) { 1484 // allocate TLS common symbol in tbss section 1485 tbss_offset += ObjectBuilder::AppendFragment(*frag, 1486 *tbss_sect_data, 1487 (*com_sym)->value()); 1488 } 1489 else { 1490 bss_offset += ObjectBuilder::AppendFragment(*frag, 1491 *bss_sect_data, 1492 (*com_sym)->value()); 1493 } 1494 } 1495 } 1496 1497 // allocate all global common symbols 1498 com_end = symbol_list.commonEnd(); 1499 for (com_sym = symbol_list.commonBegin(); com_sym != com_end; ++com_sym) { 1500 // We have to reset the description of the symbol here. When doing 1501 // incremental linking, the output relocatable object may have common 1502 // symbols. Therefore, we can not treat common symbols as normal symbols 1503 // when emitting the regular name pools. We must change the symbols' 1504 // description here. 1505 (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define); 1506 Fragment* frag = new FillFragment(0x0, 1, (*com_sym)->size()); 1507 (*com_sym)->setFragmentRef(FragmentRef::Create(*frag, 0)); 1508 1509 if (ResolveInfo::ThreadLocal == (*com_sym)->type()) { 1510 // allocate TLS common symbol in tbss section 1511 tbss_offset += ObjectBuilder::AppendFragment(*frag, 1512 *tbss_sect_data, 1513 (*com_sym)->value()); 1514 } 1515 else { 1516 bss_offset += ObjectBuilder::AppendFragment(*frag, 1517 *bss_sect_data, 1518 (*com_sym)->value()); 1519 } 1520 } 1521 1522 bss_sect.setSize(bss_offset); 1523 tbss_sect.setSize(tbss_offset); 1524 symbol_list.changeCommonsToGlobal(); 1525 return true; 1526} 1527 1528 1529/// createProgramHdrs - base on output sections to create the program headers 1530void GNULDBackend::createProgramHdrs(Module& pModule, 1531 const FragmentLinker& pLinker) 1532{ 1533 ELFFileFormat *file_format = getOutputFormat(); 1534 1535 // make PT_PHDR 1536 m_ELFSegmentTable.produce(llvm::ELF::PT_PHDR); 1537 1538 // make PT_INTERP 1539 if (file_format->hasInterp()) { 1540 ELFSegment* interp_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_INTERP); 1541 interp_seg->addSection(&file_format->getInterp()); 1542 } 1543 1544 uint32_t cur_flag, prev_flag = getSegmentFlag(0); 1545 ELFSegment* load_seg = NULL; 1546 // make possible PT_LOAD segments 1547 Module::iterator sect, sect_end = pModule.end(); 1548 for (sect = pModule.begin(); sect != sect_end; ++sect) { 1549 1550 if (0 == ((*sect)->flag() & llvm::ELF::SHF_ALLOC) && 1551 LDFileFormat::Null != (*sect)->kind()) 1552 continue; 1553 1554 cur_flag = getSegmentFlag((*sect)->flag()); 1555 bool createPT_LOAD = false; 1556 if (LDFileFormat::Null == (*sect)->kind()) { 1557 // 1. create text segment 1558 createPT_LOAD = true; 1559 } 1560 else if (!config().options().omagic() && 1561 (prev_flag & llvm::ELF::PF_W) ^ (cur_flag & llvm::ELF::PF_W)) { 1562 // 2. create data segment if w/o omagic set 1563 createPT_LOAD = true; 1564 } 1565 else if ((*sect)->kind() == LDFileFormat::BSS && 1566 load_seg->isDataSegment() && 1567 config().scripts().addressMap().find(".bss") != 1568 (config().scripts().addressMap().end())) { 1569 // 3. create bss segment if w/ -Tbss and there is a data segment 1570 createPT_LOAD = true; 1571 } 1572 else { 1573 if ((*sect != &(file_format->getText())) && 1574 (*sect != &(file_format->getData())) && 1575 (*sect != &(file_format->getBSS())) && 1576 (config().scripts().addressMap().find((*sect)->name()) != 1577 config().scripts().addressMap().end())) 1578 // 4. create PT_LOAD for sections in address map except for text, data, 1579 // and bss 1580 createPT_LOAD = true; 1581 } 1582 1583 if (createPT_LOAD) { 1584 // create new PT_LOAD segment 1585 load_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_LOAD, cur_flag); 1586 load_seg->setAlign(abiPageSize()); 1587 } 1588 1589 assert(NULL != load_seg); 1590 load_seg->addSection((*sect)); 1591 if (cur_flag != prev_flag) 1592 load_seg->updateFlag(cur_flag); 1593 1594 prev_flag = cur_flag; 1595 } 1596 1597 // make PT_DYNAMIC 1598 if (file_format->hasDynamic()) { 1599 ELFSegment* dyn_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_DYNAMIC, 1600 llvm::ELF::PF_R | 1601 llvm::ELF::PF_W); 1602 dyn_seg->addSection(&file_format->getDynamic()); 1603 } 1604 1605 if (config().options().hasRelro()) { 1606 // make PT_GNU_RELRO 1607 ELFSegment* relro_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_RELRO); 1608 for (ELFSegmentFactory::iterator seg = elfSegmentTable().begin(), 1609 segEnd = elfSegmentTable().end(); seg != segEnd; ++seg) { 1610 if (llvm::ELF::PT_LOAD != (*seg).type()) 1611 continue; 1612 1613 for (ELFSegment::sect_iterator sect = (*seg).begin(), 1614 sectEnd = (*seg).end(); sect != sectEnd; ++sect) { 1615 unsigned int order = getSectionOrder(**sect); 1616 if (SHO_RELRO_LOCAL == order || 1617 SHO_RELRO == order || 1618 SHO_RELRO_LAST == order) { 1619 relro_seg->addSection(*sect); 1620 } 1621 } 1622 } 1623 } 1624 1625 // make PT_GNU_EH_FRAME 1626 if (file_format->hasEhFrameHdr()) { 1627 ELFSegment* eh_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_EH_FRAME); 1628 eh_seg->addSection(&file_format->getEhFrameHdr()); 1629 } 1630 1631 // make PT_TLS 1632 if (file_format->hasTData() || file_format->hasTBSS()) { 1633 ELFSegment* tls_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_TLS); 1634 if (file_format->hasTData()) 1635 tls_seg->addSection(&file_format->getTData()); 1636 if (file_format->hasTBSS()) 1637 tls_seg->addSection(&file_format->getTBSS()); 1638 } 1639 1640 // make PT_GNU_STACK 1641 if (file_format->hasStackNote()) { 1642 m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_STACK, 1643 llvm::ELF::PF_R | 1644 llvm::ELF::PF_W | 1645 getSegmentFlag(file_format->getStackNote().flag())); 1646 } 1647 1648 // create target dependent segments 1649 doCreateProgramHdrs(pModule, pLinker); 1650} 1651 1652/// setupProgramHdrs - set up the attributes of segments 1653void GNULDBackend::setupProgramHdrs(const FragmentLinker& pLinker) 1654{ 1655 // update segment info 1656 ELFSegmentFactory::iterator seg, seg_end = m_ELFSegmentTable.end(); 1657 for (seg = m_ELFSegmentTable.begin(); seg != seg_end; ++seg) { 1658 ELFSegment& segment = *seg; 1659 1660 // update PT_PHDR 1661 if (llvm::ELF::PT_PHDR == segment.type()) { 1662 uint64_t offset, phdr_size; 1663 if (32 == bitclass()) { 1664 offset = sizeof(llvm::ELF::Elf32_Ehdr); 1665 phdr_size = sizeof(llvm::ELF::Elf32_Phdr); 1666 } 1667 else { 1668 offset = sizeof(llvm::ELF::Elf64_Ehdr); 1669 phdr_size = sizeof(llvm::ELF::Elf64_Phdr); 1670 } 1671 segment.setOffset(offset); 1672 segment.setVaddr(segmentStartAddr(pLinker) + offset); 1673 segment.setPaddr(segment.vaddr()); 1674 segment.setFilesz(numOfSegments() * phdr_size); 1675 segment.setMemsz(numOfSegments() * phdr_size); 1676 segment.setAlign(bitclass() / 8); 1677 continue; 1678 } 1679 1680 // bypass if there is no section in this segment (e.g., PT_GNU_STACK) 1681 if (segment.numOfSections() == 0) 1682 continue; 1683 1684 segment.setOffset(segment.front()->offset()); 1685 if (llvm::ELF::PT_LOAD == segment.type() && 1686 LDFileFormat::Null == segment.front()->kind()) 1687 segment.setVaddr(segmentStartAddr(pLinker)); 1688 else 1689 segment.setVaddr(segment.front()->addr()); 1690 segment.setPaddr(segment.vaddr()); 1691 1692 const LDSection* last_sect = segment.back(); 1693 assert(NULL != last_sect); 1694 uint64_t file_size = last_sect->offset() - segment.offset(); 1695 if (LDFileFormat::BSS != last_sect->kind()) 1696 file_size += last_sect->size(); 1697 segment.setFilesz(file_size); 1698 1699 segment.setMemsz(last_sect->addr() - segment.vaddr() + last_sect->size()); 1700 } 1701} 1702 1703/// setupGNUStackInfo - setup the section flag of .note.GNU-stack in output 1704/// @ref gold linker: layout.cc:2608 1705void GNULDBackend::setupGNUStackInfo(Module& pModule, FragmentLinker& pLinker) 1706{ 1707 uint32_t flag = 0x0; 1708 if (config().options().hasStackSet()) { 1709 // 1. check the command line option (-z execstack or -z noexecstack) 1710 if (config().options().hasExecStack()) 1711 flag = llvm::ELF::SHF_EXECINSTR; 1712 } 1713 else { 1714 // 2. check the stack info from the input objects 1715 // FIXME: since we alway emit .note.GNU-stack in output now, we may be able 1716 // to check this from the output .note.GNU-stack directly after section 1717 // merging is done 1718 size_t object_count = 0, stack_note_count = 0; 1719 Module::const_obj_iterator obj, objEnd = pModule.obj_end(); 1720 for (obj = pModule.obj_begin(); obj != objEnd; ++obj) { 1721 ++object_count; 1722 const LDSection* sect = (*obj)->context()->getSection(".note.GNU-stack"); 1723 if (NULL != sect) { 1724 ++stack_note_count; 1725 // 2.1 found a stack note that is set as executable 1726 if (0 != (llvm::ELF::SHF_EXECINSTR & sect->flag())) { 1727 flag = llvm::ELF::SHF_EXECINSTR; 1728 break; 1729 } 1730 } 1731 } 1732 1733 // 2.2 there are no stack note sections in all input objects 1734 if (0 == stack_note_count) 1735 return; 1736 1737 // 2.3 a special case. Use the target default to decide if the stack should 1738 // be executable 1739 if (llvm::ELF::SHF_EXECINSTR != flag && object_count != stack_note_count) 1740 if (isDefaultExecStack()) 1741 flag = llvm::ELF::SHF_EXECINSTR; 1742 } 1743 1744 if (getOutputFormat()->hasStackNote()) { 1745 getOutputFormat()->getStackNote().setFlag(flag); 1746 } 1747} 1748 1749/// setupRelro - setup the offset constraint of PT_RELRO 1750void GNULDBackend::setupRelro(Module& pModule) 1751{ 1752 assert(config().options().hasRelro()); 1753 // if -z relro is given, we need to adjust sections' offset again, and let 1754 // PT_GNU_RELRO end on a common page boundary 1755 1756 Module::iterator sect = pModule.begin(); 1757 for (Module::iterator sect_end = pModule.end(); sect != sect_end; ++sect) { 1758 // find the first non-relro section 1759 if (getSectionOrder(**sect) > SHO_RELRO_LAST) 1760 break; 1761 } 1762 1763 // align the first non-relro section to page boundary 1764 uint64_t offset = (*sect)->offset(); 1765 alignAddress(offset, commonPageSize()); 1766 (*sect)->setOffset(offset); 1767 1768 // It seems that compiler think .got and .got.plt are continuous (w/o any 1769 // padding between). If .got is the last section in PT_RELRO and it's not 1770 // continuous to its next section (i.e. .got.plt), we need to add padding 1771 // in front of .got instead. 1772 // FIXME: Maybe we can handle this in a more general way. 1773 LDSection& got = getOutputFormat()->getGOT(); 1774 if ((getSectionOrder(got) == SHO_RELRO_LAST) && 1775 (got.offset() + got.size() != offset)) { 1776 got.setOffset(offset - got.size()); 1777 } 1778 1779 // set up remaining section's offset 1780 setOutputSectionOffset(pModule, ++sect, pModule.end()); 1781} 1782 1783/// setOutputSectionOffset - helper function to set a group of output sections' 1784/// offset, and set pSectBegin to pStartOffset if pStartOffset is not -1U. 1785void GNULDBackend::setOutputSectionOffset(Module& pModule, 1786 Module::iterator pSectBegin, 1787 Module::iterator pSectEnd, 1788 uint64_t pStartOffset) 1789{ 1790 if (pSectBegin == pModule.end()) 1791 return; 1792 1793 assert(pSectEnd == pModule.end() || 1794 (pSectEnd != pModule.end() && 1795 (*pSectBegin)->index() <= (*pSectEnd)->index())); 1796 1797 if (pStartOffset != -1U) { 1798 (*pSectBegin)->setOffset(pStartOffset); 1799 ++pSectBegin; 1800 } 1801 1802 // set up the "cur" and "prev" iterator 1803 Module::iterator cur = pSectBegin; 1804 Module::iterator prev = pSectBegin; 1805 if (cur != pModule.begin()) 1806 --prev; 1807 else 1808 ++cur; 1809 1810 for (; cur != pSectEnd; ++cur, ++prev) { 1811 uint64_t offset = 0x0; 1812 switch ((*prev)->kind()) { 1813 case LDFileFormat::Null: 1814 offset = sectionStartOffset(); 1815 break; 1816 case LDFileFormat::BSS: 1817 offset = (*prev)->offset(); 1818 break; 1819 default: 1820 offset = (*prev)->offset() + (*prev)->size(); 1821 break; 1822 } 1823 1824 alignAddress(offset, (*cur)->align()); 1825 (*cur)->setOffset(offset); 1826 } 1827} 1828 1829/// setOutputSectionOffset - helper function to set output sections' address 1830void GNULDBackend::setOutputSectionAddress(FragmentLinker& pLinker, 1831 Module& pModule, 1832 Module::iterator pSectBegin, 1833 Module::iterator pSectEnd) 1834{ 1835 if (pSectBegin == pModule.end()) 1836 return; 1837 1838 assert(pSectEnd == pModule.end() || 1839 (pSectEnd != pModule.end() && 1840 (*pSectBegin)->index() <= (*pSectEnd)->index())); 1841 1842 for (ELFSegmentFactory::iterator seg = elfSegmentTable().begin(), 1843 segEnd = elfSegmentTable().end(), prev = elfSegmentTable().end(); 1844 seg != segEnd; prev = seg, ++seg) { 1845 if (llvm::ELF::PT_LOAD != (*seg).type()) 1846 continue; 1847 1848 uint64_t start_addr = 0x0; 1849 ScriptOptions::AddressMap::const_iterator mapping; 1850 if ((*seg).front()->kind() == LDFileFormat::Null) 1851 mapping = config().scripts().addressMap().find(".text"); 1852 else if ((*seg).isDataSegment()) 1853 mapping = config().scripts().addressMap().find(".data"); 1854 else if ((*seg).isBssSegment()) 1855 mapping = config().scripts().addressMap().find(".bss"); 1856 else 1857 mapping = config().scripts().addressMap().find((*seg).front()->name()); 1858 1859 if (mapping != config().scripts().addressMap().end()) { 1860 // check address mapping 1861 start_addr = mapping.getEntry()->value(); 1862 const uint64_t remainder = start_addr % abiPageSize(); 1863 if (remainder != (*seg).front()->offset() % abiPageSize()) { 1864 uint64_t padding = abiPageSize() + remainder - 1865 (*seg).front()->offset() % abiPageSize(); 1866 setOutputSectionOffset(pModule, 1867 pModule.begin() + (*seg).front()->index(), 1868 pModule.end(), 1869 (*seg).front()->offset() + padding); 1870 if (config().options().hasRelro()) 1871 setupRelro(pModule); 1872 } 1873 } 1874 else { 1875 if ((*seg).front()->kind() == LDFileFormat::Null) { 1876 // 1st PT_LOAD 1877 start_addr = segmentStartAddr(pLinker); 1878 } 1879 else if ((*prev).front()->kind() == LDFileFormat::Null) { 1880 // prev segment is 1st PT_LOAD 1881 start_addr = segmentStartAddr(pLinker) + (*seg).front()->offset(); 1882 } 1883 else { 1884 // Others 1885 start_addr = (*prev).front()->addr() + (*seg).front()->offset(); 1886 } 1887 1888 // padding 1889 if (((*seg).front()->offset() & (abiPageSize() - 1)) != 0) 1890 start_addr += abiPageSize(); 1891 } 1892 1893 for (ELFSegment::sect_iterator sect = (*seg).begin(), 1894 sectEnd = (*seg).end(); sect != sectEnd; ++sect) { 1895 if ((*sect)->index() < (*pSectBegin)->index()) 1896 continue; 1897 1898 if (LDFileFormat::Null == (*sect)->kind()) 1899 continue; 1900 1901 if (sect == pSectEnd) 1902 return; 1903 1904 if (sect != (*seg).begin()) 1905 (*sect)->setAddr(start_addr + (*sect)->offset() - 1906 (*seg).front()->offset()); 1907 else 1908 (*sect)->setAddr(start_addr); 1909 } 1910 } 1911} 1912 1913/// preLayout - Backend can do any needed modification before layout 1914void GNULDBackend::preLayout(Module& pModule, FragmentLinker& pLinker) 1915{ 1916 // prelayout target first 1917 doPreLayout(pLinker); 1918 1919 if (config().options().hasEhFrameHdr() && getOutputFormat()->hasEhFrame()) { 1920 // init EhFrameHdr and size the output section 1921 ELFFileFormat* format = getOutputFormat(); 1922 m_pEhFrameHdr = new EhFrameHdr(format->getEhFrameHdr(), 1923 format->getEhFrame()); 1924 m_pEhFrameHdr->sizeOutput(); 1925 } 1926 1927 // change .tbss and .tdata section symbol from Local to TLS category 1928 if (NULL != f_pTDATA) 1929 pModule.getSymbolTable().changeLocalToTLS(*f_pTDATA); 1930 1931 if (NULL != f_pTBSS) 1932 pModule.getSymbolTable().changeLocalToTLS(*f_pTBSS); 1933 1934 // To merge input's relocation sections into output's relocation sections. 1935 // 1936 // If we are generating relocatables (-r), move input relocation sections 1937 // to corresponding output relocation sections. 1938 if (LinkerConfig::Object == config().codeGenType()) { 1939 Module::obj_iterator input, inEnd = pModule.obj_end(); 1940 for (input = pModule.obj_begin(); input != inEnd; ++input) { 1941 LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd(); 1942 for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) { 1943 1944 // get the output relocation LDSection with identical name. 1945 LDSection* output_sect = pModule.getSection((*rs)->name()); 1946 if (NULL == output_sect) { 1947 output_sect = LDSection::Create((*rs)->name(), 1948 (*rs)->kind(), 1949 (*rs)->type(), 1950 (*rs)->flag()); 1951 1952 output_sect->setAlign((*rs)->align()); 1953 pModule.getSectionTable().push_back(output_sect); 1954 } 1955 1956 // set output relocation section link 1957 const LDSection* input_link = (*rs)->getLink(); 1958 assert(NULL != input_link && "Illegal input relocation section."); 1959 1960 // get the linked output section 1961 LDSection* output_link = pModule.getSection(input_link->name()); 1962 assert(NULL != output_link); 1963 1964 output_sect->setLink(output_link); 1965 1966 // get output relcoationData, create one if not exist 1967 if (!output_sect->hasRelocData()) 1968 IRBuilder::CreateRelocData(*output_sect); 1969 1970 RelocData* out_reloc_data = output_sect->getRelocData(); 1971 1972 // move relocations from input's to output's RelcoationData 1973 RelocData::FragmentListType& out_list = 1974 out_reloc_data->getFragmentList(); 1975 RelocData::FragmentListType& in_list = 1976 (*rs)->getRelocData()->getFragmentList(); 1977 out_list.splice(out_list.end(), in_list); 1978 1979 // size output 1980 if (llvm::ELF::SHT_REL == output_sect->type()) 1981 output_sect->setSize(out_reloc_data->size() * getRelEntrySize()); 1982 else if (llvm::ELF::SHT_RELA == output_sect->type()) 1983 output_sect->setSize(out_reloc_data->size() * getRelaEntrySize()); 1984 else { 1985 fatal(diag::unknown_reloc_section_type) << output_sect->type() 1986 << output_sect->name(); 1987 } 1988 } // end of for each relocation section 1989 } // end of for each input 1990 } // end of if 1991 1992 // set up the section flag of .note.GNU-stack section 1993 setupGNUStackInfo(pModule, pLinker); 1994} 1995 1996/// postLayout - Backend can do any needed modification after layout 1997void GNULDBackend::postLayout(Module& pModule, 1998 FragmentLinker& pLinker) 1999{ 2000 // 1. emit program headers 2001 if (LinkerConfig::Object != config().codeGenType()) { 2002 // 1.1 create program headers 2003 createProgramHdrs(pModule, pLinker); 2004 } 2005 2006 if (LinkerConfig::Object != config().codeGenType()) { 2007 if (config().options().hasRelro()) { 2008 // 1.2 set up the offset constraint of PT_RELRO 2009 setupRelro(pModule); 2010 } 2011 2012 // 1.3 set up the output sections' address 2013 setOutputSectionAddress(pLinker, pModule, pModule.begin(), pModule.end()); 2014 2015 // 1.4 do relaxation 2016 relax(pModule, pLinker); 2017 2018 // 1.5 set up the attributes of program headers 2019 setupProgramHdrs(pLinker); 2020 } 2021 2022 // 2. target specific post layout 2023 doPostLayout(pModule, pLinker); 2024} 2025 2026void GNULDBackend::postProcessing(FragmentLinker& pLinker, MemoryArea& pOutput) 2027{ 2028 if (config().options().hasEhFrameHdr() && getOutputFormat()->hasEhFrame()) { 2029 // emit eh_frame_hdr 2030 if (bitclass() == 32) 2031 m_pEhFrameHdr->emitOutput<32>(pOutput); 2032 } 2033} 2034 2035/// getHashBucketCount - calculate hash bucket count. 2036/// @ref Google gold linker, dynobj.cc:791 2037unsigned GNULDBackend::getHashBucketCount(unsigned pNumOfSymbols, 2038 bool pIsGNUStyle) 2039{ 2040 // @ref Google gold, dynobj.cc:loc 791 2041 static const unsigned int buckets[] = 2042 { 2043 1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209, 2044 16411, 32771, 65537, 131101, 262147 2045 }; 2046 const unsigned buckets_count = sizeof buckets / sizeof buckets[0]; 2047 2048 unsigned int result = 1; 2049 for (unsigned i = 0; i < buckets_count; ++i) { 2050 if (pNumOfSymbols < buckets[i]) 2051 break; 2052 result = buckets[i]; 2053 } 2054 2055 if (pIsGNUStyle && result < 2) 2056 result = 2; 2057 2058 return result; 2059} 2060 2061/// isDynamicSymbol 2062/// @ref Google gold linker: symtab.cc:311 2063bool GNULDBackend::isDynamicSymbol(const LDSymbol& pSymbol) 2064{ 2065 // If a local symbol is in the LDContext's symbol table, it's a real local 2066 // symbol. We should not add it 2067 if (pSymbol.binding() == ResolveInfo::Local) 2068 return false; 2069 2070 // If we are building shared object, and the visibility is external, we 2071 // need to add it. 2072 if (LinkerConfig::DynObj == config().codeGenType() || 2073 LinkerConfig::Exec == config().codeGenType()) { 2074 if (pSymbol.resolveInfo()->visibility() == ResolveInfo::Default || 2075 pSymbol.resolveInfo()->visibility() == ResolveInfo::Protected) { 2076 return true; 2077 } 2078 } 2079 return false; 2080} 2081 2082/// isDynamicSymbol 2083/// @ref Google gold linker: symtab.cc:311 2084bool GNULDBackend::isDynamicSymbol(const ResolveInfo& pResolveInfo) 2085{ 2086 // If a local symbol is in the LDContext's symbol table, it's a real local 2087 // symbol. We should not add it 2088 if (pResolveInfo.binding() == ResolveInfo::Local) 2089 return false; 2090 2091 // If we are building shared object, and the visibility is external, we 2092 // need to add it. 2093 if (LinkerConfig::DynObj == config().codeGenType() || 2094 LinkerConfig::Exec == config().codeGenType()) { 2095 if (pResolveInfo.visibility() == ResolveInfo::Default || 2096 pResolveInfo.visibility() == ResolveInfo::Protected) { 2097 return true; 2098 } 2099 } 2100 return false; 2101} 2102 2103/// commonPageSize - the common page size of the target machine. 2104/// @ref gold linker: target.h:135 2105uint64_t GNULDBackend::commonPageSize() const 2106{ 2107 if (config().options().commPageSize() > 0) 2108 return std::min(config().options().commPageSize(), abiPageSize()); 2109 else 2110 return std::min(static_cast<uint64_t>(0x1000), abiPageSize()); 2111} 2112 2113/// abiPageSize - the abi page size of the target machine. 2114/// @ref gold linker: target.h:125 2115uint64_t GNULDBackend::abiPageSize() const 2116{ 2117 if (config().options().maxPageSize() > 0) 2118 return config().options().maxPageSize(); 2119 else 2120 return static_cast<uint64_t>(0x1000); 2121} 2122 2123/// isSymbolPreemtible - whether the symbol can be preemted by other 2124/// link unit 2125/// @ref Google gold linker, symtab.h:551 2126bool GNULDBackend::isSymbolPreemptible(const ResolveInfo& pSym) const 2127{ 2128 if (pSym.other() != ResolveInfo::Default) 2129 return false; 2130 2131 // This is because the codeGenType of pie is DynObj. And gold linker check 2132 // the "shared" option instead. 2133 if (config().options().isPIE()) 2134 return false; 2135 2136 if (LinkerConfig::DynObj != config().codeGenType()) 2137 return false; 2138 2139 if (config().options().Bsymbolic()) 2140 return false; 2141 2142 // A local defined symbol should be non-preemptible. 2143 // This issue is found when linking libstdc++ on freebsd. A R_386_GOT32 2144 // relocation refers to a local defined symbol, and we should generate a 2145 // relative dynamic relocation when applying the relocation. 2146 if (pSym.isDefine() && pSym.binding() == ResolveInfo::Local) 2147 return false; 2148 2149 return true; 2150} 2151 2152/// symbolNeedsDynRel - return whether the symbol needs a dynamic relocation 2153/// @ref Google gold linker, symtab.h:645 2154bool GNULDBackend::symbolNeedsDynRel(const FragmentLinker& pLinker, 2155 const ResolveInfo& pSym, 2156 bool pSymHasPLT, 2157 bool isAbsReloc) const 2158{ 2159 // an undefined reference in the executables should be statically 2160 // resolved to 0 and no need a dynamic relocation 2161 if (pSym.isUndef() && 2162 !pSym.isDyn() && 2163 LinkerConfig::Exec == config().codeGenType()) 2164 return false; 2165 2166 if (pSym.isAbsolute()) 2167 return false; 2168 if (pLinker.isOutputPIC() && isAbsReloc) 2169 return true; 2170 if (pSymHasPLT && ResolveInfo::Function == pSym.type()) 2171 return false; 2172 if (!pLinker.isOutputPIC() && pSymHasPLT) 2173 return false; 2174 if (pSym.isDyn() || pSym.isUndef() || 2175 isSymbolPreemptible(pSym)) 2176 return true; 2177 2178 return false; 2179} 2180 2181/// symbolNeedsPLT - return whether the symbol needs a PLT entry 2182/// @ref Google gold linker, symtab.h:596 2183bool GNULDBackend::symbolNeedsPLT(const FragmentLinker& pLinker, 2184 const ResolveInfo& pSym) const 2185{ 2186 if (pSym.isUndef() && 2187 !pSym.isDyn() && 2188 LinkerConfig::DynObj != config().codeGenType()) 2189 return false; 2190 2191 // An IndirectFunc symbol (i.e., STT_GNU_IFUNC) always needs a plt entry 2192 if (pSym.type() == ResolveInfo::IndirectFunc) 2193 return true; 2194 2195 if (pSym.type() != ResolveInfo::Function) 2196 return false; 2197 2198 if (pLinker.isStaticLink() && !pLinker.isOutputPIC()) 2199 return false; 2200 2201 if (config().options().isPIE()) 2202 return false; 2203 2204 return (pSym.isDyn() || 2205 pSym.isUndef() || 2206 isSymbolPreemptible(pSym)); 2207} 2208 2209/// symbolHasFinalValue - return true if the symbol's value can be decided at 2210/// link time 2211/// @ref Google gold linker, Symbol::final_value_is_known 2212bool GNULDBackend::symbolFinalValueIsKnown(const FragmentLinker& pLinker, 2213 const ResolveInfo& pSym) const 2214{ 2215 // if the output is pic code or if not executables, symbols' value may change 2216 // at runtime 2217 if (pLinker.isOutputPIC() || LinkerConfig::Exec != config().codeGenType()) 2218 return false; 2219 2220 // if the symbol is from dynamic object, then its value is unknown 2221 if (pSym.isDyn()) 2222 return false; 2223 2224 // if the symbol is not in dynamic object and is not undefined, then its value 2225 // is known 2226 if (!pSym.isUndef()) 2227 return true; 2228 2229 // if the symbol is undefined and not in dynamic objects, for example, a weak 2230 // undefined symbol, then whether the symbol's final value can be known 2231 // depends on whrther we're doing static link 2232 return pLinker.isStaticLink(); 2233} 2234 2235/// symbolNeedsCopyReloc - return whether the symbol needs a copy relocation 2236bool GNULDBackend::symbolNeedsCopyReloc(const FragmentLinker& pLinker, 2237 const Relocation& pReloc, 2238 const ResolveInfo& pSym) const 2239{ 2240 // only the reference from dynamic executable to non-function symbol in 2241 // the dynamic objects may need copy relocation 2242 if (pLinker.isOutputPIC() || 2243 !pSym.isDyn() || 2244 pSym.type() == ResolveInfo::Function || 2245 pSym.size() == 0) 2246 return false; 2247 2248 // check if the option -z nocopyreloc is given 2249 if (config().options().hasNoCopyReloc()) 2250 return false; 2251 2252 // TODO: Is this check necessary? 2253 // if relocation target place is readonly, a copy relocation is needed 2254 uint32_t flag = pReloc.targetRef().frag()->getParent()->getSection().flag(); 2255 if (0 == (flag & llvm::ELF::SHF_WRITE)) 2256 return true; 2257 2258 return false; 2259} 2260 2261LDSymbol& GNULDBackend::getTDATASymbol() 2262{ 2263 assert(NULL != f_pTDATA); 2264 return *f_pTDATA; 2265} 2266 2267const LDSymbol& GNULDBackend::getTDATASymbol() const 2268{ 2269 assert(NULL != f_pTDATA); 2270 return *f_pTDATA; 2271} 2272 2273LDSymbol& GNULDBackend::getTBSSSymbol() 2274{ 2275 assert(NULL != f_pTBSS); 2276 return *f_pTBSS; 2277} 2278 2279const LDSymbol& GNULDBackend::getTBSSSymbol() const 2280{ 2281 assert(NULL != f_pTBSS); 2282 return *f_pTBSS; 2283} 2284 2285void GNULDBackend::checkAndSetHasTextRel(const LDSection& pSection) 2286{ 2287 if (m_bHasTextRel) 2288 return; 2289 2290 // if the target section of the dynamic relocation is ALLOCATE but is not 2291 // writable, than we should set DF_TEXTREL 2292 const uint32_t flag = pSection.flag(); 2293 if (0 == (flag & llvm::ELF::SHF_WRITE) && (flag & llvm::ELF::SHF_ALLOC)) 2294 m_bHasTextRel = true; 2295 2296 return; 2297} 2298 2299/// initBRIslandFactory - initialize the branch island factory for relaxation 2300bool GNULDBackend::initBRIslandFactory() 2301{ 2302 if (NULL == m_pBRIslandFactory) { 2303 m_pBRIslandFactory = new BranchIslandFactory(maxBranchOffset()); 2304 } 2305 return true; 2306} 2307 2308/// initStubFactory - initialize the stub factory for relaxation 2309bool GNULDBackend::initStubFactory() 2310{ 2311 if (NULL == m_pStubFactory) { 2312 m_pStubFactory = new StubFactory(); 2313 } 2314 return true; 2315} 2316 2317bool GNULDBackend::relax(Module& pModule, FragmentLinker& pLinker) 2318{ 2319 if (!mayRelax()) 2320 return true; 2321 2322 bool finished = true; 2323 do { 2324 if (doRelax(pModule, pLinker, finished)) { 2325 // If the sections (e.g., .text) are relaxed, the layout is also changed 2326 // We need to do the following: 2327 2328 // 1. set up the offset 2329 setOutputSectionOffset(pModule, pModule.begin(), pModule.end()); 2330 2331 // 2. set up the offset constraint of PT_RELRO 2332 if (config().options().hasRelro()) 2333 setupRelro(pModule); 2334 2335 // 3. set up the output sections' address 2336 setOutputSectionAddress(pLinker, pModule, pModule.begin(), pModule.end()); 2337 } 2338 } while (!finished); 2339 2340 return true; 2341} 2342 2343