[llvm] [OFFLOAD] New bintool to extract images from binaries (PR #181689)
Alex Duran via llvm-commits
llvm-commits at lists.llvm.org
Mon Feb 16 07:39:30 PST 2026
https://github.com/adurang created https://github.com/llvm/llvm-project/pull/181689
A tool that uses llvm libraries and libofflod to generate different images from a binary.
>From 0a897d05677358df3a25176d2eca789b877e2b34 Mon Sep 17 00:00:00 2001
From: Alex Duran <alejandro.duran at intel.com>
Date: Mon, 16 Feb 2026 16:37:15 +0100
Subject: [PATCH] [OFFLOAD] New bintool to extract images from binaries
---
offload/liboffload/API/Program.td | 11 ++
offload/liboffload/src/OffloadImpl.cpp | 7 +
offload/tools/CMakeLists.txt | 1 +
offload/tools/bintool/CMakeLists.txt | 29 +++
.../tools/bintool/llvm-offload-bintool.cpp | 182 ++++++++++++++++++
5 files changed, 230 insertions(+)
create mode 100644 offload/tools/bintool/CMakeLists.txt
create mode 100644 offload/tools/bintool/llvm-offload-bintool.cpp
diff --git a/offload/liboffload/API/Program.td b/offload/liboffload/API/Program.td
index 7e11b3d8e331e..7a4995b0efbfb 100644
--- a/offload/liboffload/API/Program.td
+++ b/offload/liboffload/API/Program.td
@@ -44,3 +44,14 @@ def olDestroyProgram : Function {
];
let returns = [];
}
+
+def olGetProgramDeviceImage : Function {
+ let desc = "Obtain the image loaded on the device for a program.";
+ let details = [];
+ let params = [
+ Param<"ol_program_handle_t", "Program", "handle of the program", PARAM_IN>,
+ Param<"const char **", "Image", "output buffer with the image", PARAM_OUT>,
+ Param<"size_t *", "ImageSize", "size of the image", PARAM_OUT>
+ ];
+ let returns = [];
+}
diff --git a/offload/liboffload/src/OffloadImpl.cpp b/offload/liboffload/src/OffloadImpl.cpp
index db8a5f3a78258..1f40a72764642 100644
--- a/offload/liboffload/src/OffloadImpl.cpp
+++ b/offload/liboffload/src/OffloadImpl.cpp
@@ -983,6 +983,13 @@ Error olIsValidBinary_impl(ol_device_handle_t Device, const void *ProgData,
return Error::success();
}
+Error olGetProgramDeviceImage_impl(ol_program_handle_t Program, const char **ImageData,
+ size_t *ImageSize) {
+ *ImageData = Program->DeviceImage.getBufferStart();
+ *ImageSize = Program->DeviceImage.getBufferSize();
+ return Error::success();
+}
+
Error olDestroyProgram_impl(ol_program_handle_t Program) {
auto &Device = Program->Image->getDevice();
if (auto Err = Device.unloadBinary(Program->Image))
diff --git a/offload/tools/CMakeLists.txt b/offload/tools/CMakeLists.txt
index 13772a4a675e5..35d0b3d1e0961 100644
--- a/offload/tools/CMakeLists.txt
+++ b/offload/tools/CMakeLists.txt
@@ -12,5 +12,6 @@ macro(add_openmp_tool_symlink name)
llvm_add_tool_symlink(OPENMP ${ARGV})
endmacro()
+add_subdirectory(bintool)
add_subdirectory(deviceinfo)
add_subdirectory(kernelreplay)
diff --git a/offload/tools/bintool/CMakeLists.txt b/offload/tools/bintool/CMakeLists.txt
new file mode 100644
index 0000000000000..574d191c2e294
--- /dev/null
+++ b/offload/tools/bintool/CMakeLists.txt
@@ -0,0 +1,29 @@
+# INTEL_CUSTOMIZATION
+#
+# INTEL CONFIDENTIAL
+#
+# Modifications, Copyright (C) 2021 Intel Corporation
+#
+# This software and the related documents are Intel copyrighted materials, and
+# your use of them is governed by the express license under which they were
+# provided to you ("License"). Unless the License provides otherwise, you may not
+# use, modify, copy, publish, distribute, disclose or transmit this software or
+# the related documents without Intel's prior written permission.
+#
+# This software and the related documents are provided as is, with no express
+# or implied warranties, other than those that are expressly stated in the
+# License.
+#
+# end INTEL_CUSTOMIZATION
+message(STATUS "Building the llvm-offload-bintool tool")
+
+add_openmp_tool(
+ llvm-offload-bintool llvm-offload-bintool.cpp
+ ../../plugins-nextgen/common/src/OffloadError.cpp
+)
+
+llvm_update_compile_flags(llvm-offload-bintool)
+
+target_link_libraries(llvm-offload-bintool PRIVATE
+ LLVMOffload LLVMSupport LLVMObject
+)
diff --git a/offload/tools/bintool/llvm-offload-bintool.cpp b/offload/tools/bintool/llvm-offload-bintool.cpp
new file mode 100644
index 0000000000000..48c06f8308b11
--- /dev/null
+++ b/offload/tools/bintool/llvm-offload-bintool.cpp
@@ -0,0 +1,182 @@
+
+#include <OffloadAPI.h>
+
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/BinaryFormat/Magic.h"
+#include "llvm/Object/OffloadBinary.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/FormatVariadic.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Path.h"
+
+#include "OffloadError.h"
+
+#include <iostream>
+#include <vector>
+
+using namespace llvm;
+
+#define OFFLOAD_ERR(X) \
+ if (auto Err = X) { \
+ return make_error<error::OffloadError>( \
+ static_cast<error::ErrorCode>(Err->Code), Err->Details); \
+ }
+
+struct OffloadEnvTy {
+ SmallVector<ol_device_handle_t> FoundDevices;
+};
+
+struct BinEnvTy {
+ StringRef Name;
+ MemoryBufferRef Data;
+
+ BinEnvTy(StringRef Name, MemoryBufferRef Data) : Name(Name), Data(Data) {}
+};
+
+Error init(OffloadEnvTy &Data) {
+ OFFLOAD_ERR(olInit());
+ OFFLOAD_ERR(olIterateDevices(
+ [](ol_device_handle_t Device, void *UserData) {
+ reinterpret_cast<decltype(Data.FoundDevices) *>(UserData)->push_back(
+ Device);
+ return true;
+ },
+ &Data.FoundDevices));
+
+ return Error::success();
+}
+
+Error deinit() {
+ OFFLOAD_ERR(olShutDown());
+ return Error::success();
+}
+
+int dumpBuffer(StringRef Base, StringRef Label, int BufferId, StringRef Ext,
+ const char *Buffer, size_t Size) {
+ std::string Filename =
+ formatv("{0}_{1}_{2}.{3}", Base.str(), Label.str(), BufferId, Ext.str());
+ std::error_code EC;
+ raw_fd_ostream FS(Filename, EC, llvm::sys::fs::OF_None);
+ if (EC) {
+ std::cout << "Error saving " << Label.str() << " image : " << EC.message();
+ return 1;
+ }
+ FS.write(Buffer, Size);
+ FS.close();
+ std::cout << "Saved " << Filename << "\n";
+ return 0;
+}
+
+Error processIntelBinary(const OffloadEnvTy &OffloadEnv, const BinEnvTy &BinEnv,
+ size_t FileId, const object::OffloadBinary &Binary) {
+ StringRef Image = Binary.getImage();
+ const char *Data = Image.data();
+ size_t Size = Image.size();
+
+ std::cout << "Processing SPIR-V binary #" << FileId
+ << " for target " << Binary.getTriple().str() << "/"
+ << Binary.getArch().str() << ".\n";
+
+ /* TODO: extract spv files from Binary*/
+
+ dumpBuffer(BinEnv.Name, "spirv", FileId, "spv", Data, Size);
+ return Error::success();
+}
+
+Error processOffloadBinary(const OffloadEnvTy &OffloadEnv, const BinEnvTy &BinEnv,
+ size_t FileId, const object::OffloadBinary &Binary) {
+ StringRef Image = Binary.getImage();
+ const char *Data = Image.data();
+ size_t Size = Image.size();
+
+ std::cout << "Processing offloading binary #" << FileId << " with image kind "
+ << Binary.getImageKind() << " and offload kind "
+ << Binary.getOffloadKind() << " for target "
+ << Binary.getTriple().str() << "/" << Binary.getArch().str() << ".\n"
+ << ".\n";
+
+ dumpBuffer(BinEnv.Name, "image", FileId, "bin", Data, Size);
+
+ if (Binary.getTriple() == "spirv64-intel")
+ if (auto Err = processIntelBinary(OffloadEnv, BinEnv, FileId, Binary))
+ return Err;
+
+ for (auto &D : OffloadEnv.FoundDevices) {
+ bool isValid = false;
+ OFFLOAD_ERR(olIsValidBinary(D, Data, Size, &isValid));
+ if (!isValid) {
+ continue;
+ }
+
+ ol_program_handle_t Program;
+ OFFLOAD_ERR(olCreateProgram(D, Data, Size, &Program));
+
+ const char *ImageData;
+ size_t ImageSize;
+ OFFLOAD_ERR(olGetProgramDeviceImage(Program, &ImageData, &ImageSize));
+ dumpBuffer(BinEnv.Name, "device", FileId, "bin", ImageData, ImageSize);
+ OFFLOAD_ERR(olDestroyProgram(Program));
+ return Error::success();
+ }
+ std::cout << "No compatible devices found for the provided binary.\n";
+ return Error::success();
+}
+
+Error processBinary(const OffloadEnvTy &OffloadEnv, const BinEnvTy &BinEnv) {
+ llvm::SmallVector<object::OffloadFile> Files;
+ if (auto Err = extractOffloadBinaries(BinEnv.Data, Files)) {
+ return Err;
+ }
+
+ std::cout << "Found " << Files.size()
+ << " offloading binary(ies) in the file.\n";
+
+ for (size_t FileId = 0; FileId < Files.size(); ++FileId) {
+ const auto &OffloadFile = Files[FileId];
+ if (auto Err = processOffloadBinary(OffloadEnv, BinEnv, FileId,
+ *OffloadFile.getBinary()))
+ return Err;
+ }
+
+ return Error::success();
+}
+
+int main(int argc, char **argv) {
+ cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<binary>"),
+ cl::Required);
+
+ cl::ParseCommandLineOptions(argc, argv, "llvm-offload-bintool\n");
+ auto BinOrErr = MemoryBuffer::getFile(InputFilename, /*isText=*/false,
+ /*RequiresNullTerminator=*/false);
+ if (!BinOrErr) {
+ llvm::errs() << "Error reading the binary file: "
+ << BinOrErr.getError().message() << "\n";
+ return 1;
+ }
+
+ OffloadEnvTy OffloadEnv;
+ BinEnvTy BinEnv(llvm::sys::path::filename(InputFilename).str(),
+ BinOrErr.get()->getMemBufferRef());
+
+ if (auto Err = init(OffloadEnv)) {
+ llvm::errs() << "Error initializing liboffload: "
+ << toString(std::move(Err)) << "\n";
+ return 1;
+ }
+
+ if (auto Err = processBinary(OffloadEnv, BinEnv)) {
+ llvm::errs() << "Error processing the binary: " << toString(std::move(Err))
+ << "\n";
+ return 1;
+ }
+
+ if (auto Err = deinit()) {
+ llvm::errs() << "Error shutting down liboffload: "
+ << toString(std::move(Err)) << "\n";
+ return 1;
+ }
+
+ return 0;
+}
More information about the llvm-commits
mailing list