Skip to content

Instantly share code, notes, and snippets.

@rui314
Created August 21, 2023 04:35
Show Gist options
  • Save rui314/1922c5f8b177b459be82aab601ffde9d to your computer and use it in GitHub Desktop.
Save rui314/1922c5f8b177b459be82aab601ffde9d to your computer and use it in GitHub Desktop.
diff --git a/elf/cmdline.cc b/elf/cmdline.cc
index 483da828..9af205be 100644
--- a/elf/cmdline.cc
+++ b/elf/cmdline.cc
@@ -704,6 +704,8 @@ std::vector<std::string> parse_nonpositional_args(Context<E> &ctx) {
ctx.arg.apply_dynamic_relocs = true;
} else if (read_flag("no-apply-dynamic-relocs")) {
ctx.arg.apply_dynamic_relocs = false;
+ } else if (read_flag("allocate-bss")) {
+ ctx.arg.allocate_bss = true;
} else if (read_flag("trace")) {
ctx.arg.trace = true;
} else if (read_flag("eh-frame-hdr")) {
diff --git a/elf/input-sections.cc b/elf/input-sections.cc
index 22900ba8..735fd427 100644
--- a/elf/input-sections.cc
+++ b/elf/input-sections.cc
@@ -419,8 +419,10 @@ void InputSection<E>::apply_toc_rel(Context<E> &ctx, Symbol<E> &sym,
template <typename E>
void InputSection<E>::write_to(Context<E> &ctx, u8 *buf) {
- if (shdr().sh_type == SHT_NOBITS || sh_size == 0)
+ if (shdr().sh_type == SHT_NOBITS) {
+ memset(buf, 0, shdr().sh_size);
return;
+ }
// Copy data
if constexpr (is_riscv<E>)
diff --git a/elf/mold.h b/elf/mold.h
index 331ea481..5e87bb4a 100644
--- a/elf/mold.h
+++ b/elf/mold.h
@@ -1770,6 +1770,7 @@ struct Context {
UnresolvedKind unresolved_symbols = UNRESOLVED_ERROR;
bool Bsymbolic = false;
bool Bsymbolic_functions = false;
+ bool allocate_bss = false;
bool allow_multiple_definition = false;
bool apply_dynamic_relocs = true;
bool color_diagnostics = false;
diff --git a/elf/output-chunks.cc b/elf/output-chunks.cc
index 84b17b61..36e2bcdf 100644
--- a/elf/output-chunks.cc
+++ b/elf/output-chunks.cc
@@ -859,6 +859,9 @@ OutputSection<E>::OutputSection(Context<E> &ctx, std::string_view name,
it != ctx.arg.section_align.end())
this->shdr.sh_addralign = it->second;
+ if (ctx.arg.allocate_bss && this->shdr.sh_type == SHT_NOBITS)
+ this->shdr.sh_type = SHT_PROGBITS;
+
// PT_GNU_RELRO segment is a security mechanism to make more pages
// read-only than we could have done without it.
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment