Skip to content

[DTLTO] Remove temporary files on abnormal exit, e.g. CTRL-C - #172280

Merged
bd1976bris merged 1 commit into
llvm:mainfrom
bd1976bris:dtlto_ctrl_c_leaves_files
Dec 17, 2025
Merged

bd1976bris merged 1 commit into
llvm:mainfrom
bd1976bris:dtlto_ctrl_c_leaves_files

Conversation

@bd1976bris

Copy link
Copy Markdown
Contributor

Ensure that DTLTO temporary files are removed when the link exits due to CTRL-C or comparable interrupt events.

Fixes: #171778

Ensure that DTLTO temporary files are removed when the link exits
due to CTRL-C or comparable interrupt events.

Fixes: llvm#171778
@llvmbot llvmbot added the LTO Link time optimization (regular/full LTO or ThinLTO) label Dec 15, 2025
@llvmbot

llvmbot commented Dec 15, 2025

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-lto

Author: Ben Dunbobbin (bd1976bris)

Changes

Ensure that DTLTO temporary files are removed when the link exits due to CTRL-C or comparable interrupt events.

Fixes: #171778


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

2 Files Affected:

  • (added) cross-project-tests/dtlto/signal.test (+89)
  • (modified) llvm/lib/LTO/LTO.cpp (+11)
diff --git a/cross-project-tests/dtlto/signal.test b/cross-project-tests/dtlto/signal.test
new file mode 100644
index 0000000000000..95b6bf368b577
--- /dev/null
+++ b/cross-project-tests/dtlto/signal.test
@@ -0,0 +1,89 @@
+REQUIRES: ld.lld
+
+# Test that if a link is terminated by a signal (or the equivalent on
+# Windows), e.g. CTRL-C, DTLTO temporary files are cleaned up.
+
+RUN: rm -rf %t && split-file %s %t && cd %t
+
+RUN: %clang --target=x86_64-linux-gnu -O2 t1.c t2.c -flto=thin -c
+
+DEFINE: %{kill-dtlto} = %python killer.py %clang --target=x86_64-linux-gnu \
+DEFINE:   -nostdlib -O2 -flto=thin -fuse-ld=lld t1.o t2.o \
+DEFINE:   -fthinlto-distributor=%python \
+DEFINE:   -Xthinlto-distributor=local_codegen_and_wait.py
+
+# Check that all temporary files are removed if the process is aborted.
+RUN: mkdir none
+RUN: %{kill-dtlto} -o none/t.elf
+RUN: ls none | FileCheck %s --allow-empty --check-prefix=EMPTY
+
+EMPTY-NOT: {{.}}
+
+# Check that --save-temps preserves all the files.
+RUN: rm send-signal && mkdir all
+RUN: %{kill-dtlto} -Wl,--save-temps -o all/t.elf
+RUN: ls all | sort | FileCheck %s --check-prefixes=BOOKEND,TEMPS,INDEX
+
+# Check that --thinlto-emit-index-files preserves the index files.
+RUN: rm send-signal && mkdir index
+RUN: %{kill-dtlto} -Wl,--thinlto-emit-index-files -o index/t.elf
+RUN: ls index | sort | FileCheck %s --check-prefixes=BOOKEND,INDEX
+
+# No files are expected before.
+BOOKEND-NOT: {{.}}
+TEMPS: {{^}}t.[[#]].dist-file.json{{$}}
+TEMPS: {{^}}t.elf.{{.+$}}
+TEMPS: {{^}}t1.1.[[#]].native.o{{$}}
+INDEX: {{^}}t1.1.[[#]].native.o.thinlto.bc{{$}}
+TEMPS: {{^}}t2.2.[[#]].native.o{{$}}
+INDEX: {{^}}t2.2.[[#]].native.o.thinlto.bc{{$}}
+# No files are expected after.
+BOOKEND-NOT: {{.}}
+
+#--- t1.c
+__attribute__((retain)) int t1(int x) { return x; }
+
+#--- t2.c
+__attribute__((retain)) int t2(int x) { return x; }
+
+#--- local_codegen_and_wait.py
+"""Perform codegen locally, create "send-signal" file and wait."""
+from pathlib import Path
+import json, subprocess, sys, time
+
+# Load the DTLTO information from the input JSON file.
+data = json.loads(Path(sys.argv[-1]).read_bytes())
+
+# Iterate over the jobs and execute the codegen tool.
+for job in data["jobs"]:
+    subprocess.check_call(data["common"]["args"] + job["args"])
+Path("send-signal").touch()
+while True:
+    time.sleep(1)
+
+#--- killer.py
+"""Run command, wait for "send-signal" file to exist, and then send a
+termination signal."""
+import os, sys, time, signal, subprocess
+
+if os.name == "nt":
+    # CREATE_NEW_PROCESS_GROUP is used so that p.send_signal(CTRL_BREAK_EVENT)
+    # does not get sent to the LIT processes that are running the test.
+    kwargs = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
+else:
+    # Makes the child a process-group leader so os.killpg(p.pid, SIGINT) works.
+    kwargs = {"start_new_session": True}
+
+p = subprocess.Popen(sys.argv[1:], **kwargs)
+
+while not os.path.exists("send-signal"):
+    time.sleep(0.05)
+
+if os.name == "nt":
+    # Note that CTRL_C_EVENT does not appear to work for clang.
+    p.send_signal(signal.CTRL_BREAK_EVENT)
+else:
+    os.killpg(p.pid, signal.SIGINT)
+p.wait()
+
+sys.exit(0 if p.returncode != 0 else 1)
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index a02af59600c44..d5939ae83c5b5 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -48,6 +48,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
 #include "llvm/Support/SHA1.h"
+#include "llvm/Support/Signals.h"
 #include "llvm/Support/SourceMgr.h"
 #include "llvm/Support/ThreadPool.h"
 #include "llvm/Support/Threading.h"
@@ -2354,6 +2355,13 @@ class OutOfProcessThinBackend : public CGThinBackend {
          nullptr,
          false};
 
+    // Cleanup per-job temporary files on abnormal process exit.
+    if (!SaveTemps) {
+      llvm::sys::RemoveFileOnSignal(J.NativeObjectPath);
+      if (!ShouldEmitIndexFiles)
+        llvm::sys::RemoveFileOnSignal(J.SummaryIndexPath);
+    }
+
     assert(ModuleToDefinedGVSummaries.count(ModulePath));
 
     // The BackendThreadPool is only used here to write the sharded index files
@@ -2535,6 +2543,9 @@ class OutOfProcessThinBackend : public CGThinBackend {
     SString JsonFile = sys::path::parent_path(LinkerOutputFile);
     sys::path::append(JsonFile, sys::path::stem(LinkerOutputFile) + "." + UID +
                                     ".dist-file.json");
+    // Cleanup DTLTO JSON file on abnormal process exit.
+    if (!SaveTemps)
+      llvm::sys::RemoveFileOnSignal(JsonFile);
     if (!emitDistributorJson(JsonFile))
       return make_error<StringError>(
           BCError + "failed to generate distributor JSON script: " + JsonFile,

@bd1976bris

Copy link
Copy Markdown
Contributor Author

@teresajohnson teresajohnson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

@bd1976bris
bd1976bris merged commit 0ecadb0 into llvm:main Dec 17, 2025
mahesh-attarde pushed a commit to mahesh-attarde/llvm-project that referenced this pull request Dec 19, 2025
…2280)

Ensure that DTLTO temporary files are removed when the
link exits due to CTRL-C or comparable interrupt events.

Fixes: llvm#171778
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

LTO Link time optimization (regular/full LTO or ThinLTO)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[DTLTO] Terminating a DTLTO link via "Ctrl-C" leaves behind temporary files

3 participants