\input texinfo@c Copyright 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998,@c 2000, 2001, 2002, 2003, 2004@c Free Software Foundation, Inc.@setfilename bfdint.info@settitle BFD Internals@iftex@titlepage@title{BFD Internals}@author{Ian Lance Taylor}@author{Cygnus Solutions}@page@end iftex@node Top@top BFD Internals@raisesections@cindex bfd internalsThis document describes some BFD internal information which may behelpful when working on BFD. It is very incomplete.This document is not updated regularly, and may be out of date.The initial version of this document was written by Ian Lance Taylor@email{ian@@cygnus.com}.@menu* BFD overview:: BFD overview* BFD guidelines:: BFD programming guidelines* BFD target vector:: BFD target vector* BFD generated files:: BFD generated files* BFD multiple compilations:: Files compiled multiple times in BFD* BFD relocation handling:: BFD relocation handling* BFD ELF support:: BFD ELF support* BFD glossary:: Glossary* Index:: Index@end menu@node BFD overview@section BFD overviewBFD is a library which provides a single interface to read and writeobject files, executables, archive files, and core files in any format.@menu* BFD library interfaces:: BFD library interfaces* BFD library users:: BFD library users* BFD view:: The BFD view of a file* BFD blindness:: BFD loses information@end menu@node BFD library interfaces@subsection BFD library interfacesOne way to look at the BFD library is to divide it into four parts bytype of interface.The first interface is the set of generic functions which programs usingthe BFD library will call. These generic function normally translatedirectly or indirectly into calls to routines which are specific to aparticular object file format. Many of these generic functions areactually defined as macros in @file{bfd.h}. These functions comprisethe official BFD interface.The second interface is the set of functions which appear in the targetvectors. This is the bulk of the code in BFD. A target vector is a setof function pointers specific to a particular object file format. Thetarget vector is used to implement the generic BFD functions. Thesefunctions are always called through the target vector, and are nevercalled directly. The target vector is described in detail in @ref{BFDtarget vector}. The set of functions which appear in a particulartarget vector is often referred to as a BFD backend.The third interface is a set of oddball functions which are typicallyspecific to a particular object file format, are not generic functions,and are called from outside of the BFD library. These are used as hooksby the linker and the assembler when a particular object file formatrequires some action which the BFD generic interface does not provide.These functions are typically declared in @file{bfd.h}, but in manycases they are only provided when BFD is configured with support for aparticular object file format. These functions live in a grey area, andare not really part of the official BFD interface.The fourth interface is the set of BFD support functions which arecalled by the other BFD functions. These manage issues like memoryallocation, error handling, file access, hash tables, swapping, and thelike. These functions are never called from outside of the BFD library.@node BFD library users@subsection BFD library usersAnother way to look at the BFD library is to divide it into three partsby the manner in which it is used.The first use is to read an object file. The object file readers areprograms like @samp{gdb}, @samp{nm}, @samp{objdump}, and @samp{objcopy}.These programs use BFD to view an object file in a generic form. Theofficial BFD interface is normally fully adequate for these programs.The second use is to write an object file. The object file writers areprograms like @samp{gas} and @samp{objcopy}. These programs use BFD tocreate an object file. The official BFD interface is normally adequatefor these programs, but for some object file formats the assembler needssome additional hooks in order to set particular flags or otherinformation. The official BFD interface includes functions to copyprivate information from one object file to another, and these functionsare used by @samp{objcopy} to avoid information loss.The third use is to link object files. There is only one object filelinker, @samp{ld}. Originally, @samp{ld} was an object file reader andan object file writer, and it did the link operation using the genericBFD structures. However, this turned out to be too slow and too memoryintensive.The official BFD linker functions were written to permit specific BFDbackends to perform the link without translating through the genericstructures, in the normal case where all the input files and output filehave the same object file format. Not all of the backends currentlyimplement the new interface, and there are default linking functionswithin BFD which use the generic structures and which work with allbackends.For several object file formats the linker needs additional hooks whichare not provided by the official BFD interface, particularly for dynamiclinking support. These functions are typically called from the linkeremulation template.@node BFD view@subsection The BFD view of a fileBFD uses generic structures to manage information. It translates datainto the generic form when reading files, and out of the generic formwhen writing files.BFD describes a file as a pointer to the @samp{bfd} type. A @samp{bfd}is composed of the following elements. The BFD information can bedisplayed using the @samp{objdump} program with various options.@table @asis@item general informationThe object file format, a few general flags, the start address.@item architectureThe architecture, including both a general processor type (m68k, MIPSetc.) and a specific machine number (m68000, R4000, etc.).@item sectionsA list of sections.@item symbolsA symbol table.@end tableBFD represents a section as a pointer to the @samp{asection} type. Eachsection has a name and a size. Most sections also have an associatedblock of data, known as the section contents. Sections also haveassociated flags, a virtual memory address, a load memory address, arequired alignment, a list of relocations, and other miscellaneousinformation.BFD represents a relocation as a pointer to the @samp{arelent} type. Arelocation describes an action which the linker must take to modify thesection contents. Relocations have a symbol, an address, an addend, anda pointer to a howto structure which describes how to perform therelocation. For more information, see @ref{BFD relocation handling}.BFD represents a symbol as a pointer to the @samp{asymbol} type. Asymbol has a name, a pointer to a section, an offset within thatsection, and some flags.Archive files do not have any sections or symbols. Instead, BFDrepresents an archive file as a file which contains a list of@samp{bfd}s. BFD also provides access to the archive symbol map, as alist of symbol names. BFD provides a function to return the @samp{bfd}within the archive which corresponds to a particular entry in thearchive symbol map.@node BFD blindness@subsection BFD loses informationMost object file formats have information which BFD can not represent inits generic form, at least as currently defined.There is often explicit information which BFD can not represent. Forexample, the COFF version stamp, or the ELF program segments. BFDprovides special hooks to handle this information when copying,printing, or linking an object file. The BFD support for a particularobject file format will normally store this information in private dataand handle it using the special hooks.In some cases there is also implicit information which BFD can notrepresent. For example, the MIPS processor distinguishes small andlarge symbols, and requires that all small symbls be within 32K of theGP register. This means that the MIPS assembler must be able to markvariables as either small or large, and the MIPS linker must know to putsmall symbols within range of the GP register. Since BFD can notrepresent this information, this means that the assembler and linkermust have information that is specific to a particular object fileformat which is outside of the BFD library.This loss of information indicates areas where the BFD paradigm breaksdown. It is not actually possible to represent the myriad differencesamong object file formats using a single generic interface, at least notin the manner which BFD does it today.Nevertheless, the BFD library does greatly simplify the task of dealingwith object files, and particular problems caused by information losscan normally be solved using some sort of relatively constrained hookinto the library.@node BFD guidelines@section BFD programming guidelines@cindex bfd programming guidelines@cindex programming guidelines for bfd@cindex guidelines, bfd programmingThere is a lot of poorly written and confusing code in BFD. New BFDcode should be written to a higher standard. Merely because some BFDcode is written in a particular manner does not mean that you shouldemulate it.Here are some general BFD programming guidelines:@itemize @bullet@itemFollow the GNU coding standards.@itemAvoid global variables. We ideally want BFD to be fully reentrant, sothat it can be used in multiple threads. All uses of global or staticvariables interfere with that. Initialized constant variables are OK,and they should be explicitly marked with const. Instead of globalvariables, use data attached to a BFD or to a linker hash table.@itemAll externally visible functions should have names which start with@samp{bfd_}. All such functions should be declared in some header file,typically @file{bfd.h}. See, for example, the various declarations nearthe end of @file{bfd-in.h}, which mostly declare functions required byspecific linker emulations.@itemAll functions which need to be visible from one file to another withinBFD, but should not be visible outside of BFD, should start with@samp{_bfd_}. Although external names beginning with @samp{_} areprohibited by the ANSI standard, in practice this usage will alwayswork, and it is required by the GNU coding standards.@itemAlways remember that people can compile using @samp{--enable-targets} tobuild several, or all, targets at once. It must be possible to linktogether the files for all targets.@itemBFD code should compile with few or no warnings using @samp{gcc -Wall}.Some warnings are OK, like the absence of certain function declarationswhich may or may not be declared in system header files. Warnings aboutambiguous expressions and the like should always be fixed.@end itemize@node BFD target vector@section BFD target vector@cindex bfd target vector@cindex target vector in bfdBFD supports multiple object file formats by using the @dfn{targetvector}. This is simply a set of function pointers which implementbehaviour that is specific to a particular object file format.In this section I list all of the entries in the target vector anddescribe what they do.@menu* BFD target vector miscellaneous:: Miscellaneous constants* BFD target vector swap:: Swapping functions* BFD target vector format:: Format type dependent functions* BFD_JUMP_TABLE macros:: BFD_JUMP_TABLE macros* BFD target vector generic:: Generic functions* BFD target vector copy:: Copy functions* BFD target vector core:: Core file support functions* BFD target vector archive:: Archive functions* BFD target vector symbols:: Symbol table functions* BFD target vector relocs:: Relocation support* BFD target vector write:: Output functions* BFD target vector link:: Linker functions* BFD target vector dynamic:: Dynamic linking information functions@end menu@node BFD target vector miscellaneous@subsection Miscellaneous constantsThe target vector starts with a set of constants.@table @samp@item nameThe name of the target vector. This is an arbitrary string. This ishow the target vector is named in command line options for tools whichuse BFD, such as the @samp{--oformat} linker option.@item flavourA general description of the type of target. The following flavours arecurrently defined:@table @samp@item bfd_target_unknown_flavourUndefined or unknown.@item bfd_target_aout_flavoura.out.@item bfd_target_coff_flavourCOFF.@item bfd_target_ecoff_flavourECOFF.@item bfd_target_elf_flavourELF.@item bfd_target_ieee_flavourIEEE-695.@item bfd_target_nlm_flavourNLM.@item bfd_target_oasys_flavourOASYS.@item bfd_target_tekhex_flavourTektronix hex format.@item bfd_target_srec_flavourMotorola S-record format.@item bfd_target_ihex_flavourIntel hex format.@item bfd_target_som_flavourSOM (used on HP/UX).@item bfd_target_os9k_flavouros9000.@item bfd_target_versados_flavourVERSAdos.@item bfd_target_msdos_flavourMS-DOS.@item bfd_target_evax_flavouropenVMS.@item bfd_target_mmo_flavourDonald Knuth's MMIXware object format.@end table@item byteorderThe byte order of data in the object file. One of@samp{BFD_ENDIAN_BIG}, @samp{BFD_ENDIAN_LITTLE}, or@samp{BFD_ENDIAN_UNKNOWN}. The latter would be used for a format suchas S-records which do not record the architecture of the data.@item header_byteorderThe byte order of header information in the object file. Normally thesame as the @samp{byteorder} field, but there are certain cases where itmay be different.@item object_flagsFlags which may appear in the @samp{flags} field of a BFD with thisformat.@item section_flagsFlags which may appear in the @samp{flags} field of a section within aBFD with this format.@item symbol_leading_charA character which the C compiler normally puts before a symbol. Forexample, an a.out compiler will typically generate the symbol@samp{_foo} for a function named @samp{foo} in the C source, in whichcase this field would be @samp{_}. If there is no such character, thisfield will be @samp{0}.@item ar_pad_charThe padding character to use at the end of an archive name. Normally@samp{/}.@item ar_max_namelenThe maximum length of a short name in an archive. Normally @samp{14}.@item backend_dataA pointer to constant backend data. This is used by backends to storewhatever additional information they need to distinguish similar targetvectors which use the same sets of functions.@end table@node BFD target vector swap@subsection Swapping functionsEvery target vector has function pointers used for swapping informationin and out of the target representation. There are two sets offunctions: one for data information, and one for header information.Each set has three sizes: 64-bit, 32-bit, and 16-bit. Each size hasthree actual functions: put, get unsigned, and get signed.These 18 functions are used to convert data between the host and targetrepresentations.@node BFD target vector format@subsection Format type dependent functionsEvery target vector has three arrays of function pointers which areindexed by the BFD format type. The BFD format types are as follows:@table @samp@item bfd_unknownUnknown format. Not used for anything useful.@item bfd_objectObject file.@item bfd_archiveArchive file.@item bfd_coreCore file.@end tableThe three arrays of function pointers are as follows:@table @samp@item bfd_check_formatCheck whether the BFD is of a particular format (object file, archivefile, or core file) corresponding to this target vector. This is calledby the @samp{bfd_check_format} function when examining an existing BFD.If the BFD matches the desired format, this function will initialize anyformat specific information such as the @samp{tdata} field of the BFD.This function must be called before any other BFD target vector functionon a file opened for reading.@item bfd_set_formatSet the format of a BFD which was created for output. This is called bythe @samp{bfd_set_format} function after creating the BFD with afunction such as @samp{bfd_openw}. This function will initialize formatspecific information required to write out an object file or whatever ofthe given format. This function must be called before any other BFDtarget vector function on a file opened for writing.@item bfd_write_contentsWrite out the contents of the BFD in the given format. This is calledby @samp{bfd_close} function for a BFD opened for writing. This reallyshould not be an array selected by format type, as the@samp{bfd_set_format} function provides all the required information.In fact, BFD will fail if a different format is used when callingthrough the @samp{bfd_set_format} and the @samp{bfd_write_contents}arrays; fortunately, since @samp{bfd_close} gets it right, this is adifficult error to make.@end table@node BFD_JUMP_TABLE macros@subsection @samp{BFD_JUMP_TABLE} macros@cindex @samp{BFD_JUMP_TABLE}Most target vectors are defined using @samp{BFD_JUMP_TABLE} macros.These macros take a single argument, which is a prefix applied to a setof functions. The macros are then used to initialize the fields in thetarget vector.For example, the @samp{BFD_JUMP_TABLE_RELOCS} macro defines threefunctions: @samp{_get_reloc_upper_bound}, @samp{_canonicalize_reloc},and @samp{_bfd_reloc_type_lookup}. A reference like@samp{BFD_JUMP_TABLE_RELOCS (foo)} will expand into three functionsprefixed with @samp{foo}: @samp{foo_get_reloc_upper_bound}, etc. The@samp{BFD_JUMP_TABLE_RELOCS} macro will be placed such that those threefunctions initialize the appropriate fields in the BFD target vector.This is done because it turns out that many different target vectors canshare certain classes of functions. For example, archives are similaron most platforms, so most target vectors can use the same archivefunctions. Those target vectors all use @samp{BFD_JUMP_TABLE_ARCHIVE}with the same argument, calling a set of functions which is defined in@file{archive.c}.Each of the @samp{BFD_JUMP_TABLE} macros is mentioned below along withthe description of the function pointers which it defines. The functionpointers will be described using the name without the prefix which the@samp{BFD_JUMP_TABLE} macro defines. This name is normally the same asthe name of the field in the target vector structure. Any differenceswill be noted.@node BFD target vector generic@subsection Generic functions@cindex @samp{BFD_JUMP_TABLE_GENERIC}The @samp{BFD_JUMP_TABLE_GENERIC} macro is used for some catch allfunctions which don't easily fit into other categories.@table @samp@item _close_and_cleanupFree any target specific information associated with the BFD. This iscalled when any BFD is closed (the @samp{bfd_write_contents} functionmentioned earlier is only called for a BFD opened for writing). Mosttargets use @samp{bfd_alloc} to allocate all target specificinformation, and therefore don't have to do anything in this function.This function pointer is typically set to@samp{_bfd_generic_close_and_cleanup}, which simply returns true.@item _bfd_free_cached_infoFree any cached information associated with the BFD which can berecreated later if necessary. This is used to reduce the memoryconsumption required by programs using BFD. This is normally called viathe @samp{bfd_free_cached_info} macro. It is used by the defaultarchive routines when computing the archive map. Most targets do notdo anything special for this entry point, and just set it to@samp{_bfd_generic_free_cached_info}, which simply returns true.@item _new_section_hookThis is called from @samp{bfd_make_section_anyway} whenever a newsection is created. Most targets use it to initialize section specificinformation. This function is called whether or not the sectioncorresponds to an actual section in an actual BFD.@item _get_section_contentsGet the contents of a section. This is called from@samp{bfd_get_section_contents}. Most targets set this to@samp{_bfd_generic_get_section_contents}, which does a @samp{bfd_seek}based on the section's @samp{filepos} field and a @samp{bfd_bread}. Thecorresponding field in the target vector is named@samp{_bfd_get_section_contents}.@item _get_section_contents_in_windowSet a @samp{bfd_window} to hold the contents of a section. This iscalled from @samp{bfd_get_section_contents_in_window}. The@samp{bfd_window} idea never really caught on, and I don't think this isever called. Pretty much all targets implement this as@samp{bfd_generic_get_section_contents_in_window}, which uses@samp{bfd_get_section_contents} to do the right thing. Thecorresponding field in the target vector is named@samp{_bfd_get_section_contents_in_window}.@end table@node BFD target vector copy@subsection Copy functions@cindex @samp{BFD_JUMP_TABLE_COPY}The @samp{BFD_JUMP_TABLE_COPY} macro is used for functions which arecalled when copying BFDs, and for a couple of functions which deal withinternal BFD information.@table @samp@item _bfd_copy_private_bfd_dataThis is called when copying a BFD, via @samp{bfd_copy_private_bfd_data}.If the input and output BFDs have the same format, this will copy anyprivate information over. This is called after all the section contentshave been written to the output file. Only a few targets do anything inthis function.@item _bfd_merge_private_bfd_dataThis is called when linking, via @samp{bfd_merge_private_bfd_data}. Itgives the backend linker code a chance to set any special flags in theoutput file based on the contents of the input file. Only a few targetsdo anything in this function.@item _bfd_copy_private_section_dataThis is similar to @samp{_bfd_copy_private_bfd_data}, but it is calledfor each section, via @samp{bfd_copy_private_section_data}. Thisfunction is called before any section contents have been written. Onlya few targets do anything in this function.@item _bfd_copy_private_symbol_dataThis is called via @samp{bfd_copy_private_symbol_data}, but I don'tthink anything actually calls it. If it were defined, it could be usedto copy private symbol data from one BFD to another. However, most BFDsstore extra symbol information by allocating space which is larger thanthe @samp{asymbol} structure and storing private information in theextra space. Since @samp{objcopy} and other programs copy symbolinformation by copying pointers to @samp{asymbol} structures, theprivate symbol information is automatically copied as well. Mosttargets do not do anything in this function.@item _bfd_set_private_flagsThis is called via @samp{bfd_set_private_flags}. It is basically a hookfor the assembler to set magic information. For example, the PowerPCELF assembler uses it to set flags which appear in the e_flags field ofthe ELF header. Most targets do not do anything in this function.@item _bfd_print_private_bfd_dataThis is called by @samp{objdump} when the @samp{-p} option is used. Itis called via @samp{bfd_print_private_data}. It prints any interestinginformation about the BFD which can not be otherwise represented by BFDand thus can not be printed by @samp{objdump}. Most targets do not doanything in this function.@end table@node BFD target vector core@subsection Core file support functions@cindex @samp{BFD_JUMP_TABLE_CORE}The @samp{BFD_JUMP_TABLE_CORE} macro is used for functions which dealwith core files. Obviously, these functions only do somethinginteresting for targets which have core file support.@table @samp@item _core_file_failing_commandGiven a core file, this returns the command which was run to produce thecore file.@item _core_file_failing_signalGiven a core file, this returns the signal number which produced thecore file.@item _core_file_matches_executable_pGiven a core file and a BFD for an executable, this returns whether thecore file was generated by the executable.@end table@node BFD target vector archive@subsection Archive functions@cindex @samp{BFD_JUMP_TABLE_ARCHIVE}The @samp{BFD_JUMP_TABLE_ARCHIVE} macro is used for functions which dealwith archive files. Most targets use COFF style archive files(including ELF targets), and these use @samp{_bfd_archive_coff} as theargument to @samp{BFD_JUMP_TABLE_ARCHIVE}. Some targets use BSD/a.outstyle archives, and these use @samp{_bfd_archive_bsd}. (The maindifference between BSD and COFF archives is the format of the archivesymbol table). Targets with no archive support use@samp{_bfd_noarchive}. Finally, a few targets have unusual archivehandling.@table @samp@item _slurp_armapRead in the archive symbol table, storing it in private BFD data. Thisis normally called from the archive @samp{check_format} routine. Thecorresponding field in the target vector is named@samp{_bfd_slurp_armap}.@item _slurp_extended_name_tableRead in the extended name table from the archive, if there is one,storing it in private BFD data. This is normally called from thearchive @samp{check_format} routine. The corresponding field in thetarget vector is named @samp{_bfd_slurp_extended_name_table}.@item construct_extended_name_tableBuild and return an extended name table if one is needed to write outthe archive. This also adjusts the archive headers to refer to theextended name table appropriately. This is normally called from thearchive @samp{write_contents} routine. The corresponding field in thetarget vector is named @samp{_bfd_construct_extended_name_table}.@item _truncate_arnameThis copies a file name into an archive header, truncating it asrequired. It is normally called from the archive @samp{write_contents}routine. This function is more interesting in targets which do notsupport extended name tables, but I think the GNU @samp{ar} programalways uses extended name tables anyhow. The corresponding field in thetarget vector is named @samp{_bfd_truncate_arname}.@item _write_armapWrite out the archive symbol table using calls to @samp{bfd_bwrite}.This is normally called from the archive @samp{write_contents} routine.The corresponding field in the target vector is named @samp{write_armap}(no leading underscore).@item _read_ar_hdrRead and parse an archive header. This handles expanding the archiveheader name into the real file name using the extended name table. Thisis called by routines which read the archive symbol table or the archiveitself. The corresponding field in the target vector is named@samp{_bfd_read_ar_hdr_fn}.@item _openr_next_archived_fileGiven an archive and a BFD representing a file stored within thearchive, return a BFD for the next file in the archive. This is calledvia @samp{bfd_openr_next_archived_file}. The corresponding field in thetarget vector is named @samp{openr_next_archived_file} (no leadingunderscore).@item _get_elt_at_indexGiven an archive and an index, return a BFD for the file in the archivecorresponding to that entry in the archive symbol table. This is calledvia @samp{bfd_get_elt_at_index}. The corresponding field in the targetvector is named @samp{_bfd_get_elt_at_index}.@item _generic_stat_arch_eltDo a stat on an element of an archive, returning information read fromthe archive header (modification time, uid, gid, file mode, size). Thisis called via @samp{bfd_stat_arch_elt}. The corresponding field in thetarget vector is named @samp{_bfd_stat_arch_elt}.@item _update_armap_timestampAfter the entire contents of an archive have been written out, updatethe timestamp of the archive symbol table to be newer than that of thefile. This is required for a.out style archives. This is normallycalled by the archive @samp{write_contents} routine. The correspondingfield in the target vector is named @samp{_bfd_update_armap_timestamp}.@end table@node BFD target vector symbols@subsection Symbol table functions@cindex @samp{BFD_JUMP_TABLE_SYMBOLS}The @samp{BFD_JUMP_TABLE_SYMBOLS} macro is used for functions which dealwith symbols.@table @samp@item _get_symtab_upper_boundReturn a sensible upper bound on the amount of memory which will berequired to read the symbol table. In practice most targets return theamount of memory required to hold @samp{asymbol} pointers for all thesymbols plus a trailing @samp{NULL} entry, and store the actual symbolinformation in BFD private data. This is called via@samp{bfd_get_symtab_upper_bound}. The corresponding field in thetarget vector is named @samp{_bfd_get_symtab_upper_bound}.@item _canonicalize_symtabRead in the symbol table. This is called via@samp{bfd_canonicalize_symtab}. The corresponding field in the targetvector is named @samp{_bfd_canonicalize_symtab}.@item _make_empty_symbolCreate an empty symbol for the BFD. This is needed because most targetsstore extra information with each symbol by allocating a structurelarger than an @samp{asymbol} and storing the extra information at theend. This function will allocate the right amount of memory, and returnwhat looks like a pointer to an empty @samp{asymbol}. This is calledvia @samp{bfd_make_empty_symbol}. The corresponding field in the targetvector is named @samp{_bfd_make_empty_symbol}.@item _print_symbolPrint information about the symbol. This is called via@samp{bfd_print_symbol}. One of the arguments indicates what sort ofinformation should be printed:@table @samp@item bfd_print_symbol_nameJust print the symbol name.@item bfd_print_symbol_morePrint the symbol name and some interesting flags. I don't thinkanything actually uses this.@item bfd_print_symbol_allPrint all information about the symbol. This is used by @samp{objdump}when run with the @samp{-t} option.@end tableThe corresponding field in the target vector is named@samp{_bfd_print_symbol}.@item _get_symbol_infoReturn a standard set of information about the symbol. This is calledvia @samp{bfd_symbol_info}. The corresponding field in the targetvector is named @samp{_bfd_get_symbol_info}.@item _bfd_is_local_label_nameReturn whether the given string would normally represent the name of alocal label. This is called via @samp{bfd_is_local_label} and@samp{bfd_is_local_label_name}. Local labels are normally discarded bythe assembler. In the linker, this defines the difference between the@samp{-x} and @samp{-X} options.@item _get_linenoReturn line number information for a symbol. This is only meaningfulfor a COFF target. This is called when writing out COFF line numbers.@item _find_nearest_lineGiven an address within a section, use the debugging information to findthe matching file name, function name, and line number, if any. This iscalled via @samp{bfd_find_nearest_line}. The corresponding field in thetarget vector is named @samp{_bfd_find_nearest_line}.@item _bfd_make_debug_symbolMake a debugging symbol. This is only meaningful for a COFF target,where it simply returns a symbol which will be placed in the@samp{N_DEBUG} section when it is written out. This is called via@samp{bfd_make_debug_symbol}.@item _read_minisymbolsMinisymbols are used to reduce the memory requirements of programs like@samp{nm}. A minisymbol is a cookie pointing to internal symbolinformation which the caller can use to extract complete symbolinformation. This permits BFD to not convert all the symbols intogeneric form, but to instead convert them one at a time. This is calledvia @samp{bfd_read_minisymbols}. Most targets do not implement this,and just use generic support which is based on using standard@samp{asymbol} structures.@item _minisymbol_to_symbolConvert a minisymbol to a standard @samp{asymbol}. This is called via@samp{bfd_minisymbol_to_symbol}.@end table@node BFD target vector relocs@subsection Relocation support@cindex @samp{BFD_JUMP_TABLE_RELOCS}The @samp{BFD_JUMP_TABLE_RELOCS} macro is used for functions which dealwith relocations.@table @samp@item _get_reloc_upper_boundReturn a sensible upper bound on the amount of memory which will berequired to read the relocations for a section. In practice mosttargets return the amount of memory required to hold @samp{arelent}pointers for all the relocations plus a trailing @samp{NULL} entry, andstore the actual relocation information in BFD private data. This iscalled via @samp{bfd_get_reloc_upper_bound}.@item _canonicalize_relocReturn the relocation information for a section. This is called via@samp{bfd_canonicalize_reloc}. The corresponding field in the targetvector is named @samp{_bfd_canonicalize_reloc}.@item _bfd_reloc_type_lookupGiven a relocation code, return the corresponding howto structure(@pxref{BFD relocation codes}). This is called via@samp{bfd_reloc_type_lookup}. The corresponding field in the targetvector is named @samp{reloc_type_lookup}.@end table@node BFD target vector write@subsection Output functions@cindex @samp{BFD_JUMP_TABLE_WRITE}The @samp{BFD_JUMP_TABLE_WRITE} macro is used for functions which dealwith writing out a BFD.@table @samp@item _set_arch_machSet the architecture and machine number for a BFD. This is called via@samp{bfd_set_arch_mach}. Most targets implement this by calling@samp{bfd_default_set_arch_mach}. The corresponding field in the targetvector is named @samp{_bfd_set_arch_mach}.@item _set_section_contentsWrite out the contents of a section. This is called via@samp{bfd_set_section_contents}. The corresponding field in the targetvector is named @samp{_bfd_set_section_contents}.@end table@node BFD target vector link@subsection Linker functions@cindex @samp{BFD_JUMP_TABLE_LINK}The @samp{BFD_JUMP_TABLE_LINK} macro is used for functions called by thelinker.@table @samp@item _sizeof_headersReturn the size of the header information required for a BFD. This isused to implement the @samp{SIZEOF_HEADERS} linker script function. Itis normally used to align the first section at an efficient position onthe page. This is called via @samp{bfd_sizeof_headers}. Thecorresponding field in the target vector is named@samp{_bfd_sizeof_headers}.@item _bfd_get_relocated_section_contentsRead the contents of a section and apply the relocation information.This handles both a final link and a relocatable link; in the lattercase, it adjust the relocation information as well. This is called via@samp{bfd_get_relocated_section_contents}. Most targets implement it bycalling @samp{bfd_generic_get_relocated_section_contents}.@item _bfd_relax_sectionTry to use relaxation to shrink the size of a section. This is calledby the linker when the @samp{-relax} option is used. This is called via@samp{bfd_relax_section}. Most targets do not support any sort ofrelaxation.@item _bfd_link_hash_table_createCreate the symbol hash table to use for the linker. This linker hookpermits the backend to control the size and information of the elementsin the linker symbol hash table. This is called via@samp{bfd_link_hash_table_create}.@item _bfd_link_add_symbolsGiven an object file or an archive, add all symbols into the linkersymbol hash table. Use callbacks to the linker to include archiveelements in the link. This is called via @samp{bfd_link_add_symbols}.@item _bfd_final_linkFinish the linking process. The linker calls this hook after all of theinput files have been read, when it is ready to finish the link andgenerate the output file. This is called via @samp{bfd_final_link}.@item _bfd_link_split_sectionI don't know what this is for. Nothing seems to call it. The onlynon-trivial definition is in @file{som.c}.@end table@node BFD target vector dynamic@subsection Dynamic linking information functions@cindex @samp{BFD_JUMP_TABLE_DYNAMIC}The @samp{BFD_JUMP_TABLE_DYNAMIC} macro is used for functions which readdynamic linking information.@table @samp@item _get_dynamic_symtab_upper_boundReturn a sensible upper bound on the amount of memory which will berequired to read the dynamic symbol table. In practice most targetsreturn the amount of memory required to hold @samp{asymbol} pointers forall the symbols plus a trailing @samp{NULL} entry, and store the actualsymbol information in BFD private data. This is called via@samp{bfd_get_dynamic_symtab_upper_bound}. The corresponding field inthe target vector is named @samp{_bfd_get_dynamic_symtab_upper_bound}.@item _canonicalize_dynamic_symtabRead the dynamic symbol table. This is called via@samp{bfd_canonicalize_dynamic_symtab}. The corresponding field in thetarget vector is named @samp{_bfd_canonicalize_dynamic_symtab}.@item _get_dynamic_reloc_upper_boundReturn a sensible upper bound on the amount of memory which will berequired to read the dynamic relocations. In practice most targetsreturn the amount of memory required to hold @samp{arelent} pointers forall the relocations plus a trailing @samp{NULL} entry, and store theactual relocation information in BFD private data. This is called via@samp{bfd_get_dynamic_reloc_upper_bound}. The corresponding field inthe target vector is named @samp{_bfd_get_dynamic_reloc_upper_bound}.@item _canonicalize_dynamic_relocRead the dynamic relocations. This is called via@samp{bfd_canonicalize_dynamic_reloc}. The corresponding field in thetarget vector is named @samp{_bfd_canonicalize_dynamic_reloc}.@end table@node BFD generated files@section BFD generated files@cindex generated files in bfd@cindex bfd generated filesBFD contains several automatically generated files. This sectiondescribes them. Some files are created at configure time, when youconfigure BFD. Some files are created at make time, when you buildBFD. Some files are automatically rebuilt at make time, but only ifyou configure with the @samp{--enable-maintainer-mode} option. Somefiles live in the object directory---the directory from which you runconfigure---and some live in the source directory. All files that livein the source directory are checked into the CVS repository.@table @file@item bfd.h@cindex @file{bfd.h}@cindex @file{bfd-in3.h}Lives in the object directory. Created at make time from@file{bfd-in2.h} via @file{bfd-in3.h}. @file{bfd-in3.h} is created atconfigure time from @file{bfd-in2.h}. There are automatic dependenciesto rebuild @file{bfd-in3.h} and hence @file{bfd.h} if @file{bfd-in2.h}changes, so you can normally ignore @file{bfd-in3.h}, and just thinkabout @file{bfd-in2.h} and @file{bfd.h}.@file{bfd.h} is built by replacing a few strings in @file{bfd-in2.h}.To see them, search for @samp{@@} in @file{bfd-in2.h}. They mainlycontrol whether BFD is built for a 32 bit target or a 64 bit target.@item bfd-in2.h@cindex @file{bfd-in2.h}Lives in the source directory. Created from @file{bfd-in.h} and severalother BFD source files. If you configure with the@samp{--enable-maintainer-mode} option, @file{bfd-in2.h} is rebuiltautomatically when a source file changes.@item elf32-target.h@itemx elf64-target.h@cindex @file{elf32-target.h}@cindex @file{elf64-target.h}Live in the object directory. Created from @file{elfxx-target.h}.These files are versions of @file{elfxx-target.h} customized for eithera 32 bit ELF target or a 64 bit ELF target.@item libbfd.h@cindex @file{libbfd.h}Lives in the source directory. Created from @file{libbfd-in.h} andseveral other BFD source files. If you configure with the@samp{--enable-maintainer-mode} option, @file{libbfd.h} is rebuiltautomatically when a source file changes.@item libcoff.h@cindex @file{libcoff.h}Lives in the source directory. Created from @file{libcoff-in.h} and@file{coffcode.h}. If you configure with the@samp{--enable-maintainer-mode} option, @file{libcoff.h} is rebuiltautomatically when a source file changes.@item targmatch.h@cindex @file{targmatch.h}Lives in the object directory. Created at make time from@file{config.bfd}. This file is used to map configuration triplets intoBFD target vector variable names at run time.@end table@node BFD multiple compilations@section Files compiled multiple times in BFDSeveral files in BFD are compiled multiple times. By this I mean thatthere are header files which contain function definitions. These headerfiles are included by other files, and thus the functions are compiledonce per file which includes them.Preprocessor macros are used to control the compilation, so that eachtime the files are compiled the resulting functions are slightlydifferent. Naturally, if they weren't different, there would be noreason to compile them multiple times.This is a not a particularly good programming technique, and future BFDwork should avoid it.@itemize @bullet@itemSince this technique is rarely used, even experienced C programmers findit confusing.@itemIt is difficult to debug programs which use BFD, since there is no wayto describe which version of a particular function you are looking at.@itemPrograms which use BFD wind up incorporating two or more slightlydifferent versions of the same function, which wastes space in theexecutable.@itemThis technique is never required nor is it especially efficient. It isalways possible to use statically initialized structures holdingfunction pointers and magic constants instead.@end itemizeThe following is a list of the files which are compiled multiple times.@table @file@item aout-target.h@cindex @file{aout-target.h}Describes a few functions and the target vector for a.out targets. Thisis used by individual a.out targets with different definitions of@samp{N_TXTADDR} and similar a.out macros.@item aoutf1.h@cindex @file{aoutf1.h}Implements standard SunOS a.out files. In principle it supports 64 bita.out targets based on the preprocessor macro @samp{ARCH_SIZE}, butsince all known a.out targets are 32 bits, this code may or may notwork. This file is only included by a few other files, and it isdifficult to justify its existence.@item aoutx.h@cindex @file{aoutx.h}Implements basic a.out support routines. This file can be compiled foreither 32 or 64 bit support. Since all known a.out targets are 32 bits,the 64 bit support may or may not work. I believe the originalintention was that this file would only be included by @samp{aout32.c}and @samp{aout64.c}, and that other a.out targets would simply refer tothe functions it defined. Unfortunately, some other a.out targetsstarted including it directly, leading to a somewhat confused state ofaffairs.@item coffcode.h@cindex @file{coffcode.h}Implements basic COFF support routines. This file is included by everyCOFF target. It implements code which handles COFF magic numbers aswell as various hook functions called by the generic COFF functions in@file{coffgen.c}. This file is controlled by a number of differentmacros, and more are added regularly.@item coffswap.h@cindex @file{coffswap.h}Implements COFF swapping routines. This file is included by@file{coffcode.h}, and thus by every COFF target. It implements theroutines which swap COFF structures between internal and externalformat. The main control for this file is the external structuredefinitions in the files in the @file{include/coff} directory. A COFFtarget file will include one of those files before including@file{coffcode.h} and thus @file{coffswap.h}. There are a few othermacros which affect @file{coffswap.h} as well, mostly describing whethercertain fields are present in the external structures.@item ecoffswap.h@cindex @file{ecoffswap.h}Implements ECOFF swapping routines. This is like @file{coffswap.h}, butfor ECOFF. It is included by the ECOFF target files (of which there areonly two). The control is the preprocessor macro @samp{ECOFF_32} or@samp{ECOFF_64}.@item elfcode.h@cindex @file{elfcode.h}Implements ELF functions that use external structure definitions. Thisfile is included by two other files: @file{elf32.c} and @file{elf64.c}.It is controlled by the @samp{ARCH_SIZE} macro which is defined to be@samp{32} or @samp{64} before including it. The @samp{NAME} macro isused internally to give the functions different names for the two targetsizes.@item elfcore.h@cindex @file{elfcore.h}Like @file{elfcode.h}, but for functions that are specific to ELF corefiles. This is included only by @file{elfcode.h}.@item elfxx-target.h@cindex @file{elfxx-target.h}This file is the source for the generated files @file{elf32-target.h}and @file{elf64-target.h}, one of which is included by every ELF target.It defines the ELF target vector.@item freebsd.h@cindex @file{freebsd.h}Presumably intended to be included by all FreeBSD targets, but in factthere is only one such target, @samp{i386-freebsd}. This defines afunction used to set the right magic number for FreeBSD, as well asvarious macros, and includes @file{aout-target.h}.@item netbsd.h@cindex @file{netbsd.h}Like @file{freebsd.h}, except that there are several files which includeit.@item nlm-target.h@cindex @file{nlm-target.h}Defines the target vector for a standard NLM target.@item nlmcode.h@cindex @file{nlmcode.h}Like @file{elfcode.h}, but for NLM targets. This is only included by@file{nlm32.c} and @file{nlm64.c}, both of which define the macro@samp{ARCH_SIZE} to an appropriate value. There are no 64 bit NLMtargets anyhow, so this is sort of useless.@item nlmswap.h@cindex @file{nlmswap.h}Like @file{coffswap.h}, but for NLM targets. This is included by eachNLM target, but I think it winds up compiling to the exact same code forevery target, and as such is fairly useless.@item peicode.h@cindex @file{peicode.h}Provides swapping routines and other hooks for PE targets.@file{coffcode.h} will include this rather than @file{coffswap.h} for aPE target. This defines PE specific versions of the COFF swappingroutines, and also defines some macros which control @file{coffcode.h}itself.@end table@node BFD relocation handling@section BFD relocation handling@cindex bfd relocation handling@cindex relocations in bfdThe handling of relocations is one of the more confusing aspects of BFD.Relocation handling has been implemented in various different ways, allsomewhat incompatible, none perfect.@menu* BFD relocation concepts:: BFD relocation concepts* BFD relocation functions:: BFD relocation functions* BFD relocation codes:: BFD relocation codes* BFD relocation future:: BFD relocation future@end menu@node BFD relocation concepts@subsection BFD relocation conceptsA relocation is an action which the linker must take when linking. Itdescribes a change to the contents of a section. The change is normallybased on the final value of one or more symbols. Relocations arecreated by the assembler when it creates an object file.Most relocations are simple. A typical simple relocation is to set 32bits at a given offset in a section to the value of a symbol. This typeof relocation would be generated for code like @code{int *p = &i;} where@samp{p} and @samp{i} are global variables. A relocation for the symbol@samp{i} would be generated such that the linker would initialize thearea of memory which holds the value of @samp{p} to the value of thesymbol @samp{i}.Slightly more complex relocations may include an addend, which is aconstant to add to the symbol value before using it. In some cases arelocation will require adding the symbol value to the existing contentsof the section in the object file. In others the relocation will simplyreplace the contents of the section with the symbol value. Somerelocations are PC relative, so that the value to be stored in thesection is the difference between the value of a symbol and the finaladdress of the section contents.In general, relocations can be arbitrarily complex. For example,relocations used in dynamic linking systems often require the linker toallocate space in a different section and use the offset within thatsection as the value to store. In the IEEE object file format,relocations may involve arbitrary expressions.When doing a relocatable link, the linker may or may not have to doanything with a relocation, depending upon the definition of therelocation. Simple relocations generally do not require any specialaction.@node BFD relocation functions@subsection BFD relocation functionsIn BFD, each section has an array of @samp{arelent} structures. Eachstructure has a pointer to a symbol, an address within the section, anaddend, and a pointer to a @samp{reloc_howto_struct} structure. Thehowto structure has a bunch of fields describing the reloc, including atype field. The type field is specific to the object file formatbackend; none of the generic code in BFD examines it.Originally, the function @samp{bfd_perform_relocation} was supposed tohandle all relocations. In theory, many relocations would be simpleenough to be described by the fields in the howto structure. For thosethat weren't, the howto structure included a @samp{special_function}field to use as an escape.While this seems plausible, a look at @samp{bfd_perform_relocation}shows that it failed. The function has odd special cases. Some of thefields in the howto structure, such as @samp{pcrel_offset}, were notadequately documented.The linker uses @samp{bfd_perform_relocation} to do all relocations whenthe input and output file have different formats (e.g., when generatingS-records). The generic linker code, which is used by all targets whichdo not define their own special purpose linker, uses@samp{bfd_get_relocated_section_contents}, which for most targets turnsinto a call to @samp{bfd_generic_get_relocated_section_contents}, whichcalls @samp{bfd_perform_relocation}. So @samp{bfd_perform_relocation}is still widely used, which makes it difficult to change, since it isdifficult to test all possible cases.The assembler used @samp{bfd_perform_relocation} for a while. Thisturned out to be the wrong thing to do, since@samp{bfd_perform_relocation} was written to handle relocations on anexisting object file, while the assembler needed to create relocationsin a new object file. The assembler was changed to use the new function@samp{bfd_install_relocation} instead, and @samp{bfd_install_relocation}was created as a copy of @samp{bfd_perform_relocation}.Unfortunately, the work did not progress any farther, so@samp{bfd_install_relocation} remains a simple copy of@samp{bfd_perform_relocation}, with all the odd special cases andconfusing code. This again is difficult to change, because again anychange can affect any assembler target, and so is difficult to test.The new linker, when using the same object file format for all inputfiles and the output file, does not convert relocations into@samp{arelent} structures, so it can not use@samp{bfd_perform_relocation} at all. Instead, users of the new linkerare expected to write a @samp{relocate_section} function which willhandle relocations in a target specific fashion.There are two helper functions for target specific relocation:@samp{_bfd_final_link_relocate} and @samp{_bfd_relocate_contents}.These functions use a howto structure, but they @emph{do not} use the@samp{special_function} field. Since the functions are normally calledfrom target specific code, the @samp{special_function} field addslittle; any relocations which require special handling can be handledwithout calling those functions.So, if you want to add a new target, or add a new relocation to anexisting target, you need to do the following:@itemize @bullet@itemMake sure you clearly understand what the contents of the section shouldlook like after assembly, after a relocatable link, and after a finallink. Make sure you clearly understand the operations the linker mustperform during a relocatable link and during a final link.@itemWrite a howto structure for the relocation. The howto structure isflexible enough to represent any relocation which should be handled bysetting a contiguous bitfield in the destination to the value of asymbol, possibly with an addend, possibly adding the symbol value to thevalue already present in the destination.@itemChange the assembler to generate your relocation. The assembler willcall @samp{bfd_install_relocation}, so your howto structure has to beable to handle that. You may need to set the @samp{special_function}field to handle assembly correctly. Be careful to ensure that any codeyou write to handle the assembler will also work correctly when doing arelocatable link. For example, see @samp{bfd_elf_generic_reloc}.@itemTest the assembler. Consider the cases of relocation against anundefined symbol, a common symbol, a symbol defined in the object filein the same section, and a symbol defined in the object file in adifferent section. These cases may not all be applicable for yourreloc.@itemIf your target uses the new linker, which is recommended, add anyrequired handling to the target specific relocation function. In simplecases this will just involve a call to @samp{_bfd_final_link_relocate}or @samp{_bfd_relocate_contents}, depending upon the definition of therelocation and whether the link is relocatable or not.@itemTest the linker. Test the case of a final link. If the relocation canoverflow, use a linker script to force an overflow and make sure theerror is reported correctly. Test a relocatable link, whether thesymbol is defined or undefined in the relocatable output. For both thefinal and relocatable link, test the case when the symbol is a commonsymbol, when the symbol looked like a common symbol but became a definedsymbol, when the symbol is defined in a different object file, and whenthe symbol is defined in the same object file.@itemIn order for linking to another object file format, such as S-records,to work correctly, @samp{bfd_perform_relocation} has to do the rightthing for the relocation. You may need to set the@samp{special_function} field to handle this correctly. Test this bydoing a link in which the output object file format is S-records.@itemUsing the linker to generate relocatable output in a different objectfile format is impossible in the general case, so you generally don'thave to worry about that. The GNU linker makes sure to stop that fromhappening when an input file in a different format has relocations.Linking input files of different object file formats together is quiteunusual, but if you're really dedicated you may want to consider testingthis case, both when the output object file format is the same as yourformat, and when it is different.@end itemize@node BFD relocation codes@subsection BFD relocation codesBFD has another way of describing relocations besides the howtostructures described above: the enum @samp{bfd_reloc_code_real_type}.Every known relocation type can be described as a value in thisenumeration. The enumeration contains many target specific relocations,but where two or more targets have the same relocation, a single code isused. For example, the single value @samp{BFD_RELOC_32} is used for allsimple 32 bit relocation types.The main purpose of this relocation code is to give the assembler somemechanism to create @samp{arelent} structures. In order for theassembler to create an @samp{arelent} structure, it has to be able toobtain a howto structure. The function @samp{bfd_reloc_type_lookup},which simply calls the target vector entry point@samp{reloc_type_lookup}, takes a relocation code and returns a howtostructure.The function @samp{bfd_get_reloc_code_name} returns the name of arelocation code. This is mainly used in error messages.Using both howto structures and relocation codes can be somewhatconfusing. There are many processor specific relocation codes.However, the relocation is only fully defined by the howto structure.The same relocation code will map to different howto structures indifferent object file formats. For example, the addend handling may bedifferent.Most of the relocation codes are not really general. The assembler cannot use them without already understanding what sorts of relocations canbe used for a particular target. It might be possible to replace therelocation codes with something simpler.@node BFD relocation future@subsection BFD relocation futureClearly the current BFD relocation support is in bad shape. Awholescale rewrite would be very difficult, because it would requirethorough testing of every BFD target. So some sort of incrementalchange is required.My vague thoughts on this would involve defining a new, clearly defined,howto structure. Some mechanism would be used to determine which typeof howto structure was being used by a particular format.The new howto structure would clearly define the relocation behaviour inthe case of an assembly, a relocatable link, and a final link. Atleast one special function would be defined as an escape, and it mightmake sense to define more.One or more generic functions similar to @samp{bfd_perform_relocation}would be written to handle the new howto structure.This should make it possible to write a generic version of the relocatesection functions used by the new linker. The target specific codewould provide some mechanism (a function pointer or an initialconversion) to convert target specific relocations into howtostructures.Ideally it would be possible to use this generic relocate sectionfunction for the generic linker as well. That is, it would replace the@samp{bfd_generic_get_relocated_section_contents} function which iscurrently normally used.For the special case of ELF dynamic linking, more consideration needs tobe given to writing ELF specific but ELF target generic code to handlespecial relocation types such as GOT and PLT.@node BFD ELF support@section BFD ELF support@cindex elf support in bfd@cindex bfd elf supportThe ELF object file format is defined in two parts: a generic ABI and aprocessor specific supplement. The ELF support in BFD is split in asimilar fashion. The processor specific support is largely kept withina single file. The generic support is provided by several other files.The processor specific support provides a set of function pointers andconstants used by the generic support.@menu* BFD ELF sections and segments:: ELF sections and segments* BFD ELF generic support:: BFD ELF generic support* BFD ELF processor specific support:: BFD ELF processor specific support* BFD ELF core files:: BFD ELF core files* BFD ELF future:: BFD ELF future@end menu@node BFD ELF sections and segments@subsection ELF sections and segmentsThe ELF ABI permits a file to have either sections or segments or both.Relocateable object files conventionally have only sections.Executables conventionally have both. Core files conventionally haveonly program segments.ELF sections are similar to sections in other object file formats: theyhave a name, a VMA, file contents, flags, and other miscellaneousinformation. ELF relocations are stored in sections of a particulartype; BFD automatically converts these sections into internal relocationinformation.ELF program segments are intended for fast interpretation by a systemloader. They have a type, a VMA, an LMA, file contents, and a couple ofother fields. When an ELF executable is run on a Unix system, thesystem loader will examine the program segments to decide how to loadit. The loader will ignore the section information. Loadable programsegments (type @samp{PT_LOAD}) are directly loaded into memory. Otherprogram segments are interpreted by the loader, and generally providedynamic linking information.When an ELF file has both program segments and sections, an ELF programsegment may encompass one or more ELF sections, in the sense that theportion of the file which corresponds to the program segment may includethe portions of the file corresponding to one or more sections. Whenthere is more than one section in a loadable program segment, therelative positions of the section contents in the file must correspondto the relative positions they should hold when the program segment isloaded. This requirement should be obvious if you consider that thesystem loader will load an entire program segment at a time.On a system which supports dynamic paging, such as any native Unixsystem, the contents of a loadable program segment must be at the sameoffset in the file as in memory, modulo the memory page size used on thesystem. This is because the system loader will map the file into memorystarting at the start of a page. The system loader can easily remapentire pages to the correct load address. However, if the contents ofthe file were not correctly aligned within the page, the system loaderwould have to shift the contents around within the page, which is tooexpensive. For example, if the LMA of a loadable program segment is@samp{0x40080} and the page size is @samp{0x1000}, then the position ofthe segment contents within the file must equal @samp{0x80} modulo@samp{0x1000}.BFD has only a single set of sections. It does not provide any genericway to examine both sections and segments. When BFD is used to open anobject file or executable, the BFD sections will represent ELF sections.When BFD is used to open a core file, the BFD sections will representELF program segments.When BFD is used to examine an object file or executable, any programsegments will be read to set the LMA of the sections. This is becauseELF sections only have a VMA, while ELF program segments have both a VMAand an LMA. Any program segments will be copied by the@samp{copy_private} entry points. They will be printed by the@samp{print_private} entry point. Otherwise, the program segments areignored. In particular, programs which use BFD currently have no directaccess to the program segments.When BFD is used to create an executable, the program segments will becreated automatically based on the section information. This is done inthe function @samp{assign_file_positions_for_segments} in @file{elf.c}.This function has been tweaked many times, and probably still hasproblems that arise in particular cases.There is a hook which may be used to explicitly define the programsegments when creating an executable: the @samp{bfd_record_phdr}function in @file{bfd.c}. If this function is called, BFD will notcreate program segments itself, but will only create the programsegments specified by the caller. The linker uses this function toimplement the @samp{PHDRS} linker script command.@node BFD ELF generic support@subsection BFD ELF generic supportIn general, functions which do not read external data from the ELF fileare found in @file{elf.c}. They operate on the internal forms of theELF structures, which are defined in @file{include/elf/internal.h}. Theinternal structures are defined in terms of @samp{bfd_vma}, and so maybe used for both 32 bit and 64 bit ELF targets.The file @file{elfcode.h} contains functions which operate on theexternal data. @file{elfcode.h} is compiled twice, once via@file{elf32.c} with @samp{ARCH_SIZE} defined as @samp{32}, and once via@file{elf64.c} with @samp{ARCH_SIZE} defined as @samp{64}.@file{elfcode.h} includes functions to swap the ELF structures in andout of external form, as well as a few more complex functions.Linker support is found in @file{elflink.c}. Thelinker support is only used if the processor specific file defines@samp{elf_backend_relocate_section}, which is required to relocate thesection contents. If that macro is not defined, the generic linker codeis used, and relocations are handled via @samp{bfd_perform_relocation}.The core file support is in @file{elfcore.h}, which is compiled twice,for both 32 and 64 bit support. The more interesting cases of core filesupport only work on a native system which has the @file{sys/procfs.h}header file. Without that file, the core file support does little morethan read the ELF program segments as BFD sections.The BFD internal header file @file{elf-bfd.h} is used for communicationamong these files and the processor specific files.The default entries for the BFD ELF target vector are found mainly in@file{elf.c}. Some functions are found in @file{elfcode.h}.The processor specific files may override particular entries in thetarget vector, but most do not, with one exception: the@samp{bfd_reloc_type_lookup} entry point is always processor specific.@node BFD ELF processor specific support@subsection BFD ELF processor specific supportBy convention, the processor specific support for a particular processorwill be found in @file{elf@var{nn}-@var{cpu}.c}, where @var{nn} iseither 32 or 64, and @var{cpu} is the name of the processor.@menu* BFD ELF processor required:: Required processor specific support* BFD ELF processor linker:: Processor specific linker support* BFD ELF processor other:: Other processor specific support options@end menu@node BFD ELF processor required@subsubsection Required processor specific supportWhen writing a @file{elf@var{nn}-@var{cpu}.c} file, you must do thefollowing:@itemize @bullet@itemDefine either @samp{TARGET_BIG_SYM} or @samp{TARGET_LITTLE_SYM}, orboth, to a unique C name to use for the target vector. This name shouldappear in the list of target vectors in @file{targets.c}, and will alsohave to appear in @file{config.bfd} and @file{configure.in}. Define@samp{TARGET_BIG_SYM} for a big-endian processor,@samp{TARGET_LITTLE_SYM} for a little-endian processor, and define bothfor a bi-endian processor.@itemDefine either @samp{TARGET_BIG_NAME} or @samp{TARGET_LITTLE_NAME}, orboth, to a string used as the name of the target vector. This is thename which a user of the BFD tool would use to specify the object fileformat. It would normally appear in a linker emulation parametersfile.@itemDefine @samp{ELF_ARCH} to the BFD architecture (an element of the@samp{bfd_architecture} enum, typically @samp{bfd_arch_@var{cpu}}).@itemDefine @samp{ELF_MACHINE_CODE} to the magic number which should appearin the @samp{e_machine} field of the ELF header. As of this writing,these magic numbers are assigned by Caldera; if you want to get a magicnumber for a particular processor, try sending a note to@email{registry@@caldera.com}. In the BFD sources, the magic numbers arefound in @file{include/elf/common.h}; they have names beginning with@samp{EM_}.@itemDefine @samp{ELF_MAXPAGESIZE} to the maximum size of a virtual page inmemory. This can normally be found at the start of chapter 5 in theprocessor specific supplement. For a processor which will only be usedin an embedded system, or which has no memory management hardware, thiscan simply be @samp{1}.@itemIf the format should use @samp{Rel} rather than @samp{Rela} relocations,define @samp{USE_REL}. This is normally defined in chapter 4 of theprocessor specific supplement.In the absence of a supplement, it's easier to work with @samp{Rela}relocations. @samp{Rela} relocations will require more space in objectfiles (but not in executables, except when using dynamic linking).However, this is outweighed by the simplicity of addend handling whenusing @samp{Rela} relocations. With @samp{Rel} relocations, the addendmust be stored in the section contents, which makes relocatable linksmore complex.For example, consider C code like @code{i = a[1000];} where @samp{a} isa global array. The instructions which load the value of @samp{a[1000]}will most likely use a relocation which refers to the symbolrepresenting @samp{a}, with an addend that gives the offset from thestart of @samp{a} to element @samp{1000}. When using @samp{Rel}relocations, that addend must be stored in the instructions themselves.If you are adding support for a RISC chip which uses two or moreinstructions to load an address, then the addend may not fit in a singleinstruction, and will have to be somehow split among the instructions.This makes linking awkward, particularly when doing a relocatable linkin which the addend may have to be updated. It can be done---the MIPSELF support does it---but it should be avoided when possible.It is possible, though somewhat awkward, to support both @samp{Rel} and@samp{Rela} relocations for a single target; @file{elf64-mips.c} does itby overriding the relocation reading and writing routines.@itemDefine howto structures for all the relocation types.@itemDefine a @samp{bfd_reloc_type_lookup} routine. This must be named@samp{bfd_elf@var{nn}_bfd_reloc_type_lookup}, and may be either afunction or a macro. It must translate a BFD relocation code into ahowto structure. This is normally a table lookup or a simple switch.@itemIf using @samp{Rel} relocations, define @samp{elf_info_to_howto_rel}.If using @samp{Rela} relocations, define @samp{elf_info_to_howto}.Either way, this is a macro defined as the name of a function whichtakes an @samp{arelent} and a @samp{Rel} or @samp{Rela} structure, andsets the @samp{howto} field of the @samp{arelent} based on the@samp{Rel} or @samp{Rela} structure. This is normally uses@samp{ELF@var{nn}_R_TYPE} to get the ELF relocation type and uses it asan index into a table of howto structures.@end itemizeYou must also add the magic number for this processor to the@samp{prep_headers} function in @file{elf.c}.You must also create a header file in the @file{include/elf} directorycalled @file{@var{cpu}.h}. This file should define any target specificinformation which may be needed outside of the BFD code. In particularit should use the @samp{START_RELOC_NUMBERS}, @samp{RELOC_NUMBER},@samp{FAKE_RELOC}, @samp{EMPTY_RELOC} and @samp{END_RELOC_NUMBERS}macros to create a table mapping the number used to identify arelocation to a name describing that relocation.While not a BFD component, you probably also want to make the binutilsprogram @samp{readelf} parse your ELF objects. For this, you need to addcode for @code{EM_@var{cpu}} as appropriate in @file{binutils/readelf.c}.@node BFD ELF processor linker@subsubsection Processor specific linker supportThe linker will be much more efficient if you define a relocate sectionfunction. This will permit BFD to use the ELF specific linker support.If you do not define a relocate section function, BFD must use thegeneric linker support, which requires converting all symbols andrelocations into BFD @samp{asymbol} and @samp{arelent} structures. Inthis case, relocations will be handled by calling@samp{bfd_perform_relocation}, which will use the howto structures youhave defined. @xref{BFD relocation handling}.In order to support linking into a different object file format, such asS-records, @samp{bfd_perform_relocation} must work correctly with yourhowto structures, so you can't skip that step. However, if you definethe relocate section function, then in the normal case of linking intoan ELF file the linker will not need to convert symbols and relocations,and will be much more efficient.To use a relocation section function, define the macro@samp{elf_backend_relocate_section} as the name of a function which willtake the contents of a section, as well as relocation, symbol, and otherinformation, and modify the section contents according to the relocationinformation. In simple cases, this is little more than a loop over therelocations which computes the value of each relocation and calls@samp{_bfd_final_link_relocate}. The function must check for arelocatable link, and in that case normally needs to do nothing otherthan adjust the addend for relocations against a section symbol.The complex cases generally have to do with dynamic linker support. GOTand PLT relocations must be handled specially, and the linker normallyarranges to set up the GOT and PLT sections while handling relocations.When generating a shared library, random relocations must normally becopied into the shared library, or converted to RELATIVE relocationswhen possible.@node BFD ELF processor other@subsubsection Other processor specific support optionsThere are many other macros which may be defined in@file{elf@var{nn}-@var{cpu}.c}. These macros may be found in@file{elfxx-target.h}.Macros may be used to override some of the generic ELF target vectorfunctions.Several processor specific hook functions which may be defined asmacros. These functions are found as function pointers in the@samp{elf_backend_data} structure defined in @file{elf-bfd.h}. Ingeneral, a hook function is set by defining a macro@samp{elf_backend_@var{name}}.There are a few processor specific constants which may also be defined.These are again found in the @samp{elf_backend_data} structure.I will not define the various functions and constants here; see thecomments in @file{elf-bfd.h}.Normally any odd characteristic of a particular ELF processor is handledvia a hook function. For example, the special @samp{SHN_MIPS_SCOMMON}section number found in MIPS ELF is handled via the hooks@samp{section_from_bfd_section}, @samp{symbol_processing},@samp{add_symbol_hook}, and @samp{output_symbol_hook}.Dynamic linking support, which involves processor specific relocationsrequiring special handling, is also implemented via hook functions.@node BFD ELF core files@subsection BFD ELF core files@cindex elf core filesOn native ELF Unix systems, core files are generated without anysections. Instead, they only have program segments.When BFD is used to read an ELF core file, the BFD sections willactually represent program segments. Since ELF program segments do nothave names, BFD will invent names like @samp{segment@var{n}} where@var{n} is a number.A single ELF program segment may include both an initialized part and anuninitialized part. The size of the initialized part is given by the@samp{p_filesz} field. The total size of the segment is given by the@samp{p_memsz} field. If @samp{p_memsz} is larger than @samp{p_filesz},then the extra space is uninitialized, or, more precisely, initializedto zero.BFD will represent such a program segment as two different sections.The first, named @samp{segment@var{n}a}, will represent the initializedpart of the program segment. The second, named @samp{segment@var{n}b},will represent the uninitialized part.ELF core files store special information such as register values inprogram segments with the type @samp{PT_NOTE}. BFD will attempt tointerpret the information in these segments, and will create additionalsections holding the information. Some of this interpretation requiresinformation found in the host header file @file{sys/procfs.h}, and sowill only work when BFD is built on a native system.BFD does not currently provide any way to create an ELF core file. Ingeneral, BFD does not provide a way to create core files. The way toimplement this would be to write @samp{bfd_set_format} and@samp{bfd_write_contents} routines for the @samp{bfd_core} type; see@ref{BFD target vector format}.@node BFD ELF future@subsection BFD ELF futureThe current dynamic linking support has too much code duplication.While each processor has particular differences, much of the dynamiclinking support is quite similar for each processor. The GOT and PLTare handled in fairly similar ways, the details of -Bsymbolic linkingare generally similar, etc. This code should be reworked to use moregeneric functions, eliminating the duplication.Similarly, the relocation handling has too much duplication. Many ofthe @samp{reloc_type_lookup} and @samp{info_to_howto} functions arequite similar. The relocate section functions are also often quitesimilar, both in the standard linker handling and the dynamic linkerhandling. Many of the COFF processor specific backends share a singlerelocate section function (@samp{_bfd_coff_generic_relocate_section}),and it should be possible to do something like this for the ELF targetsas well.The appearance of the processor specific magic number in@samp{prep_headers} in @file{elf.c} is somewhat bogus. It should bepossible to add support for a new processor without changing the genericsupport.The processor function hooks and constants are ad hoc and need betterdocumentation.When a linker script uses @samp{SIZEOF_HEADERS}, the ELF backend mustguess at the number of program segments which will be required, in@samp{get_program_header_size}. This is because the linker calls@samp{bfd_sizeof_headers} before it knows all the section addresses andsizes. The ELF backend may later discover, when creating programsegments, that more program segments are required. This is currentlyreported as an error in @samp{assign_file_positions_for_segments}.In practice this makes it difficult to use @samp{SIZEOF_HEADERS} exceptwith a carefully defined linker script. Unfortunately,@samp{SIZEOF_HEADERS} is required for fast program loading on a nativesystem, since it permits the initial code section to appear on the samepage as the program segments, saving a page read when the program startsrunning. Fortunately, native systems permit careful definition of thelinker script. Still, ideally it would be possible to use relaxation tocompute the number of program segments.@node BFD glossary@section BFD glossary@cindex glossary for bfd@cindex bfd glossaryThis is a short glossary of some BFD terms.@table @asis@item a.outThe a.out object file format. The original Unix object file format.Still used on SunOS, though not Solaris. Supports only three sections.@item archiveA collection of object files produced and manipulated by the @samp{ar}program.@item backendThe implementation within BFD of a particular object file format. Theset of functions which appear in a particular target vector.@item BFDThe BFD library itself. Also, each object file, archive, or executableopened by the BFD library has the type @samp{bfd *}, and is sometimesreferred to as a bfd.@item COFFThe Common Object File Format. Used on Unix SVR3. Used by someembedded targets, although ELF is normally better.@item DLLA shared library on Windows.@item dynamic linkerWhen a program linked against a shared library is run, the dynamiclinker will locate the appropriate shared library and arrange to somehowinclude it in the running image.@item dynamic objectAnother name for an ELF shared library.@item ECOFFThe Extended Common Object File Format. Used on Alpha Digital Unix(formerly OSF/1), as well as Ultrix and Irix 4. A variant of COFF.@item ELFThe Executable and Linking Format. The object file format used on mostmodern Unix systems, including GNU/Linux, Solaris, Irix, and SVR4. Alsoused on many embedded systems.@item executableA program, with instructions and symbols, and perhaps dynamic linkinginformation. Normally produced by a linker.@item LMALoad Memory Address. This is the address at which a section will beloaded. Compare with VMA, below.@item NLMNetWare Loadable Module. Used to describe the format of an object whichbe loaded into NetWare, which is some kind of PC based network serverprogram.@item object fileA binary file including machine instructions, symbols, and relocationinformation. Normally produced by an assembler.@item object file formatThe format of an object file. Typically object files and executablesfor a particular system are in the same format, although executableswill not contain any relocation information.@item PEThe Portable Executable format. This is the object file format used forWindows (specifically, Win32) object files. It is based closely onCOFF, but has a few significant differences.@item PEIThe Portable Executable Image format. This is the object file formatused for Windows (specifically, Win32) executables. It is very similarto PE, but includes some additional header information.@item relocationsInformation used by the linker to adjust section contents. Also calledrelocs.@item sectionObject files and executable are composed of sections. Sections haveoptional data and optional relocation information.@item shared libraryA library of functions which may be used by many executables withoutactually being linked into each executable. There are several differentimplementations of shared libraries, each having slightly differentfeatures.@item symbolEach object file and executable may have a list of symbols, oftenreferred to as the symbol table. A symbol is basically a name and anaddress. There may also be some additional information like the type ofsymbol, although the type of a symbol is normally something simple likefunction or object, and should be confused with the more complex Cnotion of type. Typically every global function and variable in a Cprogram will have an associated symbol.@item target vectorA set of functions which implement support for a particular object fileformat. The @samp{bfd_target} structure.@item Win32The current Windows API, implemented by Windows 95 and later and WindowsNT 3.51 and later, but not by Windows 3.1.@item XCOFFThe eXtended Common Object File Format. Used on AIX. A variant ofCOFF, with a completely different symbol table implementation.@item VMAVirtual Memory Address. This is the address a section will have whenan executable is run. Compare with LMA, above.@end table@node Index@unnumberedsec Index@printindex cp@contents@bye