Skip to content

Commit

Permalink
[ELF] Full support for -n (--nmagic) and -N (--omagic) via common page
Browse files Browse the repository at this point in the history
The -n (--nmagic) disables page alignment, and acts as a -Bstatic
The -N (--omagic) does what -n does but also marks the executable segment as
writeable. As page alignment is disabled headers are not allocated unless
explicit in the linker script.

To disable page alignment in LLD we choose to set the page sizes to 1 so
that any alignment based on the page size does nothing. To set the
Target->PageSize to 1 we implement -z common-page-size, which has the side
effect of allowing the user to set the value as well.

Setting the page alignments to 1 does mean that any use of
CONSTANT(MAXPAGESIZE) or CONSTANT(COMMONPAGESIZE) in a linker script will
return 1, unlike in ld.bfd. However given that -n and -N disable paging
these probably shouldn't be used in a linker script where -n or -N is in
use.

Differential Revision: https://reviews.llvm.org/D61688

llvm-svn: 360593
  • Loading branch information
smithp35 committed May 13, 2019
1 parent d3cedee commit 4e21c77
Show file tree
Hide file tree
Showing 14 changed files with 515 additions and 22 deletions.
2 changes: 1 addition & 1 deletion lld/ELF/Arch/SPARCV9.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ SPARCV9::SPARCV9() {
PltEntrySize = 32;
PltHeaderSize = 4 * PltEntrySize;

PageSize = 8192;
DefaultCommonPageSize = 8192;
DefaultMaxPageSize = 0x100000;
DefaultImageBase = 0x100000;
}
Expand Down
2 changes: 2 additions & 0 deletions lld/ELF/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ struct Configuration {
bool LTONewPassManager;
bool MergeArmExidx;
bool MipsN32Abi = false;
bool Nmagic;
bool NoinhibitExec;
bool Nostdlib;
bool OFormatBinary;
Expand Down Expand Up @@ -219,6 +220,7 @@ struct Configuration {
uint16_t DefaultSymbolVersion = llvm::ELF::VER_NDX_GLOBAL;
uint16_t EMachine = llvm::ELF::EM_NONE;
llvm::Optional<uint64_t> ImageBase;
uint64_t CommonPageSize;
uint64_t MaxPageSize;
uint64_t MipsGotSize;
uint64_t ZStackSize;
Expand Down
49 changes: 43 additions & 6 deletions lld/ELF/Driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,8 @@ static bool isKnownZFlag(StringRef S) {
S == "nokeep-text-section-prefix" || S == "norelro" || S == "notext" ||
S == "now" || S == "origin" || S == "relro" || S == "retpolineplt" ||
S == "rodynamic" || S == "text" || S == "wxneeded" ||
S.startswith("max-page-size=") || S.startswith("stack-size=");
S.startswith("common-page-size") || S.startswith("max-page-size=") ||
S.startswith("stack-size=");
}

// Report an error for an unknown -z option.
Expand Down Expand Up @@ -829,6 +830,7 @@ static void readConfigs(opt::InputArgList &Args) {
Config->MipsGotSize = args::getInteger(Args, OPT_mips_got_size, 0xfff0);
Config->MergeArmExidx =
Args.hasFlag(OPT_merge_exidx_entries, OPT_no_merge_exidx_entries, true);
Config->Nmagic = Args.hasFlag(OPT_nmagic, OPT_no_nmagic, false);
Config->NoinhibitExec = Args.hasArg(OPT_noinhibit_exec);
Config->Nostdlib = Args.hasArg(OPT_nostdlib);
Config->OFormatBinary = isOutputFormatBinary(Args);
Expand Down Expand Up @@ -957,11 +959,10 @@ static void readConfigs(opt::InputArgList &Args) {
if (Args.hasArg(OPT_print_map))
Config->MapFile = "-";

// --omagic is an option to create old-fashioned executables in which
// .text segments are writable. Today, the option is still in use to
// create special-purpose programs such as boot loaders. It doesn't
// make sense to create PT_GNU_RELRO for such executables.
if (Config->Omagic)
// Page alignment can be disabled by the -n (--nmagic) and -N (--omagic).
// As PT_GNU_RELRO relies on Paging, do not create it when we have disabled
// it.
if (Config->Nmagic || Config->Omagic)
Config->ZRelro = false;

std::tie(Config->BuildId, Config->BuildIdVector) = getBuildId(Args);
Expand Down Expand Up @@ -1114,6 +1115,8 @@ void LinkerDriver::createFiles(opt::InputArgList &Args) {
Config->AsNeeded = false;
break;
case OPT_Bstatic:
case OPT_omagic:
case OPT_nmagic:
Config->Static = true;
break;
case OPT_Bdynamic:
Expand Down Expand Up @@ -1199,6 +1202,29 @@ static uint64_t getMaxPageSize(opt::InputArgList &Args) {
Target->DefaultMaxPageSize);
if (!isPowerOf2_64(Val))
error("max-page-size: value isn't a power of 2");
if (Config->Nmagic || Config->Omagic) {
if (Val != Target->DefaultMaxPageSize)
warn("-z max-page-size set, but paging disabled by omagic or nmagic");
return 1;
}
return Val;
}

// Parse -z common-page-size=<value>. The default value is defined by
// each target.
static uint64_t getCommonPageSize(opt::InputArgList &Args) {
uint64_t Val = args::getZOptionValue(Args, OPT_z, "common-page-size",
Target->DefaultCommonPageSize);
if (!isPowerOf2_64(Val))
error("common-page-size: value isn't a power of 2");
if (Config->Nmagic || Config->Omagic) {
if (Val != Target->DefaultCommonPageSize)
warn("-z common-page-size set, but paging disabled by omagic or nmagic");
return 1;
}
// CommonPageSize can't be larger than MaxPageSize.
if (Val > Config->MaxPageSize)
Val = Config->MaxPageSize;
return Val;
}

Expand Down Expand Up @@ -1623,7 +1649,18 @@ template <class ELFT> void LinkerDriver::link(opt::InputArgList &Args) {
llvm::erase_if(InputSections, [](InputSectionBase *S) { return S->Debug; });

Config->EFlags = Target->calcEFlags();
// MaxPageSize (sometimes called abi page size) is the maximum page size that
// the output can be run on. For example if the OS can use 4k or 64k page
// sizes then MaxPageSize must be 64 for the output to be useable on both.
// All important alignment decisions must use this value.
Config->MaxPageSize = getMaxPageSize(Args);
// CommonPageSize is the most common page size that the output will be run on.
// For example if an OS can use 4k or 64k page sizes and 4k is more common
// than 64k then CommonPageSize is set to 4k. CommonPageSize can be used for
// optimizations such as DATA_SEGMENT_ALIGN in linker scripts. LLD's use of it
// is limited to writing trap instructions on the last executable segment.
Config->CommonPageSize = getCommonPageSize(Args);

Config->ImageBase = getImageBase(Args);

if (Config->EMachine == EM_ARM) {
Expand Down
4 changes: 3 additions & 1 deletion lld/ELF/LinkerScript.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -993,8 +993,10 @@ void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
llvm::any_of(PhdrsCommands, [](const PhdrsCommand &Cmd) {
return Cmd.HasPhdrs || Cmd.HasFilehdr;
});
bool Paged = !Config->Omagic && !Config->Nmagic;
uint64_t HeaderSize = getHeaderSize();
if (HeaderSize <= Min - computeBase(Min, HasExplicitHeaders)) {
if ((Paged || HasExplicitHeaders) &&
HeaderSize <= Min - computeBase(Min, HasExplicitHeaders)) {
Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
Out::ElfHeader->Addr = Min;
Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
Expand Down
11 changes: 9 additions & 2 deletions lld/ELF/Options.td
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ defm merge_exidx_entries: B<"merge-exidx-entries",
"Enable merging .ARM.exidx entries (default)",
"Disable merging .ARM.exidx entries">;

def nmagic: F<"nmagic">, MetaVarName<"<magic>">,
HelpText<"Do not page align sections, link against static libraries.">;

def nostdlib: F<"nostdlib">,
HelpText<"Only search directories specified on the command line">;

Expand All @@ -230,8 +233,11 @@ def no_dynamic_linker: F<"no-dynamic-linker">,
def noinhibit_exec: F<"noinhibit-exec">,
HelpText<"Retain the executable output file whenever it is still usable">;

def no_nmagic: F<"no-nmagic">, MetaVarName<"<magic>">,
HelpText<"Page align sections (default)">;

def no_omagic: F<"no-omagic">, MetaVarName<"<magic>">,
HelpText<"Do not set the text data sections to be writable">;
HelpText<"Do not set the text data sections to be writable, page align sections (default)">;

def no_rosegment: F<"no-rosegment">,
HelpText<"Do not put read-only non-executable sections in their own segment">;
Expand All @@ -246,7 +252,7 @@ def oformat: Separate<["--"], "oformat">, MetaVarName<"<format>">,
HelpText<"Specify the binary format for the output object file">;

def omagic: Flag<["--"], "omagic">, MetaVarName<"<magic>">,
HelpText<"Set the text and data sections to be readable and writable">;
HelpText<"Set the text and data sections to be readable and writable, do not page align sections, link against static libraries">;

defm orphan_handling:
Eq<"orphan-handling", "Control how orphan sections are handled when linker script used">;
Expand Down Expand Up @@ -414,6 +420,7 @@ def: Separate<["-"], "b">, Alias<format>, HelpText<"Alias for --format">;
def: JoinedOrSeparate<["-"], "l">, Alias<library>, HelpText<"Alias for --library">;
def: JoinedOrSeparate<["-"], "L">, Alias<library_path>, HelpText<"Alias for --library-path">;
def: F<"no-pic-executable">, Alias<no_pie>, HelpText<"Alias for --no-pie">;
def: Flag<["-"], "n">, Alias<nmagic>, HelpText<"Alias for --nmagic">;
def: Flag<["-"], "N">, Alias<omagic>, HelpText<"Alias for --omagic">;
def: Joined<["--"], "output=">, Alias<o>, HelpText<"Alias for -o">;
def: Separate<["--"], "output">, Alias<o>, HelpText<"Alias for -o">;
Expand Down
2 changes: 1 addition & 1 deletion lld/ELF/ScriptParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ Expr ScriptParser::getPageSize() {
std::string Location = getCurrentLocation();
return [=]() -> uint64_t {
if (Target)
return Target->PageSize;
return Config->CommonPageSize;
error(Location + ": unable to calculate page size");
return 4096; // Return a dummy value.
};
Expand Down
2 changes: 1 addition & 1 deletion lld/ELF/Target.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class TargetInfo {

virtual ~TargetInfo();

unsigned PageSize = 4096;
unsigned DefaultCommonPageSize = 4096;
unsigned DefaultMaxPageSize = 4096;

uint64_t getImageBase() const;
Expand Down
13 changes: 7 additions & 6 deletions lld/ELF/Writer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2132,7 +2132,7 @@ template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
// segment is the last loadable segment, align the offset of the
// following section to avoid loading non-segments parts of the file.
if (LastRX && LastRX->LastSec == Sec)
Off = alignTo(Off, Target->PageSize);
Off = alignTo(Off, Config->CommonPageSize);
}

SectionHeaderOff = alignTo(Off, Config->Wordsize);
Expand Down Expand Up @@ -2184,7 +2184,7 @@ template <class ELFT> void Writer<ELFT>::setPhdrs() {
// The glibc dynamic loader rounds the size down, so we need to round up
// to protect the last page. This is a no-op on FreeBSD which always
// rounds up.
P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
P->p_memsz = alignTo(P->p_memsz, Config->CommonPageSize);
}

if (P->p_type == PT_TLS && P->p_memsz) {
Expand Down Expand Up @@ -2477,10 +2477,10 @@ template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
// Fill the last page.
for (PhdrEntry *P : Phdrs)
if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
fillTrap(Out::BufferStart +
alignDown(P->p_offset + P->p_filesz, Target->PageSize),
fillTrap(Out::BufferStart + alignDown(P->p_offset + P->p_filesz,
Config->CommonPageSize),
Out::BufferStart +
alignTo(P->p_offset + P->p_filesz, Target->PageSize));
alignTo(P->p_offset + P->p_filesz, Config->CommonPageSize));

// Round up the file size of the last segment to the page boundary iff it is
// an executable segment to ensure that other tools don't accidentally
Expand All @@ -2491,7 +2491,8 @@ template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
Last = P;

if (Last && (Last->p_flags & PF_X))
Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
Last->p_memsz = Last->p_filesz =
alignTo(Last->p_filesz, Config->CommonPageSize);
}

// Write section contents to a mmap'ed file.
Expand Down
8 changes: 7 additions & 1 deletion lld/docs/ld.lld.1
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ Set target emulation.
.It Fl -Map Ns = Ns Ar file , Fl M Ar file
Print a link map to
.Ar file .
.It Fl -nmagic , Fl n
Do not page align sections, link against static libraries.
.It Fl -no-allow-shlib-undefined
Do not allow unresolved references in shared libraries.
This option is enabled by default when linking an executable.
Expand All @@ -277,6 +279,10 @@ Disable garbage collection of unused sections.
Disable STB_GNU_UNIQUE symbol binding.
.It Fl -no-merge-exidx-entries
Disable merging .ARM.exidx entries.
.It F1 -no-nmagic
Page align sections.
.It F1 -no-omagic
Do not set the text data sections to be writable, page align sections.
.It Fl -no-rosegment
Do not put read-only non-executable sections in their own segment.
.It Fl -no-threads
Expand Down Expand Up @@ -325,7 +331,7 @@ is
.Cm binary ,
which produces output with no ELF header.
.It Fl -omagic , Fl N
Set the text and data sections to be readable and writable.
Set the text and data sections to be readable and writable, do not page align sections, link against static libraries.
.It Fl -opt-remarks-filename Ar file
Write optimization remarks in YAML format to
.Ar file .
Expand Down
Loading

0 comments on commit 4e21c77

Please sign in to comment.