Debian Codegraph @

inst/make-r-def.R

raw
1 # [description]
2 # Create a definition file (.def) from a .dll file, using objdump. This
3 # is used by FindLibR.cmake when building the R package with MSVC.
4 #
5 # [usage]
6 #
7 # Rscript make-r-def.R something.dll something.def
8 #
9 # [references]
10 # * https://www.cs.colorado.edu/~main/cs1300/doc/mingwfaq.html
11
12 args <- commandArgs(trailingOnly = TRUE)
13
14 IN_DLL_FILE <- args[[1L]]
15 OUT_DEF_FILE <- args[[2L]]
16 DLL_BASE_NAME <- basename(IN_DLL_FILE)
17
18 message(sprintf("Creating '%s' from '%s'", OUT_DEF_FILE, IN_DLL_FILE))
19
20 # system() will not raise an R exception if the process called
21 # fails. Wrapping it here to get that behavior.
22 #
23 # system() introduces a lot of overhead, at least on Windows,
24 # so trying processx if it is available
25 .pipe_shell_command_to_stdout <- function(command, args, out_file) {
26 has_processx <- suppressMessages({
27 suppressWarnings({
28 require("processx") # nolint
29 })
30 })
31 if (has_processx) {
32 p <- processx::process$new(
33 command = command
34 , args = args
35 , stdout = out_file
36 , windows_verbatim_args = FALSE
37 )
38 invisible(p$wait())
39 } else {
40 message(paste0(
41 "Using system2() to run shell commands. Installing "
42 , "'processx' with install.packages('processx') might "
43 , "make this faster."
44 ))
45 exit_code <- system2(
46 command = command
47 , args = shQuote(args)
48 , stdout = out_file
49 )
50 if (exit_code != 0L) {
51 stop(paste0("Command failed with exit code: ", exit_code))
52 }
53 }
54 return(invisible(NULL))
55 }
56
57 # use objdump to dump all the symbols
58 OBJDUMP_FILE <- file.path(tempdir(), "objdump-out.txt")
59 .pipe_shell_command_to_stdout(
60 command = "objdump"
61 , args = c("-p", IN_DLL_FILE)
62 , out_file = OBJDUMP_FILE
63 )
64
65 objdump_results <- readLines(OBJDUMP_FILE)
66 result <- file.remove(OBJDUMP_FILE)
67
68 # Only one table in the objdump results matters for our purposes,
69 # see https://www.cs.colorado.edu/~main/cs1300/doc/mingwfaq.html
70 start_index <- which(
71 grepl(
72 pattern = "[Ordinal/Name Pointer] Table"
73 , x = objdump_results
74 , fixed = TRUE
75 )
76 )
77 empty_lines <- which(objdump_results == "")
78 end_of_table <- empty_lines[empty_lines > start_index][1L]
79
80 # Read the contents of the table
81 exported_symbols <- objdump_results[(start_index + 1L):end_of_table]
82 exported_symbols <- gsub("\t", "", exported_symbols, fixed = TRUE)
83 exported_symbols <- gsub(".*\\] ", "", exported_symbols)
84 exported_symbols <- gsub(" ", "", exported_symbols, fixed = TRUE)
85
86 # Write R.def file
87 writeLines(
88 text = c(
89 paste0("LIBRARY \"", DLL_BASE_NAME, "\"")
90 , "EXPORTS"
91 , exported_symbols
92 )
93 , con = OUT_DEF_FILE
94 , sep = "\n"
95 )
96 message(sprintf("Successfully created '%s'", OUT_DEF_FILE))