Skip to content

Commit cb879b2

Browse files
committed
add is_executable_binary()
1 parent 7e29dc5 commit cb879b2

File tree

3 files changed

+71
-5
lines changed

3 files changed

+71
-5
lines changed

+stdlib/is_executable_binary.m

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
function y = is_executable_binary(filename)
2+
% IS_EXECUTABLE_BINARY Check if a file is an executable binary by examining magic numbers
3+
%
4+
% NOTE: on Unix-like operating systems, often times what users run thinking
5+
% it's a "program" is actually a shell script invoking a binary with
6+
% options.
7+
% fullfile(matlabroot, 'bin/matlab')
8+
% is a shell script and thus is FALSE for this function.
9+
10+
y = false;
11+
12+
fid = fopen(filename, 'rb');
13+
if fid < 0, return, end
14+
15+
N = 4;
16+
if ispc(), N = 2; end
17+
18+
magic = fread(fid, N, 'uint8').';
19+
fclose(fid);
20+
if numel(magic) < N, return, end
21+
22+
if ispc()
23+
y = isequal(magic(1:2), [0x4d, 0x5a]);
24+
% Check for PE magic number (MZ)
25+
elseif ismac()
26+
% Check for Mach-O magic number
27+
feedface = [0xFE, 0xED, 0xFA, 0xCE];
28+
feedfacf = [0xFE, 0xED, 0xFA, 0xCF];
29+
cafebabe = [0xCA, 0xFE, 0xBA, 0xBE];
30+
cafebabf = [0xCA, 0xFE, 0xBA, 0xBF];
31+
for a = {feedface, fliplr(feedface), ...
32+
feedfacf, fliplr(feedfacf), ...
33+
cafebabe, fliplr(cafebabe), ...
34+
cafebabf, fliplr(cafebabf)}
35+
36+
y = isequal(magic, a{1});
37+
if y, return, end
38+
end
39+
else
40+
% Check for ELF magic number (0x7f followed by 'ELF')
41+
y = isequal(magic, [0x7f, 0x45, 0x4c, 0x46]);
42+
end
43+
44+
end

test/TestFileImpure.m

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ function test_file_size(tc, p_file_size)
2424

2525

2626
function test_null_file(tc)
27-
import matlab.unittest.constraints.IsFile
2827
tc.assumeFalse(ispc)
29-
tc.verifyThat(stdlib.null_file, IsFile)
28+
29+
tc.verifyThat(stdlib.null_file, matlab.unittest.constraints.IsFile)
3030
end
3131

3232

test/TestIsExe.m

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,35 @@ function test_is_exe_dir(tc, fun)
3131
function test_matlab_exe(tc, fun)
3232
is_capable(tc, fun)
3333

34-
f = fullfile(matlabroot, "bin/matlab");
34+
35+
f = matlab_path();
36+
tc.verifyTrue(fun(f))
37+
end
38+
39+
40+
function test_is_executable_binary(tc)
41+
3542
if ispc()
36-
f = f + ".exe";
43+
f = matlab_path();
44+
else
45+
f = '/bin/ls';
3746
end
3847

39-
tc.verifyTrue(fun(f))
48+
tc.assumeThat(f, matlab.unittest.constraints.IsFile)
49+
50+
b = stdlib.is_executable_binary(f);
51+
tc.assumeTrue(b, f)
52+
53+
end
4054
end
4155

4256
end
57+
58+
59+
function f = matlab_path()
60+
61+
f = fullfile(matlabroot, "bin/matlab");
62+
if ispc()
63+
f = f + ".exe";
4364
end
65+
end

0 commit comments

Comments
 (0)