Skip to content

Commit

Permalink
utils: add check_binary_linkage function
Browse files Browse the repository at this point in the history
  • Loading branch information
alebcay committed Jan 20, 2025
1 parent 637fd5b commit 796dc51
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
52 changes: 52 additions & 0 deletions Library/Homebrew/test/utils/linkage_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# frozen_string_literal: true

require "utils/linkage"

RSpec.describe Utils do
suffix = OS.mac? ? ".dylib" : ".so"

describe "::binary_linked_to_library?", :integration_test do
before do
install_test_formula "testball-linkage", <<~RUBY
def install
(buildpath/"foo.h").write "void foo();"
(buildpath/"foo.c").write <<~C
#include <stdio.h>
#include "foo.h"
void foo() { printf("foo\\\\n"); }
C
(buildpath/"bar.c").write <<~C
#include <stdio.h>
void bar() { printf("bar\\\\n"); }
C
(buildpath/"test.c").write <<~C
#include "foo.h"
int main() { foo(); return 0; }
C
system ENV.cc, "-c", "-fpic", "foo.c"
system ENV.cc, "-c", "-fpic", "bar.c"
dll_flag = OS.mac? ? "-dynamiclib" : "-shared"
system ENV.cc, dll_flag, "-o", shared_library("libbrewfoo"), "foo.o"
system ENV.cc, dll_flag, "-o", shared_library("libbrewbar"), "bar.o"
lib.install shared_library("libbrewfoo"), shared_library("libbrewbar")
system ENV.cc, "-o", "brewtest", "test.c", "-L\#{lib}", "-lbrewfoo"
bin.install "brewtest"
end
RUBY
end

it "returns true if the binary is linked to the library" do
f = Formula["testball-linkage"]
result = described_class.binary_linked_to_library?(f.bin/"brewtest",
f.lib/"libbrewfoo#{suffix}", HOMEBREW_CELLAR)
expect(result).to be true
end

it "returns false if the binary is not linked to the library" do
f = Formula["testball-linkage"]
result = described_class.binary_linked_to_library?(f.bin/"brewtest",
f.lib/"libbrewbar#{suffix}", HOMEBREW_CELLAR)
expect(result).to be false
end
end
end
16 changes: 16 additions & 0 deletions Library/Homebrew/utils/linkage.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# typed: strict
# frozen_string_literal: true

module Utils
sig {
params(binary: T.any(String, Pathname), library: T.any(String, Pathname),
prefix: T.any(String, Pathname)).returns(T::Boolean)
}
def self.binary_linked_to_library?(binary, library, prefix = HOMEBREW_PREFIX)
Pathname.new(binary).dynamically_linked_libraries.any? do |dll|
next false unless dll.start_with?(prefix.to_s)

File.realpath(dll) == File.realpath(Pathname.new(library))
end
end
end

0 comments on commit 796dc51

Please sign in to comment.