Skip to content

Conversation

@amosher-nvidia
Copy link
Contributor

@amosher-nvidia amosher-nvidia commented Dec 9, 2024

According to the binutils spec: https://sourceware.org/binutils/docs/ld/Input-Section-Basics.html

You should be able to specify all files in an archive using this syntax archivename: , however, lld currently will only accept archivename:* to match all files within an archive.

This patch will, only when necessary, create a copy of the file specification and add an implicit wildcard * to the end. It also updates the filename-spec linkerscript test to check for this behavior.

@github-actions
Copy link

github-actions bot commented Dec 9, 2024

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Dec 9, 2024

@llvm/pr-subscribers-lld

@llvm/pr-subscribers-lld-elf

Author: None (amosher-nvidia)

Changes

According to the binutils spec: https://sourceware.org/binutils/docs/ld/Input-Section-Basics.htm

You should be able to specify all files in an archive using this syntax archivename: , however, lld currently will only accept archivename:* to match all files within an archive.

This patch will, only when necessary, create a copy of the file specification and add an implicit wildcard * to the end. It also updates the filename-spec linkerscript test to check for this behavior.


Full diff: https://github.com/llvm/llvm-project/pull/119293.diff

2 Files Affected:

  • (modified) lld/ELF/LinkerScript.h (+12-1)
  • (modified) lld/test/ELF/linkerscript/filename-spec.s (+1-1)
diff --git a/lld/ELF/LinkerScript.h b/lld/ELF/LinkerScript.h
index 328368fd3b4333..b7e84a1849637d 100644
--- a/lld/ELF/LinkerScript.h
+++ b/lld/ELF/LinkerScript.h
@@ -195,6 +195,7 @@ class SectionPattern {
 
 class InputSectionDescription : public SectionCommand {
   SingleStringMatcher filePat;
+  SmallString<0> implicitArchiveWildcardPat;
 
   // Cache of the most recent input argument and result of matchesFile().
   mutable std::optional<std::pair<const InputFile *, bool>> matchesFileCache;
@@ -203,9 +204,19 @@ class InputSectionDescription : public SectionCommand {
   InputSectionDescription(StringRef filePattern, uint64_t withFlags = 0,
                           uint64_t withoutFlags = 0, StringRef classRef = {})
       : SectionCommand(InputSectionKind), filePat(filePattern),
-        classRef(classRef), withFlags(withFlags), withoutFlags(withoutFlags) {
+        implicitArchiveWildcardPat(), classRef(classRef), withFlags(withFlags),
+        withoutFlags(withoutFlags) {
     assert((filePattern.empty() || classRef.empty()) &&
            "file pattern and class reference are mutually exclusive");
+
+    // Fixes up the input file pattern, adding an implicit wildcard
+    // if the trailing character is an ':' to allow matching entire archives
+    if (!filePattern.empty() && filePattern.back() == ':') {
+      implicitArchiveWildcardPat.reserve(filePattern.size() + 1);
+      implicitArchiveWildcardPat.append(filePattern);
+      implicitArchiveWildcardPat.push_back('*');
+      filePat = SingleStringMatcher(implicitArchiveWildcardPat);
+    }
   }
 
   static bool classof(const SectionCommand *c) {
diff --git a/lld/test/ELF/linkerscript/filename-spec.s b/lld/test/ELF/linkerscript/filename-spec.s
index 4fc4f2f4217528..d91b4a76ca24e2 100644
--- a/lld/test/ELF/linkerscript/filename-spec.s
+++ b/lld/test/ELF/linkerscript/filename-spec.s
@@ -55,7 +55,7 @@
 # RUN: llvm-objdump -s 8 | FileCheck --check-prefix=SECONDFIRST %s
 
 ## Verify matching of archive library names in KEEP.
-# RUN: echo 'SECTIONS{.foo :{ KEEP(*lib2*(.foo)) KEEP(*lib1*(.foo)) }}' > 9.t
+# RUN: echo 'SECTIONS{.foo :{ KEEP(*lib2.a:(.foo)) KEEP(*lib1*(.foo)) }}' > 9.t
 # RUN: ld.lld -o 9 -T 9.t --whole-archive \
 # RUN:   dir1/lib1.a dir2/lib2.a
 # RUN: llvm-objdump -s 9 | FileCheck --check-prefix=SECONDFIRST %s

@MaskRay
Copy link
Member

MaskRay commented Dec 12, 2024

sourceware.org/binutils/docs/ld/Input-Section-Basics.htm

missing l in htm


class InputSectionDescription : public SectionCommand {
SingleStringMatcher filePat;
SmallString<0> implicitArchiveWildcardPat;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: move before since the lifetime of the SmallString should be larger than filePat

@smithp35
Copy link
Collaborator

I happened to run across the same problem yesterday and didn't realise that this existed #119584 . I started a fix myself which I've attached. It is only work in progress, but uses a slightly different approach. I've pasted it here just in case you want to adopt it.

This also fixes the :file syntax which LLD doesn't support either.

EXCLUDE_FILE can also use the same problem. My plan for that was to extract the MatchType and filePat into a separate struct so that for each EXCLUDE_FILE we could use similar logic.

diff --git a/lld/ELF/LinkerScript.cpp b/lld/ELF/LinkerScript.cpp
index 7d24c6750b0d..47ec329e5a84 100644
--- a/lld/ELF/LinkerScript.cpp
+++ b/lld/ELF/LinkerScript.cpp
@@ -407,11 +407,21 @@ static inline StringRef getFilename(const InputFile *file) {
 }

 bool InputSectionDescription::matchesFile(const InputFile *file) const {
-  if (filePat.isTrivialMatchAll())
+  if (matchType != FileOnly && filePat.isTrivialMatchAll())
     return true;

+  StringRef fileName = getFilename(file);
+  if (matchType == FileOnly && !file->archiveName.empty())
+    return false;
+
+  if (matchType == LibOnly) {
+    if (file->archiveName.empty())
+      return false;
+    fileName = file->archiveName;
+  }
+
   if (!matchesFileCache || matchesFileCache->first != file)
-    matchesFileCache.emplace(file, filePat.match(getFilename(file)));
+    matchesFileCache.emplace(file, filePat.match(fileName));

   return matchesFileCache->second;
 }
diff --git a/lld/ELF/LinkerScript.h b/lld/ELF/LinkerScript.h
index 328368fd3b43..b83feda2bea2 100644
--- a/lld/ELF/LinkerScript.h
+++ b/lld/ELF/LinkerScript.h
@@ -195,7 +195,7 @@ public:

 class InputSectionDescription : public SectionCommand {
   SingleStringMatcher filePat;
-
+  enum MatchType { LibAndFile, FileOnly, LibOnly } matchType = LibAndFile;
   // Cache of the most recent input argument and result of matchesFile().
   mutable std::optional<std::pair<const InputFile *, bool>> matchesFileCache;

@@ -206,6 +206,13 @@ public:
         classRef(classRef), withFlags(withFlags), withoutFlags(withoutFlags) {
     assert((filePattern.empty() || classRef.empty()) &&
            "file pattern and class reference are mutually exclusive");
+    if (filePattern.starts_with(':')) {
+      filePat = filePattern.drop_front();
+      matchType = FileOnly;
+    } else if (filePattern.ends_with(':')) {
+      filePat = filePattern.drop_back();
+      matchType = LibOnly;
+    }
   }

   static bool classof(const SectionCommand *c) {

@amosher-nvidia amosher-nvidia force-pushed the amosher/archive-implicit-filename branch from eb7db25 to 4c1215f Compare December 17, 2024 00:14
@amosher-nvidia amosher-nvidia changed the title [lld][ELF] Allow implicit wildcard in archive file name [lld][ELF] Handle archive special casing in Input Sections Dec 17, 2024
@amosher-nvidia
Copy link
Contributor Author

Thanks @smithp35! I took your general idea and implemented it slightly differently for better caching and added/tweaked some unit tests.

}

static inline StringRef getArchiveName(const InputFile *file) {
return file ? static_cast<StringRef>(file->archiveName) : StringRef();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StringRef(file->archiveName)

https://en.cppreference.com/w/cpp/language/static_cast you were using the unnecessarily complex "If target-type is a reference type, the effect is the same as performing the declaration and initialization target-type temp(expression ); "

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, file is guaranteed to be non-nullptr. I am refactoring the caller to take a reference instead of a pointer to make this clear. Just delete this function

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for reviewing, I also went ahead and removed getFilename since it serves the same purpose.

return file ? file->getNameForScript() : StringRef();
}

static inline StringRef getArchiveName(const InputFile *file) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete inline

@amosher-nvidia amosher-nvidia force-pushed the amosher/archive-implicit-filename branch from e0f5e18 to 2a895c4 Compare December 17, 2024 21:39
@smithp35
Copy link
Collaborator

Thanks @smithp35! I took your general idea and implemented it slightly differently for better caching and added/tweaked some unit tests.

Thank you!

At some point we may need to look at the matching in EXCLUDE_FILES but I think that can be done separately. I don't have any other comments.

@amosher-nvidia amosher-nvidia requested a review from MaskRay January 3, 2025 19:13

## Verify that matching files excluded from an archive doesn't match files within one
# RUN: echo 'SECTIONS{.foo :{ KEEP(:*x.o(.foo)) KEEP(*y.o(.foo)) KEEP(*x.o(.foo)) }}' > 12.t
# RUN: ld.lld -o 12 -T 12.t --whole-archive \
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

combined.a doesn't need to be wrapped

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ping

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry about the delay, missed this comment somehow. Just pushed an updated commit with this changed and freshly re-based onto main. Thanks for taking the time to review (:

@amosher-nvidia amosher-nvidia force-pushed the amosher/archive-implicit-filename branch from e30bcb6 to 9e35ee0 Compare January 11, 2025 02:24
# RUN: ld.lld -o 11 -T 11.t --whole-archive 'lib1().a' dir2/lib2.a
# RUN: llvm-objdump -s 11 | FileCheck --check-prefix=SECONDFIRST %s

## Verify that matching files excluded from an archive doesn't match files within one
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Complete sentences in comments end with .

@MaskRay MaskRay merged commit 1807860 into llvm:main Jan 11, 2025
5 of 6 checks passed
@github-actions
Copy link

@amosher-nvidia Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

BaiXilin pushed a commit to BaiXilin/llvm-project that referenced this pull request Jan 12, 2025
According to the binutils spec:
https://sourceware.org/binutils/docs/ld/Input-Section-Basics.html

You should be able to specify all files in an archive using this syntax
`archivename:` , however, lld currently will only accept `archivename:*`
to match all files within an archive.

This patch will, only when necessary, create a copy of the file
specification and add an implicit wildcard `*` to the end. It also
updates the filename-spec linkerscript test to check for this behavior.

---------

Co-authored-by: Peter Smith <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants