GNULDBackend.cpp revision affc150dc44fab1911775a49636d0ce85333b634
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 <llvm/Support/ELF.h> 10#include <mcld/ADT/SizeTraits.h> 11#include <mcld/Target/GNULDBackend.h> 12#include <mcld/MC/MCLDInfo.h> 13#include <mcld/MC/MCLDOutput.h> 14#include <mcld/MC/InputTree.h> 15#include <mcld/MC/SymbolCategory.h> 16#include <mcld/LD/LDSymbol.h> 17#include <mcld/LD/Layout.h> 18#include <mcld/Support/MemoryArea.h> 19#include <mcld/Support/MemoryRegion.h> 20#include <mcld/Support/MsgHandling.h> 21#include <mcld/MC/MCLinker.h> 22#include <string> 23#include <cstring> 24#include <cassert> 25 26using namespace mcld; 27 28//===----------------------------------------------------------------------===// 29// GNULDBackend 30GNULDBackend::GNULDBackend() 31 : m_pArchiveReader(NULL), 32 m_pObjectReader(NULL), 33 m_pDynObjReader(NULL), 34 m_pObjectWriter(NULL), 35 m_pDynObjWriter(NULL), 36 m_pExecWriter(NULL), 37 m_pDynObjFileFormat(NULL), 38 m_pExecFileFormat(NULL), 39 m_ELFSegmentTable(9), // magic number 40 m_pEhFrameHdr(NULL), 41 f_pPreInitArrayStart(NULL), 42 f_pPreInitArrayEnd(NULL), 43 f_pInitArrayStart(NULL), 44 f_pInitArrayEnd(NULL), 45 f_pFiniArrayStart(NULL), 46 f_pFiniArrayEnd(NULL), 47 f_pStack(NULL), 48 f_pExecutableStart(NULL), 49 f_pEText(NULL), 50 f_p_EText(NULL), 51 f_p__EText(NULL), 52 f_pEData(NULL), 53 f_p_EData(NULL), 54 f_pBSSStart(NULL), 55 f_pEnd(NULL), 56 f_p_End(NULL) { 57 m_pSymIndexMap = new HashTableType(1024); 58} 59 60GNULDBackend::~GNULDBackend() 61{ 62 if (NULL != m_pArchiveReader) 63 delete m_pArchiveReader; 64 if (NULL != m_pObjectReader) 65 delete m_pObjectReader; 66 if (NULL != m_pDynObjReader) 67 delete m_pDynObjReader; 68 if (NULL != m_pObjectWriter) 69 delete m_pObjectWriter; 70 if (NULL != m_pDynObjWriter) 71 delete m_pDynObjWriter; 72 if (NULL != m_pExecWriter) 73 delete m_pExecWriter; 74 if (NULL != m_pDynObjFileFormat) 75 delete m_pDynObjFileFormat; 76 if (NULL != m_pExecFileFormat) 77 delete m_pExecFileFormat; 78 if (NULL != m_pSymIndexMap) 79 delete m_pSymIndexMap; 80 if (NULL != m_pEhFrameHdr) 81 delete m_pEhFrameHdr; 82} 83 84size_t GNULDBackend::sectionStartOffset() const 85{ 86 // FIXME: use fixed offset, we need 10 segments by default 87 return sizeof(llvm::ELF::Elf64_Ehdr)+10*sizeof(llvm::ELF::Elf64_Phdr); 88} 89 90uint64_t GNULDBackend::segmentStartAddr(const Output& pOutput, 91 const MCLDInfo& pInfo) const 92{ 93 // TODO: handle the user option: -TText= 94 if (isOutputPIC(pOutput, pInfo)) 95 return 0x0; 96 else 97 return defaultTextSegmentAddr(); 98} 99 100bool GNULDBackend::initArchiveReader(MCLinker&, MCLDInfo &pInfo) 101{ 102 if (0 == m_pArchiveReader) 103 m_pArchiveReader = new GNUArchiveReader(pInfo); 104 return true; 105} 106 107bool GNULDBackend::initObjectReader(MCLinker& pLinker) 108{ 109 if (0 == m_pObjectReader) 110 m_pObjectReader = new ELFObjectReader(*this, pLinker); 111 return true; 112} 113 114bool GNULDBackend::initDynObjReader(MCLinker& pLinker) 115{ 116 if (0 == m_pDynObjReader) 117 m_pDynObjReader = new ELFDynObjReader(*this, pLinker); 118 return true; 119} 120 121bool GNULDBackend::initObjectWriter(MCLinker&) 122{ 123 // TODO 124 return true; 125} 126 127bool GNULDBackend::initDynObjWriter(MCLinker& pLinker) 128{ 129 if (NULL == m_pDynObjWriter) 130 m_pDynObjWriter = new ELFDynObjWriter(*this, pLinker); 131 return true; 132} 133 134bool GNULDBackend::initExecWriter(MCLinker& pLinker) 135{ 136 if (NULL == m_pExecWriter) 137 m_pExecWriter = new ELFExecWriter(*this, pLinker); 138 return true; 139} 140 141bool GNULDBackend::initExecSections(MCLinker& pMCLinker) 142{ 143 if (0 == m_pExecFileFormat) 144 m_pExecFileFormat = new ELFExecFileFormat(*this); 145 146 // initialize standard sections 147 m_pExecFileFormat->initStdSections(pMCLinker); 148 return true; 149} 150 151bool GNULDBackend::initDynObjSections(MCLinker& pMCLinker) 152{ 153 if (0 == m_pDynObjFileFormat) 154 m_pDynObjFileFormat = new ELFDynObjFileFormat(*this); 155 156 // initialize standard sections 157 m_pDynObjFileFormat->initStdSections(pMCLinker); 158 return true; 159} 160 161bool GNULDBackend::initStandardSymbols(MCLinker& pLinker, const Output& pOutput) 162{ 163 ELFFileFormat* file_format = getOutputFormat(pOutput); 164 165 // ----- section symbols ----- // 166 // .preinit_array 167 MCFragmentRef* preinit_array = NULL; 168 if (file_format->hasPreInitArray()) { 169 preinit_array = pLinker.getLayout().getFragmentRef( 170 *(file_format->getPreInitArray().getSectionData()->begin()), 171 0x0); 172 } 173 f_pPreInitArrayStart = 174 pLinker.defineSymbol<MCLinker::AsRefered, 175 MCLinker::Resolve>("__preinit_array_start", 176 false, // isDyn 177 ResolveInfo::NoType, 178 ResolveInfo::Define, 179 ResolveInfo::Global, 180 0x0, // size 181 0x0, // value 182 preinit_array, // FragRef 183 ResolveInfo::Hidden); 184 f_pPreInitArrayEnd = 185 pLinker.defineSymbol<MCLinker::AsRefered, 186 MCLinker::Resolve>("__preinit_array_end", 187 false, // isDyn 188 ResolveInfo::NoType, 189 ResolveInfo::Define, 190 ResolveInfo::Global, 191 0x0, // size 192 0x0, // value 193 NULL, // FragRef 194 ResolveInfo::Hidden); 195 196 // .init_array 197 MCFragmentRef* init_array = NULL; 198 if (file_format->hasInitArray()) { 199 init_array = pLinker.getLayout().getFragmentRef( 200 *(file_format->getInitArray().getSectionData()->begin()), 201 0x0); 202 } 203 204 f_pInitArrayStart = 205 pLinker.defineSymbol<MCLinker::AsRefered, 206 MCLinker::Resolve>("__init_array_start", 207 false, // isDyn 208 ResolveInfo::NoType, 209 ResolveInfo::Define, 210 ResolveInfo::Global, 211 0x0, // size 212 0x0, // value 213 init_array, // FragRef 214 ResolveInfo::Hidden); 215 f_pInitArrayEnd = 216 pLinker.defineSymbol<MCLinker::AsRefered, 217 MCLinker::Resolve>("__init_array_end", 218 false, // isDyn 219 ResolveInfo::NoType, 220 ResolveInfo::Define, 221 ResolveInfo::Global, 222 0x0, // size 223 0x0, // value 224 init_array, // FragRef 225 ResolveInfo::Hidden); 226 227 // .fini_array 228 MCFragmentRef* fini_array = NULL; 229 if (file_format->hasFiniArray()) { 230 fini_array = pLinker.getLayout().getFragmentRef( 231 *(file_format->getFiniArray().getSectionData()->begin()), 232 0x0); 233 } 234 235 f_pFiniArrayStart = 236 pLinker.defineSymbol<MCLinker::AsRefered, 237 MCLinker::Resolve>("__fini_array_start", 238 false, // isDyn 239 ResolveInfo::NoType, 240 ResolveInfo::Define, 241 ResolveInfo::Global, 242 0x0, // size 243 0x0, // value 244 fini_array, // FragRef 245 ResolveInfo::Hidden); 246 f_pFiniArrayEnd = 247 pLinker.defineSymbol<MCLinker::AsRefered, 248 MCLinker::Resolve>("__fini_array_end", 249 false, // isDyn 250 ResolveInfo::NoType, 251 ResolveInfo::Define, 252 ResolveInfo::Global, 253 0x0, // size 254 0x0, // value 255 fini_array, // FragRef 256 ResolveInfo::Hidden); 257 258 // .stack 259 MCFragmentRef* stack = NULL; 260 if (file_format->hasStack()) { 261 stack = pLinker.getLayout().getFragmentRef( 262 *(file_format->getStack().getSectionData()->begin()), 263 0x0); 264 } 265 f_pStack = 266 pLinker.defineSymbol<MCLinker::AsRefered, 267 MCLinker::Resolve>("__stack", 268 false, // isDyn 269 ResolveInfo::NoType, 270 ResolveInfo::Define, 271 ResolveInfo::Global, 272 0x0, // size 273 0x0, // value 274 stack, // FragRef 275 ResolveInfo::Hidden); 276 277 // ----- segment symbols ----- // 278 f_pExecutableStart = 279 pLinker.defineSymbol<MCLinker::AsRefered, 280 MCLinker::Resolve>("__executable_start", 281 false, // isDyn 282 ResolveInfo::NoType, 283 ResolveInfo::Define, 284 ResolveInfo::Absolute, 285 0x0, // size 286 0x0, // value 287 NULL, // FragRef 288 ResolveInfo::Default); 289 f_pEText = 290 pLinker.defineSymbol<MCLinker::AsRefered, 291 MCLinker::Resolve>("etext", 292 false, // isDyn 293 ResolveInfo::NoType, 294 ResolveInfo::Define, 295 ResolveInfo::Absolute, 296 0x0, // size 297 0x0, // value 298 NULL, // FragRef 299 ResolveInfo::Default); 300 f_p_EText = 301 pLinker.defineSymbol<MCLinker::AsRefered, 302 MCLinker::Resolve>("_etext", 303 false, // isDyn 304 ResolveInfo::NoType, 305 ResolveInfo::Define, 306 ResolveInfo::Absolute, 307 0x0, // size 308 0x0, // value 309 NULL, // FragRef 310 ResolveInfo::Default); 311 f_p__EText = 312 pLinker.defineSymbol<MCLinker::AsRefered, 313 MCLinker::Resolve>("__etext", 314 false, // isDyn 315 ResolveInfo::NoType, 316 ResolveInfo::Define, 317 ResolveInfo::Absolute, 318 0x0, // size 319 0x0, // value 320 NULL, // FragRef 321 ResolveInfo::Default); 322 f_pEData = 323 pLinker.defineSymbol<MCLinker::AsRefered, 324 MCLinker::Resolve>("edata", 325 false, // isDyn 326 ResolveInfo::NoType, 327 ResolveInfo::Define, 328 ResolveInfo::Absolute, 329 0x0, // size 330 0x0, // value 331 NULL, // FragRef 332 ResolveInfo::Default); 333 334 f_pEnd = 335 pLinker.defineSymbol<MCLinker::AsRefered, 336 MCLinker::Resolve>("end", 337 false, // isDyn 338 ResolveInfo::NoType, 339 ResolveInfo::Define, 340 ResolveInfo::Absolute, 341 0x0, // size 342 0x0, // value 343 NULL, // FragRef 344 ResolveInfo::Default); 345 346 // _edata is defined forcefully. 347 // @ref Google gold linker: defstd.cc: 186 348 f_p_EData = 349 pLinker.defineSymbol<MCLinker::Force, 350 MCLinker::Resolve>("_edata", 351 false, // isDyn 352 ResolveInfo::NoType, 353 ResolveInfo::Define, 354 ResolveInfo::Absolute, 355 0x0, // size 356 0x0, // value 357 NULL, // FragRef 358 ResolveInfo::Default); 359 360 // __bss_start is defined forcefully. 361 // @ref Google gold linker: defstd.cc: 214 362 f_pBSSStart = 363 pLinker.defineSymbol<MCLinker::Force, 364 MCLinker::Resolve>("__bss_start", 365 false, // isDyn 366 ResolveInfo::NoType, 367 ResolveInfo::Define, 368 ResolveInfo::Absolute, 369 0x0, // size 370 0x0, // value 371 NULL, // FragRef 372 ResolveInfo::Default); 373 374 // _end is defined forcefully. 375 // @ref Google gold linker: defstd.cc: 228 376 f_p_End = 377 pLinker.defineSymbol<MCLinker::Force, 378 MCLinker::Resolve>("_end", 379 false, // isDyn 380 ResolveInfo::NoType, 381 ResolveInfo::Define, 382 ResolveInfo::Absolute, 383 0x0, // size 384 0x0, // value 385 NULL, // FragRef 386 ResolveInfo::Default); 387 388 return true; 389} 390 391bool 392GNULDBackend::finalizeStandardSymbols(MCLinker& pLinker, const Output& pOutput) 393{ 394 ELFFileFormat* file_format = getOutputFormat(pOutput); 395 396 // ----- section symbols ----- // 397 if (NULL != f_pPreInitArrayStart) { 398 if (!f_pPreInitArrayStart->hasFragRef()) { 399 f_pPreInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 400 f_pPreInitArrayStart->setValue(0x0); 401 } 402 } 403 404 if (NULL != f_pPreInitArrayEnd) { 405 if (f_pPreInitArrayEnd->hasFragRef()) { 406 f_pPreInitArrayEnd->setValue(f_pPreInitArrayEnd->value() + 407 file_format->getPreInitArray().size()); 408 } 409 else { 410 f_pPreInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 411 f_pPreInitArrayEnd->setValue(0x0); 412 } 413 } 414 415 if (NULL != f_pInitArrayStart) { 416 if (!f_pInitArrayStart->hasFragRef()) { 417 f_pInitArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 418 f_pInitArrayStart->setValue(0x0); 419 } 420 } 421 422 if (NULL != f_pInitArrayEnd) { 423 if (f_pInitArrayEnd->hasFragRef()) { 424 f_pInitArrayEnd->setValue(f_pInitArrayEnd->value() + 425 file_format->getInitArray().size()); 426 } 427 else { 428 f_pInitArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 429 f_pInitArrayEnd->setValue(0x0); 430 } 431 } 432 433 if (NULL != f_pFiniArrayStart) { 434 if (!f_pFiniArrayStart->hasFragRef()) { 435 f_pFiniArrayStart->resolveInfo()->setBinding(ResolveInfo::Absolute); 436 f_pFiniArrayStart->setValue(0x0); 437 } 438 } 439 440 if (NULL != f_pFiniArrayEnd) { 441 if (f_pFiniArrayEnd->hasFragRef()) { 442 f_pFiniArrayEnd->setValue(f_pFiniArrayEnd->value() + 443 file_format->getFiniArray().size()); 444 } 445 else { 446 f_pFiniArrayEnd->resolveInfo()->setBinding(ResolveInfo::Absolute); 447 f_pFiniArrayEnd->setValue(0x0); 448 } 449 } 450 451 if (NULL != f_pStack) { 452 if (!f_pStack->hasFragRef()) { 453 f_pStack->resolveInfo()->setBinding(ResolveInfo::Absolute); 454 f_pStack->setValue(0x0); 455 } 456 } 457 458 // ----- segment symbols ----- // 459 if (NULL != f_pExecutableStart) { 460 ELFSegment* exec_start = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 0x0, 0x0); 461 if (NULL != exec_start) { 462 if (ResolveInfo::ThreadLocal != f_pExecutableStart->type()) { 463 f_pExecutableStart->setValue(f_pExecutableStart->value() + 464 exec_start->vaddr()); 465 } 466 } 467 else 468 f_pExecutableStart->setValue(0x0); 469 } 470 471 if (NULL != f_pEText || NULL != f_p_EText || NULL !=f_p__EText) { 472 ELFSegment* etext = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 473 llvm::ELF::PF_X, 474 llvm::ELF::PF_W); 475 if (NULL != etext) { 476 if (NULL != f_pEText && ResolveInfo::ThreadLocal != f_pEText->type()) { 477 f_pEText->setValue(f_pEText->value() + 478 etext->vaddr() + 479 etext->memsz()); 480 } 481 if (NULL != f_p_EText && ResolveInfo::ThreadLocal != f_p_EText->type()) { 482 f_p_EText->setValue(f_p_EText->value() + 483 etext->vaddr() + 484 etext->memsz()); 485 } 486 if (NULL != f_p__EText && ResolveInfo::ThreadLocal != f_p__EText->type()) { 487 f_p__EText->setValue(f_p__EText->value() + 488 etext->vaddr() + 489 etext->memsz()); 490 } 491 } 492 else { 493 if (NULL != f_pEText) 494 f_pEText->setValue(0x0); 495 if (NULL != f_p_EText) 496 f_p_EText->setValue(0x0); 497 if (NULL != f_p__EText) 498 f_p__EText->setValue(0x0); 499 } 500 } 501 502 if (NULL != f_pEData || NULL != f_p_EData || NULL != f_pBSSStart || 503 NULL != f_pEnd || NULL != f_p_End) { 504 ELFSegment* edata = m_ELFSegmentTable.find(llvm::ELF::PT_LOAD, 505 llvm::ELF::PF_W, 506 0x0); 507 if (NULL != edata) { 508 if (NULL != f_pEData && ResolveInfo::ThreadLocal != f_pEData->type()) { 509 f_pEData->setValue(f_pEData->value() + 510 edata->vaddr() + 511 edata->filesz()); 512 } 513 if (NULL != f_p_EData && ResolveInfo::ThreadLocal != f_p_EData->type()) { 514 f_p_EData->setValue(f_p_EData->value() + 515 edata->vaddr() + 516 edata->filesz()); 517 } 518 if (NULL != f_pBSSStart && ResolveInfo::ThreadLocal != f_pBSSStart->type()) { 519 f_pBSSStart->setValue(f_pBSSStart->value() + 520 edata->vaddr() + 521 edata->filesz()); 522 } 523 524 if (NULL != f_pEnd && ResolveInfo::ThreadLocal != f_pEnd->type()) { 525 f_pEnd->setValue(f_pEnd->value() + 526 edata->vaddr() + 527 edata->memsz()); 528 } 529 if (NULL != f_p_End && ResolveInfo::ThreadLocal != f_p_End->type()) { 530 f_p_End->setValue(f_p_End->value() + 531 edata->vaddr() + 532 edata->memsz()); 533 } 534 } 535 else { 536 if (NULL != f_pEData) 537 f_pEData->setValue(0x0); 538 if (NULL != f_p_EData) 539 f_p_EData->setValue(0x0); 540 if (NULL != f_pBSSStart) 541 f_pBSSStart->setValue(0x0); 542 543 if (NULL != f_pEnd) 544 f_pEnd->setValue(0x0); 545 if (NULL != f_p_End) 546 f_p_End->setValue(0x0); 547 } 548 } 549 550 return true; 551} 552 553GNUArchiveReader *GNULDBackend::getArchiveReader() 554{ 555 assert(0 != m_pArchiveReader); 556 return m_pArchiveReader; 557} 558 559const GNUArchiveReader *GNULDBackend::getArchiveReader() const 560{ 561 assert(0 != m_pArchiveReader); 562 return m_pArchiveReader; 563} 564 565ELFObjectReader *GNULDBackend::getObjectReader() 566{ 567 assert(0 != m_pObjectReader); 568 return m_pObjectReader; 569} 570 571const ELFObjectReader *GNULDBackend::getObjectReader() const 572{ 573 assert(0 != m_pObjectReader); 574 return m_pObjectReader; 575} 576 577ELFDynObjReader *GNULDBackend::getDynObjReader() 578{ 579 assert(0 != m_pDynObjReader); 580 return m_pDynObjReader; 581} 582 583const ELFDynObjReader *GNULDBackend::getDynObjReader() const 584{ 585 assert(0 != m_pDynObjReader); 586 return m_pDynObjReader; 587} 588 589ELFObjectWriter *GNULDBackend::getObjectWriter() 590{ 591 // TODO 592 return NULL; 593} 594 595const ELFObjectWriter *GNULDBackend::getObjectWriter() const 596{ 597 // TODO 598 return NULL; 599} 600 601ELFDynObjWriter *GNULDBackend::getDynObjWriter() 602{ 603 assert(0 != m_pDynObjWriter); 604 return m_pDynObjWriter; 605} 606 607const ELFDynObjWriter *GNULDBackend::getDynObjWriter() const 608{ 609 assert(0 != m_pDynObjWriter); 610 return m_pDynObjWriter; 611} 612 613ELFExecWriter *GNULDBackend::getExecWriter() 614{ 615 assert(NULL != m_pExecWriter); 616 return m_pExecWriter; 617} 618 619const ELFExecWriter *GNULDBackend::getExecWriter() const 620{ 621 assert(NULL != m_pExecWriter); 622 return m_pExecWriter; 623} 624 625ELFFileFormat* GNULDBackend::getOutputFormat(const Output& pOutput) 626{ 627 switch (pOutput.type()) { 628 case Output::DynObj: 629 return getDynObjFileFormat(); 630 case Output::Exec: 631 return getExecFileFormat(); 632 // FIXME: We do not support building .o now 633 case Output::Object: 634 default: 635 fatal(diag::unrecognized_output_file) << pOutput.type(); 636 return NULL; 637 } 638} 639 640const ELFFileFormat* GNULDBackend::getOutputFormat(const Output& pOutput) const 641{ 642 switch (pOutput.type()) { 643 case Output::DynObj: 644 return getDynObjFileFormat(); 645 case Output::Exec: 646 return getExecFileFormat(); 647 // FIXME: We do not support building .o now 648 case Output::Object: 649 default: 650 fatal(diag::unrecognized_output_file) << pOutput.type(); 651 return NULL; 652 } 653} 654 655ELFDynObjFileFormat* GNULDBackend::getDynObjFileFormat() 656{ 657 assert(0 != m_pDynObjFileFormat); 658 return m_pDynObjFileFormat; 659} 660 661const ELFDynObjFileFormat* GNULDBackend::getDynObjFileFormat() const 662{ 663 assert(0 != m_pDynObjFileFormat); 664 return m_pDynObjFileFormat; 665} 666 667ELFExecFileFormat* GNULDBackend::getExecFileFormat() 668{ 669 assert(0 != m_pExecFileFormat); 670 return m_pExecFileFormat; 671} 672 673const ELFExecFileFormat* GNULDBackend::getExecFileFormat() const 674{ 675 assert(0 != m_pExecFileFormat); 676 return m_pExecFileFormat; 677} 678 679/// sizeNamePools - compute the size of regular name pools 680/// In ELF executable files, regular name pools are .symtab, .strtab, 681/// .dynsym, .dynstr, and .hash 682void 683GNULDBackend::sizeNamePools(const Output& pOutput, 684 const SymbolCategory& pSymbols, 685 const MCLDInfo& pLDInfo) 686{ 687 // size of string tables starts from 1 to hold the null character in their 688 // first byte 689 size_t symtab = 1; 690 size_t dynsym = 1; 691 // number of entries in symbol tables starts from 1 to hold the special entry 692 // at index 0 (STN_UNDEF). See ELF Spec Book I, p1-21. 693 size_t strtab = 1; 694 size_t dynstr = 1; 695 size_t hash = 0; 696 697 // compute size of .symtab, .dynsym and .strtab 698 SymbolCategory::const_iterator symbol; 699 SymbolCategory::const_iterator symEnd = pSymbols.end(); 700 for (symbol = pSymbols.begin(); symbol != symEnd; ++symbol) { 701 size_t str_size = (*symbol)->nameSize() + 1; 702 if (isDynamicSymbol(**symbol, pOutput)) { 703 ++dynsym; 704 dynstr += str_size; 705 } 706 ++symtab; 707 strtab += str_size; 708 } 709 710 ELFFileFormat* file_format = getOutputFormat(pOutput); 711 712 switch(pOutput.type()) { 713 // compute size of .dynstr and .hash 714 case Output::DynObj: 715 case Output::Exec: { 716 // add DT_NEED strings into .dynstr and .dynamic 717 // Rules: 718 // 1. ignore --no-add-needed 719 // 2. force count in --no-as-needed 720 // 3. judge --as-needed 721 InputTree::const_bfs_iterator input, inputEnd = pLDInfo.inputs().bfs_end(); 722 for (input = pLDInfo.inputs().bfs_begin(); input != inputEnd; ++input) { 723 if (Input::DynObj == (*input)->type()) { 724 // --add-needed 725 if ((*input)->attribute()->isAddNeeded()) { 726 // --no-as-needed 727 if (!(*input)->attribute()->isAsNeeded()) { 728 dynstr += (*input)->name().size() + 1; 729 dynamic().reserveNeedEntry(); 730 } 731 // --as-needed 732 else if ((*input)->isNeeded()) { 733 dynstr += (*input)->name().size() + 1; 734 dynamic().reserveNeedEntry(); 735 } 736 } 737 } 738 } // for 739 740 // compute .hash 741 // Both Elf32_Word and Elf64_Word are 4 bytes 742 hash = (2 + getHashBucketCount(dynsym, false) + dynsym) * 743 sizeof(llvm::ELF::Elf32_Word); 744 745 // set size 746 dynstr += pOutput.name().size() + 1; 747 if (32 == bitclass()) 748 file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf32_Sym)); 749 else 750 file_format->getDynSymTab().setSize(dynsym*sizeof(llvm::ELF::Elf64_Sym)); 751 file_format->getDynStrTab().setSize(dynstr); 752 file_format->getHashTab().setSize(hash); 753 754 } 755 /* fall through */ 756 case Output::Object: { 757 if (32 == bitclass()) 758 file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf32_Sym)); 759 else 760 file_format->getSymTab().setSize(symtab*sizeof(llvm::ELF::Elf64_Sym)); 761 file_format->getStrTab().setSize(strtab); 762 break; 763 } 764 } // end of switch 765 766 // reserve fixed entries in the .dynamic section. 767 if (Output::DynObj == pOutput.type() || Output::Exec == pOutput.type()) { 768 // Because some entries in .dynamic section need information of .dynsym, 769 // .dynstr, .symtab, .strtab and .hash, we can not reserve non-DT_NEEDED 770 // entries until we get the size of the sections mentioned above 771 dynamic().reserveEntries(pLDInfo, *file_format); 772 file_format->getDynamic().setSize(dynamic().numOfBytes()); 773 } 774} 775 776/// emitRegNamePools - emit regular name pools - .symtab, .strtab 777/// 778/// the size of these tables should be computed before layout 779/// layout should computes the start offset of these tables 780void GNULDBackend::emitRegNamePools(Output& pOutput, 781 SymbolCategory& pSymbols, 782 const Layout& pLayout, 783 const MCLDInfo& pLDInfo) 784{ 785 786 assert(pOutput.hasMemArea()); 787 788 bool sym_exist = false; 789 HashTableType::entry_type* entry = 0; 790 791 ELFFileFormat* file_format = getOutputFormat(pOutput); 792 if (pOutput.type() == Output::Object) { 793 // add first symbol into m_pSymIndexMap 794 entry = m_pSymIndexMap->insert(NULL, sym_exist); 795 entry->setValue(0); 796 797 // TODO: not support yet 798 return; 799 } 800 801 LDSection& symtab_sect = file_format->getSymTab(); 802 LDSection& strtab_sect = file_format->getStrTab(); 803 804 MemoryRegion* symtab_region = pOutput.memArea()->request(symtab_sect.offset(), 805 symtab_sect.size()); 806 MemoryRegion* strtab_region = pOutput.memArea()->request(strtab_sect.offset(), 807 strtab_sect.size()); 808 809 // set up symtab_region 810 llvm::ELF::Elf32_Sym* symtab32 = NULL; 811 llvm::ELF::Elf64_Sym* symtab64 = NULL; 812 if (32 == bitclass()) 813 symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region->start(); 814 else if (64 == bitclass()) 815 symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region->start(); 816 else 817 llvm::report_fatal_error(llvm::Twine("unsupported bitclass ") + 818 llvm::Twine(bitclass()) + 819 llvm::Twine(".\n")); 820 // set up strtab_region 821 char* strtab = (char*)strtab_region->start(); 822 strtab[0] = '\0'; 823 824 // initialize the first ELF symbol 825 if (32 == bitclass()) { 826 symtab32[0].st_name = 0; 827 symtab32[0].st_value = 0; 828 symtab32[0].st_size = 0; 829 symtab32[0].st_info = 0; 830 symtab32[0].st_other = 0; 831 symtab32[0].st_shndx = 0; 832 } 833 else { // must 64 834 symtab64[0].st_name = 0; 835 symtab64[0].st_value = 0; 836 symtab64[0].st_size = 0; 837 symtab64[0].st_info = 0; 838 symtab64[0].st_other = 0; 839 symtab64[0].st_shndx = 0; 840 } 841 842 size_t symtabIdx = 1; 843 size_t strtabsize = 1; 844 // compute size of .symtab, .dynsym and .strtab 845 SymbolCategory::iterator symbol; 846 SymbolCategory::iterator symEnd = pSymbols.end(); 847 for (symbol = pSymbols.begin(); symbol != symEnd; ++symbol) { 848 849 // maintain output's symbol and index map if building .o file 850 if (Output::Object == pOutput.type()) { 851 entry = m_pSymIndexMap->insert(NULL, sym_exist); 852 entry->setValue(symtabIdx); 853 } 854 855 // FIXME: check the endian between host and target 856 // write out symbol 857 if (32 == bitclass()) { 858 symtab32[symtabIdx].st_name = strtabsize; 859 symtab32[symtabIdx].st_value = getSymbolValue(**symbol); 860 symtab32[symtabIdx].st_size = getSymbolSize(**symbol); 861 symtab32[symtabIdx].st_info = getSymbolInfo(**symbol); 862 symtab32[symtabIdx].st_other = (*symbol)->visibility(); 863 symtab32[symtabIdx].st_shndx = getSymbolShndx(**symbol, pLayout); 864 } 865 else { // must 64 866 symtab64[symtabIdx].st_name = strtabsize; 867 symtab64[symtabIdx].st_value = getSymbolValue(**symbol); 868 symtab64[symtabIdx].st_size = getSymbolSize(**symbol); 869 symtab64[symtabIdx].st_info = getSymbolInfo(**symbol); 870 symtab64[symtabIdx].st_other = (*symbol)->visibility(); 871 symtab64[symtabIdx].st_shndx = getSymbolShndx(**symbol, pLayout); 872 } 873 // write out string 874 strcpy((strtab + strtabsize), (*symbol)->name()); 875 876 // write out 877 // sum up counters 878 ++symtabIdx; 879 strtabsize += (*symbol)->nameSize() + 1; 880 } 881} 882 883/// emitNamePools - emit dynamic name pools - .dyntab, .dynstr, .hash 884/// 885/// the size of these tables should be computed before layout 886/// layout should computes the start offset of these tables 887void GNULDBackend::emitDynNamePools(Output& pOutput, 888 SymbolCategory& pSymbols, 889 const Layout& pLayout, 890 const MCLDInfo& pLDInfo) 891{ 892 assert(pOutput.hasMemArea()); 893 ELFFileFormat* file_format = getOutputFormat(pOutput); 894 895 bool sym_exist = false; 896 HashTableType::entry_type* entry = 0; 897 898 LDSection& symtab_sect = file_format->getDynSymTab(); 899 LDSection& strtab_sect = file_format->getDynStrTab(); 900 LDSection& hash_sect = file_format->getHashTab(); 901 LDSection& dyn_sect = file_format->getDynamic(); 902 903 MemoryRegion* symtab_region = pOutput.memArea()->request(symtab_sect.offset(), 904 symtab_sect.size()); 905 MemoryRegion* strtab_region = pOutput.memArea()->request(strtab_sect.offset(), 906 strtab_sect.size()); 907 MemoryRegion* hash_region = pOutput.memArea()->request(hash_sect.offset(), 908 hash_sect.size()); 909 MemoryRegion* dyn_region = pOutput.memArea()->request(dyn_sect.offset(), 910 dyn_sect.size()); 911 // set up symtab_region 912 llvm::ELF::Elf32_Sym* symtab32 = NULL; 913 llvm::ELF::Elf64_Sym* symtab64 = NULL; 914 if (32 == bitclass()) 915 symtab32 = (llvm::ELF::Elf32_Sym*)symtab_region->start(); 916 else if (64 == bitclass()) 917 symtab64 = (llvm::ELF::Elf64_Sym*)symtab_region->start(); 918 else 919 llvm::report_fatal_error(llvm::Twine("unsupported bitclass ") + 920 llvm::Twine(bitclass()) + 921 llvm::Twine(".\n")); 922 923 // initialize the first ELF symbol 924 if (32 == bitclass()) { 925 symtab32[0].st_name = 0; 926 symtab32[0].st_value = 0; 927 symtab32[0].st_size = 0; 928 symtab32[0].st_info = 0; 929 symtab32[0].st_other = 0; 930 symtab32[0].st_shndx = 0; 931 } 932 else { // must 64 933 symtab64[0].st_name = 0; 934 symtab64[0].st_value = 0; 935 symtab64[0].st_size = 0; 936 symtab64[0].st_info = 0; 937 symtab64[0].st_other = 0; 938 symtab64[0].st_shndx = 0; 939 } 940 // set up strtab_region 941 char* strtab = (char*)strtab_region->start(); 942 strtab[0] = '\0'; 943 944 // add the first symbol into m_pSymIndexMap 945 entry = m_pSymIndexMap->insert(NULL, sym_exist); 946 entry->setValue(0); 947 948 size_t symtabIdx = 1; 949 size_t strtabsize = 1; 950 951 // emit of .dynsym, and .dynstr 952 SymbolCategory::iterator symbol; 953 SymbolCategory::iterator symEnd = pSymbols.end(); 954 for (symbol = pSymbols.begin(); symbol != symEnd; ++symbol) { 955 if (!isDynamicSymbol(**symbol, pOutput)) 956 continue; 957 958 // maintain output's symbol and index map 959 entry = m_pSymIndexMap->insert(*symbol, sym_exist); 960 entry->setValue(symtabIdx); 961 962 // FIXME: check the endian between host and target 963 // write out symbol 964 if (32 == bitclass()) { 965 symtab32[symtabIdx].st_name = strtabsize; 966 symtab32[symtabIdx].st_value = (*symbol)->value(); 967 symtab32[symtabIdx].st_size = getSymbolSize(**symbol); 968 symtab32[symtabIdx].st_info = getSymbolInfo(**symbol); 969 symtab32[symtabIdx].st_other = (*symbol)->visibility(); 970 symtab32[symtabIdx].st_shndx = getSymbolShndx(**symbol, pLayout); 971 } 972 else { // must 64 973 symtab64[symtabIdx].st_name = strtabsize; 974 symtab64[symtabIdx].st_value = (*symbol)->value(); 975 symtab64[symtabIdx].st_size = getSymbolSize(**symbol); 976 symtab64[symtabIdx].st_info = getSymbolInfo(**symbol); 977 symtab64[symtabIdx].st_other = (*symbol)->visibility(); 978 symtab64[symtabIdx].st_shndx = getSymbolShndx(**symbol, pLayout); 979 } 980 // write out string 981 strcpy((strtab + strtabsize), (*symbol)->name()); 982 983 // sum up counters 984 ++symtabIdx; 985 strtabsize += (*symbol)->nameSize() + 1; 986 } 987 988 // emit DT_NEED 989 // add DT_NEED strings into .dynstr 990 // Rules: 991 // 1. ignore --no-add-needed 992 // 2. force count in --no-as-needed 993 // 3. judge --as-needed 994 ELFDynamic::iterator dt_need = dynamic().needBegin(); 995 InputTree::const_bfs_iterator input, inputEnd = pLDInfo.inputs().bfs_end(); 996 for (input = pLDInfo.inputs().bfs_begin(); input != inputEnd; ++input) { 997 if (Input::DynObj == (*input)->type()) { 998 // --add-needed 999 if ((*input)->attribute()->isAddNeeded()) { 1000 // --no-as-needed 1001 if (!(*input)->attribute()->isAsNeeded()) { 1002 strcpy((strtab + strtabsize), (*input)->name().c_str()); 1003 (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize); 1004 strtabsize += (*input)->name().size() + 1; 1005 ++dt_need; 1006 } 1007 // --as-needed 1008 else if ((*input)->isNeeded()) { 1009 strcpy((strtab + strtabsize), (*input)->name().c_str()); 1010 (*dt_need)->setValue(llvm::ELF::DT_NEEDED, strtabsize); 1011 strtabsize += (*input)->name().size() + 1; 1012 ++dt_need; 1013 } 1014 } 1015 } 1016 } // for 1017 1018 // emit soname 1019 // initialize value of ELF .dynamic section 1020 if (Output::DynObj == pOutput.type()) 1021 dynamic().applySoname(strtabsize); 1022 dynamic().applyEntries(pLDInfo, *file_format); 1023 dynamic().emit(dyn_sect, *dyn_region); 1024 1025 strcpy((strtab + strtabsize), pOutput.name().c_str()); 1026 strtabsize += pOutput.name().size() + 1; 1027 1028 // emit hash table 1029 // FIXME: this verion only emit SVR4 hash section. 1030 // Please add GNU new hash section 1031 1032 // both 32 and 64 bits hash table use 32-bit entry 1033 // set up hash_region 1034 uint32_t* word_array = (uint32_t*)hash_region->start(); 1035 uint32_t& nbucket = word_array[0]; 1036 uint32_t& nchain = word_array[1]; 1037 1038 nbucket = getHashBucketCount(symtabIdx, false); 1039 nchain = symtabIdx; 1040 1041 uint32_t* bucket = (word_array + 2); 1042 uint32_t* chain = (bucket + nbucket); 1043 1044 // initialize bucket 1045 bzero((void*)bucket, nbucket); 1046 1047 StringHash<ELF> hash_func; 1048 1049 if (32 == bitclass()) { 1050 for (size_t sym_idx=0; sym_idx < symtabIdx; ++sym_idx) { 1051 llvm::StringRef name(strtab + symtab32[sym_idx].st_name); 1052 size_t bucket_pos = hash_func(name) % nbucket; 1053 chain[sym_idx] = bucket[bucket_pos]; 1054 bucket[bucket_pos] = sym_idx; 1055 } 1056 } 1057 else if (64 == bitclass()) { 1058 for (size_t sym_idx=0; sym_idx < symtabIdx; ++sym_idx) { 1059 llvm::StringRef name(strtab + symtab64[sym_idx].st_name); 1060 size_t bucket_pos = hash_func(name) % nbucket; 1061 chain[sym_idx] = bucket[bucket_pos]; 1062 bucket[bucket_pos] = sym_idx; 1063 } 1064 } 1065} 1066 1067/// sizeInterp - compute the size of the .interp section 1068void GNULDBackend::sizeInterp(const Output& pOutput, const MCLDInfo& pLDInfo) 1069{ 1070 assert(pOutput.type() == Output::Exec); 1071 1072 const char* dyld_name; 1073 if (pLDInfo.options().hasDyld()) 1074 dyld_name = pLDInfo.options().dyld().c_str(); 1075 else 1076 dyld_name = dyld(); 1077 1078 LDSection& interp = getExecFileFormat()->getInterp(); 1079 interp.setSize(std::strlen(dyld_name) + 1); 1080} 1081 1082/// emitInterp - emit the .interp 1083void GNULDBackend::emitInterp(Output& pOutput, const MCLDInfo& pLDInfo) 1084{ 1085 assert(pOutput.type() == Output::Exec && 1086 getExecFileFormat()->hasInterp() && 1087 pOutput.hasMemArea()); 1088 1089 const LDSection& interp = getExecFileFormat()->getInterp(); 1090 MemoryRegion *region = pOutput.memArea()->request( 1091 interp.offset(), interp.size()); 1092 const char* dyld_name; 1093 if (pLDInfo.options().hasDyld()) 1094 dyld_name = pLDInfo.options().dyld().c_str(); 1095 else 1096 dyld_name = dyld(); 1097 1098 std::memcpy(region->start(), dyld_name, interp.size()); 1099} 1100 1101/// getSectionOrder 1102unsigned int GNULDBackend::getSectionOrder(const Output& pOutput, 1103 const LDSection& pSectHdr, 1104 const MCLDInfo& pInfo) const 1105{ 1106 // NULL section should be the "1st" section 1107 if (LDFileFormat::Null == pSectHdr.kind()) 1108 return 0; 1109 1110 // if the section is not ALLOC, lay it out until the last possible moment 1111 if (0 == (pSectHdr.flag() & llvm::ELF::SHF_ALLOC)) 1112 return SHO_UNDEFINED; 1113 1114 bool is_write = (pSectHdr.flag() & llvm::ELF::SHF_WRITE) != 0; 1115 bool is_exec = (pSectHdr.flag() & llvm::ELF::SHF_EXECINSTR) != 0; 1116 const ELFFileFormat* file_format = getOutputFormat(pOutput); 1117 1118 // TODO: need to take care other possible output sections 1119 switch (pSectHdr.kind()) { 1120 case LDFileFormat::Regular: 1121 if (is_exec) { 1122 if (&pSectHdr == &file_format->getInit()) 1123 return SHO_INIT; 1124 if (&pSectHdr == &file_format->getFini()) 1125 return SHO_FINI; 1126 return SHO_TEXT; 1127 } else if (!is_write) { 1128 return SHO_RO; 1129 } else { 1130 if (pInfo.options().hasRelro()) { 1131 if (pSectHdr.type() == llvm::ELF::SHT_PREINIT_ARRAY || 1132 pSectHdr.type() == llvm::ELF::SHT_INIT_ARRAY || 1133 pSectHdr.type() == llvm::ELF::SHT_FINI_ARRAY || 1134 &pSectHdr == &file_format->getCtors() || 1135 &pSectHdr == &file_format->getDtors() || 1136 &pSectHdr == &file_format->getJCR() || 1137 0 == pSectHdr.name().compare(".data.rel.ro")) 1138 return SHO_RELRO; 1139 if (0 == pSectHdr.name().compare(".data.rel.ro.local")) 1140 return SHO_RELRO_LOCAL; 1141 } 1142 return SHO_DATA; 1143 } 1144 1145 case LDFileFormat::BSS: 1146 return SHO_BSS; 1147 1148 case LDFileFormat::NamePool: 1149 if (&pSectHdr == &file_format->getDynamic()) 1150 return SHO_RELRO; 1151 return SHO_NAMEPOOL; 1152 1153 case LDFileFormat::Relocation: 1154 if (&pSectHdr == &file_format->getRelPlt() || 1155 &pSectHdr == &file_format->getRelaPlt()) 1156 return SHO_REL_PLT; 1157 return SHO_RELOCATION; 1158 1159 // get the order from target for target specific sections 1160 case LDFileFormat::Target: 1161 return getTargetSectionOrder(pOutput, pSectHdr, pInfo); 1162 1163 // handle .interp 1164 case LDFileFormat::Note: 1165 return SHO_INTERP; 1166 1167 case LDFileFormat::EhFrame: 1168 case LDFileFormat::EhFrameHdr: 1169 case LDFileFormat::GCCExceptTable: 1170 return SHO_EXCEPTION; 1171 1172 case LDFileFormat::MetaData: 1173 case LDFileFormat::Debug: 1174 default: 1175 return SHO_UNDEFINED; 1176 } 1177} 1178 1179/// getSymbolSize 1180uint64_t GNULDBackend::getSymbolSize(const LDSymbol& pSymbol) const 1181{ 1182 // @ref Google gold linker: symtab.cc: 2780 1183 // undefined and dynamic symbols should have zero size. 1184 if (pSymbol.isDyn() || pSymbol.desc() == ResolveInfo::Undefined) 1185 return 0x0; 1186 return pSymbol.resolveInfo()->size(); 1187} 1188 1189/// getSymbolInfo 1190uint64_t GNULDBackend::getSymbolInfo(const LDSymbol& pSymbol) const 1191{ 1192 // set binding 1193 uint8_t bind = 0x0; 1194 if (pSymbol.resolveInfo()->isLocal()) 1195 bind = llvm::ELF::STB_LOCAL; 1196 else if (pSymbol.resolveInfo()->isGlobal()) 1197 bind = llvm::ELF::STB_GLOBAL; 1198 else if (pSymbol.resolveInfo()->isWeak()) 1199 bind = llvm::ELF::STB_WEAK; 1200 else if (pSymbol.resolveInfo()->isAbsolute()) { 1201 // (Luba) Is a absolute but not global (weak or local) symbol meaningful? 1202 bind = llvm::ELF::STB_GLOBAL; 1203 } 1204 1205 if (pSymbol.visibility() == llvm::ELF::STV_INTERNAL || 1206 pSymbol.visibility() == llvm::ELF::STV_HIDDEN) 1207 bind = llvm::ELF::STB_LOCAL; 1208 1209 uint32_t type = pSymbol.resolveInfo()->type(); 1210 // if the IndirectFunc symbol (i.e., STT_GNU_IFUNC) is from dynobj, change 1211 // its type to Function 1212 if (type == ResolveInfo::IndirectFunc && pSymbol.isDyn()) 1213 type = ResolveInfo::Function; 1214 return (type | (bind << 4)); 1215} 1216 1217/// getSymbolValue - this function is called after layout() 1218uint64_t GNULDBackend::getSymbolValue(const LDSymbol& pSymbol) const 1219{ 1220 if (pSymbol.isDyn()) 1221 return 0x0; 1222 1223 return pSymbol.value(); 1224} 1225 1226/// getSymbolShndx - this function is called after layout() 1227uint64_t 1228GNULDBackend::getSymbolShndx(const LDSymbol& pSymbol, const Layout& pLayout) const 1229{ 1230 if (pSymbol.resolveInfo()->isAbsolute()) 1231 return llvm::ELF::SHN_ABS; 1232 if (pSymbol.resolveInfo()->isCommon()) 1233 return llvm::ELF::SHN_COMMON; 1234 if (pSymbol.resolveInfo()->isUndef() || pSymbol.isDyn()) 1235 return llvm::ELF::SHN_UNDEF; 1236 1237 if (pSymbol.resolveInfo()->isLocal()) { 1238 switch (pSymbol.type()) { 1239 case ResolveInfo::NoType: 1240 case ResolveInfo::File: 1241 return llvm::ELF::SHN_ABS; 1242 } 1243 } 1244 1245 assert(pSymbol.hasFragRef() && "symbols must have fragment reference to get its index"); 1246 return pLayout.getOutputLDSection(*pSymbol.fragRef()->frag())->index(); 1247} 1248 1249/// getSymbolIdx - called by emitRelocation to get the ouput symbol table index 1250size_t GNULDBackend::getSymbolIdx(LDSymbol* pSymbol) const 1251{ 1252 HashTableType::iterator entry = m_pSymIndexMap->find(pSymbol); 1253 return entry.getEntry()->value(); 1254} 1255 1256/// allocateCommonSymbols - allocate common symbols in the corresponding 1257/// sections. 1258/// @refer Google gold linker: common.cc: 214 1259bool 1260GNULDBackend::allocateCommonSymbols(const MCLDInfo& pInfo, MCLinker& pLinker) const 1261{ 1262 SymbolCategory& symbol_list = pLinker.getOutputSymbols(); 1263 1264 if (symbol_list.emptyCommons() && symbol_list.emptyLocals()) 1265 return true; 1266 1267 SymbolCategory::iterator com_sym, com_end; 1268 1269 // FIXME: If the order of common symbols is defined, then sort common symbols 1270 // std::sort(com_sym, com_end, some kind of order); 1271 1272 // get or create corresponding BSS LDSection 1273 LDSection* bss_sect = &pLinker.getOrCreateOutputSectHdr(".bss", 1274 LDFileFormat::BSS, 1275 llvm::ELF::SHT_NOBITS, 1276 llvm::ELF::SHF_WRITE | llvm::ELF::SHF_ALLOC); 1277 1278 LDSection* tbss_sect = &pLinker.getOrCreateOutputSectHdr( 1279 ".tbss", 1280 LDFileFormat::BSS, 1281 llvm::ELF::SHT_NOBITS, 1282 llvm::ELF::SHF_WRITE | llvm::ELF::SHF_ALLOC); 1283 1284 assert(NULL != bss_sect && NULL !=tbss_sect); 1285 1286 // get or create corresponding BSS MCSectionData 1287 llvm::MCSectionData& bss_sect_data = pLinker.getOrCreateSectData(*bss_sect); 1288 llvm::MCSectionData& tbss_sect_data = pLinker.getOrCreateSectData(*tbss_sect); 1289 1290 // remember original BSS size 1291 uint64_t bss_offset = bss_sect->size(); 1292 uint64_t tbss_offset = tbss_sect->size(); 1293 1294 // allocate all local common symbols 1295 com_end = symbol_list.localEnd(); 1296 1297 for (com_sym = symbol_list.localBegin(); com_sym != com_end; ++com_sym) { 1298 if (ResolveInfo::Common == (*com_sym)->desc()) { 1299 // We have to reset the description of the symbol here. When doing 1300 // incremental linking, the output relocatable object may have common 1301 // symbols. Therefore, we can not treat common symbols as normal symbols 1302 // when emitting the regular name pools. We must change the symbols' 1303 // description here. 1304 (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define); 1305 llvm::MCFragment* frag = new llvm::MCFillFragment(0x0, 1, (*com_sym)->size()); 1306 (*com_sym)->setFragmentRef(new MCFragmentRef(*frag, 0)); 1307 1308 if (ResolveInfo::ThreadLocal == (*com_sym)->type()) { 1309 // allocate TLS common symbol in tbss section 1310 tbss_offset += pLinker.getLayout().appendFragment(*frag, 1311 tbss_sect_data, 1312 (*com_sym)->value()); 1313 } 1314 else { 1315 bss_offset += pLinker.getLayout().appendFragment(*frag, 1316 bss_sect_data, 1317 (*com_sym)->value()); 1318 } 1319 } 1320 } 1321 1322 // allocate all global common symbols 1323 com_end = symbol_list.commonEnd(); 1324 for (com_sym = symbol_list.commonBegin(); com_sym != com_end; ++com_sym) { 1325 // We have to reset the description of the symbol here. When doing 1326 // incremental linking, the output relocatable object may have common 1327 // symbols. Therefore, we can not treat common symbols as normal symbols 1328 // when emitting the regular name pools. We must change the symbols' 1329 // description here. 1330 (*com_sym)->resolveInfo()->setDesc(ResolveInfo::Define); 1331 llvm::MCFragment* frag = new llvm::MCFillFragment(0x0, 1, (*com_sym)->size()); 1332 (*com_sym)->setFragmentRef(new MCFragmentRef(*frag, 0)); 1333 1334 if (ResolveInfo::ThreadLocal == (*com_sym)->type()) { 1335 // allocate TLS common symbol in tbss section 1336 tbss_offset += pLinker.getLayout().appendFragment(*frag, 1337 tbss_sect_data, 1338 (*com_sym)->value()); 1339 } 1340 else { 1341 bss_offset += pLinker.getLayout().appendFragment(*frag, 1342 bss_sect_data, 1343 (*com_sym)->value()); 1344 } 1345 } 1346 1347 bss_sect->setSize(bss_offset); 1348 tbss_sect->setSize(tbss_offset); 1349 symbol_list.changeCommonsToGlobal(); 1350 return true; 1351} 1352 1353 1354/// createProgramHdrs - base on output sections to create the program headers 1355void GNULDBackend::createProgramHdrs(Output& pOutput, const MCLDInfo& pInfo) 1356{ 1357 assert(pOutput.hasContext()); 1358 ELFFileFormat *file_format = getOutputFormat(pOutput); 1359 1360 // make PT_PHDR 1361 m_ELFSegmentTable.produce(llvm::ELF::PT_PHDR); 1362 1363 // make PT_INTERP 1364 if (file_format->hasInterp()) { 1365 ELFSegment* interp_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_INTERP); 1366 interp_seg->addSection(&file_format->getInterp()); 1367 } 1368 1369 if (pInfo.options().hasRelro()) { 1370 // if -z relro is given, we need to adjust sections' offset again, and let 1371 // PT_GNU_RELRO end on a common page boundary 1372 LDContext::SectionTable& sect_table = pOutput.context()->getSectionTable(); 1373 size_t idx = 0; 1374 while (idx < pOutput.context()->numOfSections()) { 1375 // find the first non-relro section, and align its offset to a page 1376 // boundary 1377 if (getSectionOrder(pOutput, *sect_table[idx], pInfo) > SHO_RELRO_LAST) { 1378 uint64_t offset = sect_table[idx]->offset(); 1379 alignAddress(offset, commonPageSize(pInfo)); 1380 sect_table[idx]->setOffset(offset); 1381 ++idx; 1382 break; 1383 } 1384 ++idx; 1385 } 1386 while (idx < pOutput.context()->numOfSections()) { 1387 // adjust the remaining sections' offset 1388 uint64_t offset = sect_table[idx - 1]->offset(); 1389 if (LDFileFormat::BSS != sect_table[idx - 1]->kind()) 1390 offset += sect_table[idx - 1]->size(); 1391 alignAddress(offset, sect_table[idx]->align()); 1392 sect_table[idx]->setOffset(offset); 1393 ++idx; 1394 } 1395 } 1396 1397 uint32_t cur_seg_flag, prev_seg_flag = getSegmentFlag(0); 1398 uint64_t padding = 0; 1399 ELFSegment* load_seg = NULL; 1400 // make possible PT_LOAD segments 1401 LDContext::sect_iterator sect, sect_end = pOutput.context()->sectEnd(); 1402 for (sect = pOutput.context()->sectBegin(); sect != sect_end; ++sect) { 1403 1404 if (0 == ((*sect)->flag() & llvm::ELF::SHF_ALLOC) && 1405 LDFileFormat::Null != (*sect)->kind()) 1406 continue; 1407 1408 // FIXME: Now only separate writable and non-writable PT_LOAD 1409 cur_seg_flag = getSegmentFlag((*sect)->flag()); 1410 if ((prev_seg_flag & llvm::ELF::PF_W) ^ (cur_seg_flag & llvm::ELF::PF_W) || 1411 LDFileFormat::Null == (*sect)->kind()) { 1412 // create new PT_LOAD segment 1413 load_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_LOAD); 1414 load_seg->setAlign(commonPageSize(pInfo)); 1415 1416 // check if this segment needs padding 1417 padding = 0; 1418 if (((*sect)->offset() & (abiPageSize(pInfo) - 1)) != 0) 1419 padding = abiPageSize(pInfo); 1420 } 1421 1422 assert(NULL != load_seg); 1423 load_seg->addSection((*sect)); 1424 if (cur_seg_flag != prev_seg_flag) 1425 load_seg->updateFlag(cur_seg_flag); 1426 1427 if (LDFileFormat::Null != (*sect)->kind()) 1428 (*sect)->setAddr(segmentStartAddr(pOutput, pInfo) + 1429 (*sect)->offset() + 1430 padding); 1431 1432 prev_seg_flag = cur_seg_flag; 1433 } 1434 1435 // make PT_DYNAMIC 1436 if (file_format->hasDynamic()) { 1437 ELFSegment* dyn_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_DYNAMIC, 1438 llvm::ELF::PF_R | 1439 llvm::ELF::PF_W); 1440 dyn_seg->addSection(&file_format->getDynamic()); 1441 } 1442 1443 if (pInfo.options().hasRelro()) { 1444 // make PT_GNU_RELRO 1445 ELFSegment* relro_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_RELRO); 1446 for (LDContext::sect_iterator sect = pOutput.context()->sectBegin(); 1447 sect != pOutput.context()->sectEnd(); ++sect) { 1448 unsigned int order = getSectionOrder(pOutput, **sect, pInfo); 1449 if (SHO_RELRO_LOCAL == order || 1450 SHO_RELRO == order || 1451 SHO_RELRO_LAST == order) { 1452 relro_seg->addSection(*sect); 1453 } 1454 } 1455 } 1456 1457 // make PT_GNU_EH_FRAME 1458 if (file_format->hasEhFrameHdr()) { 1459 ELFSegment* eh_seg = m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_EH_FRAME); 1460 eh_seg->addSection(&file_format->getEhFrameHdr()); 1461 } 1462} 1463 1464/// setupProgramHdrs - set up the attributes of segments 1465void GNULDBackend:: setupProgramHdrs(const Output& pOutput, const MCLDInfo& pInfo) 1466{ 1467 // update segment info 1468 ELFSegmentFactory::iterator seg, seg_end = m_ELFSegmentTable.end(); 1469 for (seg = m_ELFSegmentTable.begin(); seg != seg_end; ++seg) { 1470 ELFSegment& segment = *seg; 1471 1472 // update PT_PHDR 1473 if (llvm::ELF::PT_PHDR == segment.type()) { 1474 uint64_t offset, phdr_size; 1475 if (32 == bitclass()) { 1476 offset = sizeof(llvm::ELF::Elf32_Ehdr); 1477 phdr_size = sizeof(llvm::ELF::Elf32_Phdr); 1478 } 1479 else { 1480 offset = sizeof(llvm::ELF::Elf64_Ehdr); 1481 phdr_size = sizeof(llvm::ELF::Elf64_Phdr); 1482 } 1483 segment.setOffset(offset); 1484 segment.setVaddr(segmentStartAddr(pOutput, pInfo) + offset); 1485 segment.setPaddr(segment.vaddr()); 1486 segment.setFilesz(numOfSegments() * phdr_size); 1487 segment.setMemsz(numOfSegments() * phdr_size); 1488 segment.setAlign(bitclass() / 8); 1489 continue; 1490 } 1491 1492 // bypass if there is no section in this segment (e.g., PT_GNU_STACK) 1493 if (segment.numOfSections() == 0) 1494 continue; 1495 1496 segment.setOffset(segment.getFirstSection()->offset()); 1497 if (llvm::ELF::PT_LOAD == segment.type() && 1498 LDFileFormat::Null == segment.getFirstSection()->kind()) 1499 segment.setVaddr(segmentStartAddr(pOutput, pInfo)); 1500 else 1501 segment.setVaddr(segment.getFirstSection()->addr()); 1502 segment.setPaddr(segment.vaddr()); 1503 1504 const LDSection* last_sect = segment.getLastSection(); 1505 assert(NULL != last_sect); 1506 uint64_t file_size = last_sect->offset() - segment.offset(); 1507 if (LDFileFormat::BSS != last_sect->kind()) 1508 file_size += last_sect->size(); 1509 segment.setFilesz(file_size); 1510 1511 segment.setMemsz(last_sect->addr() - segment.vaddr() + last_sect->size()); 1512 } 1513} 1514 1515/// createGNUStackInfo - create an output GNU stack section or segment if needed 1516/// @ref gold linker: layout.cc:2608 1517void GNULDBackend::createGNUStackInfo(const Output& pOutput, 1518 const MCLDInfo& pInfo, 1519 MCLinker& pLinker) 1520{ 1521 uint32_t flag = 0x0; 1522 if (pInfo.options().hasStackSet()) { 1523 // 1. check the command line option (-z execstack or -z noexecstack) 1524 if (pInfo.options().hasExecStack()) 1525 flag = llvm::ELF::SHF_EXECINSTR; 1526 } else { 1527 // 2. check the stack info from the input objects 1528 size_t object_count = 0, stack_note_count = 0; 1529 mcld::InputTree::const_bfs_iterator input, inEnd = pInfo.inputs().bfs_end(); 1530 for (input=pInfo.inputs().bfs_begin(); input!=inEnd; ++input) { 1531 if ((*input)->type() == Input::Object) { 1532 ++object_count; 1533 const LDSection* sect = (*input)->context()->getSection( 1534 ".note.GNU-stack"); 1535 if (NULL != sect) { 1536 ++stack_note_count; 1537 // 2.1 found a stack note that is set as executable 1538 if (0 != (llvm::ELF::SHF_EXECINSTR & sect->flag())) { 1539 flag = llvm::ELF::SHF_EXECINSTR; 1540 break; 1541 } 1542 } 1543 } 1544 } 1545 1546 // 2.2 there are no stack note sections in all input objects 1547 if (0 == stack_note_count) 1548 return; 1549 1550 // 2.3 a special case. Use the target default to decide if the stack should 1551 // be executable 1552 if (llvm::ELF::SHF_EXECINSTR != flag && object_count != stack_note_count) 1553 if (isDefaultExecStack()) 1554 flag = llvm::ELF::SHF_EXECINSTR; 1555 } 1556 1557 if (pOutput.type() != Output::Object) 1558 m_ELFSegmentTable.produce(llvm::ELF::PT_GNU_STACK, 1559 llvm::ELF::PF_R | 1560 llvm::ELF::PF_W | 1561 getSegmentFlag(flag)); 1562 else 1563 pLinker.getOrCreateOutputSectHdr(".note.GNU-stack", 1564 LDFileFormat::Note, 1565 llvm::ELF::SHT_PROGBITS, 1566 flag); 1567} 1568 1569/// preLayout - Backend can do any needed modification before layout 1570void GNULDBackend::preLayout(const Output& pOutput, 1571 const MCLDInfo& pLDInfo, 1572 MCLinker& pLinker) 1573{ 1574 // prelayout target first 1575 doPreLayout(pOutput, pLDInfo, pLinker); 1576 1577 if (pLDInfo.options().hasEhFrameHdr()) { 1578 // init EhFrameHdr and size the output section 1579 ELFFileFormat* format = getOutputFormat(pOutput); 1580 assert(NULL != getEhFrame()); 1581 m_pEhFrameHdr = new EhFrameHdr(*getEhFrame(), 1582 format->getEhFrame(), 1583 format->getEhFrameHdr()); 1584 m_pEhFrameHdr->sizeOutput(); 1585 } 1586} 1587 1588/// postLayout -Backend can do any needed modification after layout 1589void GNULDBackend::postLayout(const Output& pOutput, 1590 const MCLDInfo& pInfo, 1591 MCLinker& pLinker) 1592{ 1593 // 1. emit program headers 1594 if (pOutput.type() != Output::Object) { 1595 // 1.1 create program headers 1596 createProgramHdrs(pLinker.getLDInfo().output(), pInfo); 1597 } 1598 1599 // 1.2 create special GNU Stack note section or segment 1600 createGNUStackInfo(pOutput, pInfo, pLinker); 1601 1602 if (pOutput.type() != Output::Object) { 1603 // 1.3 set up the attributes of program headers 1604 setupProgramHdrs(pOutput, pInfo); 1605 } 1606 1607 // 2. target specific post layout 1608 doPostLayout(pOutput, pInfo, pLinker); 1609} 1610 1611void GNULDBackend::postProcessing(const Output& pOutput, 1612 const MCLDInfo& pInfo, 1613 MCLinker& pLinker) 1614{ 1615 if (pInfo.options().hasEhFrameHdr()) { 1616 // emit eh_frame_hdr 1617 if (bitclass() == 32) 1618 m_pEhFrameHdr->emitOutput<32>(pLinker.getLDInfo().output(), 1619 pLinker); 1620 } 1621} 1622 1623/// getHashBucketCount - calculate hash bucket count. 1624/// @ref Google gold linker, dynobj.cc:791 1625unsigned GNULDBackend::getHashBucketCount(unsigned pNumOfSymbols, 1626 bool pIsGNUStyle) 1627{ 1628 // @ref Google gold, dynobj.cc:loc 791 1629 static const unsigned int buckets[] = 1630 { 1631 1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209, 1632 16411, 32771, 65537, 131101, 262147 1633 }; 1634 const unsigned buckets_count = sizeof buckets / sizeof buckets[0]; 1635 1636 unsigned int result = 1; 1637 for (unsigned i = 0; i < buckets_count; ++i) { 1638 if (pNumOfSymbols < buckets[i]) 1639 break; 1640 result = buckets[i]; 1641 } 1642 1643 if (pIsGNUStyle && result < 2) 1644 result = 2; 1645 1646 return result; 1647} 1648 1649/// isDynamicSymbol 1650/// @ref Google gold linker: symtab.cc:311 1651bool GNULDBackend::isDynamicSymbol(const LDSymbol& pSymbol, 1652 const Output& pOutput) 1653{ 1654 // If a local symbol is in the LDContext's symbol table, it's a real local 1655 // symbol. We should not add it 1656 if (pSymbol.binding() == ResolveInfo::Local) 1657 return false; 1658 1659 // If we are building shared object, and the visibility is external, we 1660 // need to add it. 1661 if (Output::DynObj == pOutput.type() || Output::Exec == pOutput.type()) 1662 if (pSymbol.resolveInfo()->visibility() == ResolveInfo::Default || 1663 pSymbol.resolveInfo()->visibility() == ResolveInfo::Protected) 1664 return true; 1665 return false; 1666} 1667 1668/// commonPageSize - the common page size of the target machine. 1669/// @ref gold linker: target.h:135 1670uint64_t GNULDBackend::commonPageSize(const MCLDInfo& pInfo) const 1671{ 1672 if (pInfo.options().commPageSize() > 0) 1673 return std::min(pInfo.options().commPageSize(), abiPageSize(pInfo)); 1674 else 1675 return std::min(static_cast<uint64_t>(0x1000), abiPageSize(pInfo)); 1676} 1677 1678/// abiPageSize - the abi page size of the target machine. 1679/// @ref gold linker: target.h:125 1680uint64_t GNULDBackend::abiPageSize(const MCLDInfo& pInfo) const 1681{ 1682 if (pInfo.options().maxPageSize() > 0) 1683 return pInfo.options().maxPageSize(); 1684 else 1685 return static_cast<uint64_t>(0x1000); 1686} 1687 1688/// isOutputPIC - return whether the output is position-independent 1689bool GNULDBackend::isOutputPIC(const Output& pOutput, 1690 const MCLDInfo& pInfo) const 1691{ 1692 if (Output::DynObj == pOutput.type() || pInfo.options().isPIE()) 1693 return true; 1694 return false; 1695} 1696 1697/// isStaticLink - return whether we're doing static link 1698bool GNULDBackend::isStaticLink(const Output& pOutput, 1699 const MCLDInfo& pInfo) const 1700{ 1701 InputTree::const_iterator it = pInfo.inputs().begin(); 1702 if (!isOutputPIC(pOutput, pInfo) && (*it)->attribute()->isStatic()) 1703 return true; 1704 return false; 1705} 1706 1707/// isSymbolPreemtible - whether the symbol can be preemted by other 1708/// link unit 1709/// @ref Google gold linker, symtab.h:551 1710bool GNULDBackend::isSymbolPreemptible(const ResolveInfo& pSym, 1711 const MCLDInfo& pLDInfo, 1712 const Output& pOutput) const 1713{ 1714 if (pSym.other() != ResolveInfo::Default) 1715 return false; 1716 1717 if (Output::DynObj != pOutput.type()) 1718 return false; 1719 1720 if (pLDInfo.options().Bsymbolic()) 1721 return false; 1722 1723 return true; 1724} 1725 1726/// symbolNeedsPLT - return whether the symbol needs a PLT entry 1727/// @ref Google gold linker, symtab.h:596 1728bool GNULDBackend::symbolNeedsPLT(const ResolveInfo& pSym, 1729 const MCLDInfo& pLDInfo, 1730 const Output& pOutput) const 1731{ 1732 if (pSym.isUndef() && !pSym.isDyn() && pOutput.type() != Output::DynObj) 1733 return false; 1734 1735 // An IndirectFunc symbol (i.e., STT_GNU_IFUNC) always needs a plt entry 1736 if (pSym.type() == ResolveInfo::IndirectFunc) 1737 return true; 1738 1739 if (pSym.type() != ResolveInfo::Function) 1740 return false; 1741 1742 if (isStaticLink(pOutput, pLDInfo) || pLDInfo.options().isPIE()) 1743 return false; 1744 1745 return (pSym.isDyn() || 1746 pSym.isUndef() || 1747 isSymbolPreemptible(pSym, pLDInfo, pOutput)); 1748} 1749 1750/// symbolNeedsDynRel - return whether the symbol needs a dynamic relocation 1751/// @ref Google gold linker, symtab.h:645 1752bool GNULDBackend::symbolNeedsDynRel(const ResolveInfo& pSym, 1753 bool pSymHasPLT, 1754 const MCLDInfo& pLDInfo, 1755 const Output& pOutput, 1756 bool isAbsReloc) const 1757{ 1758 // an undefined reference in the executables should be statically 1759 // resolved to 0 and no need a dynamic relocation 1760 if (pSym.isUndef() && !pSym.isDyn() && (Output::Exec == pOutput.type())) 1761 return false; 1762 if (pSym.isAbsolute()) 1763 return false; 1764 if (isOutputPIC(pOutput, pLDInfo) && isAbsReloc) 1765 return true; 1766 if (pSymHasPLT && ResolveInfo::Function == pSym.type()) 1767 return false; 1768 if (!isOutputPIC(pOutput, pLDInfo) && pSymHasPLT) 1769 return false; 1770 if (pSym.isDyn() || pSym.isUndef() || 1771 isSymbolPreemptible(pSym, pLDInfo, pOutput)) 1772 return true; 1773 1774 return false; 1775} 1776 1777/// symbolNeedsCopyReloc - return whether the symbol needs a copy relocation 1778bool GNULDBackend::symbolNeedsCopyReloc(const Layout& pLayout, 1779 const Relocation& pReloc, 1780 const ResolveInfo& pSym, 1781 const MCLDInfo& pLDInfo, 1782 const Output& pOutput) const 1783{ 1784 // only the reference from dynamic executable to non-function symbol in 1785 // the dynamic objects may need copy relocation 1786 if (isOutputPIC(pOutput, pLDInfo) || 1787 !pSym.isDyn() || 1788 pSym.type() == ResolveInfo::Function || 1789 pSym.size() == 0) 1790 return false; 1791 1792 // check if the option -z nocopyreloc is given 1793 if (pLDInfo.options().hasNoCopyReloc()) 1794 return false; 1795 1796 // TODO: Is this check necessary? 1797 // if relocation target place is readonly, a copy relocation is needed 1798 if ((pLayout.getOutputLDSection(*pReloc.targetRef().frag())->flag() & 1799 llvm::ELF::SHF_WRITE) == 0) 1800 return true; 1801 1802 return false; 1803} 1804 1805