forked from ilammy/setup-nasm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
258 lines (232 loc) · 9.68 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
const core = require('@actions/core')
const AdmZip = require('adm-zip')
const spawn = require('child_process').spawnSync
const fs = require('fs')
const fetch = require('node-fetch')
const path = require('path')
const process = require('process')
const stream = require('stream')
const tar = require('tar-fs')
const URL = require('url').URL
const util = require('util')
const zlib = require("zlib")
// This could have been a ten-line shell script, but no, we are full-stack async now...
// Though, it does look pretty in the Web console.
// These are platform names as expected by NASM build archive
function selectPlatform(platform) {
if (platform) { return platform }
if (process.platform == 'linux') { return 'linux' }
if (process.platform == 'darwin') { return 'macosx' }
if (process.platform == 'win32') { return 'win64' }
throw new Error(`unsupported platform: '${process.platform}'`)
}
async function main() {
const version = core.getInput('version', {required: true})
const destination = core.getInput('destination') || 'nasm'
const from_source = core.getInput('from-source')
// Yeah, these are strings... JavaScript at its finest
var try_binary = (from_source != 'true')
var try_source = (from_source != 'false')
const platform = selectPlatform(core.getInput('platform'))
const homedir = require('os').homedir()
const absNasmDir = path.resolve(homedir, destination)
const nasm = (process.platform == 'win32' ? 'nasm.exe' : 'nasm')
const ndisasm = (process.platform == 'win32' ? 'ndisasm.exe' : 'ndisasm')
const absNasmFile = path.join(absNasmDir, nasm)
const absNdisasmFile = path.join(absNasmDir, ndisasm)
if (!fs.existsSync(absNasmDir)) {
fs.mkdirSync(absNasmDir, {recursive: true})
}
// NASM publishes borked macOS binaries for older releases. Modern macOS
// does not support 32-bit binaries and for some reason throws "Bad CPU type"
// errors if a binary contain 32-bit code slice. Build old versions from source.
if (platform == 'macosx') {
let match = version.match(/^(\d+)\.(\d+)/)
let major = parseInt(match[1])
let minor = parseInt(match[2])
if (major < 2 || (major == 2 && minor < 14)) {
core.info(`Requested NASM version ${version} has incompatible prebuilt binaries.`)
core.info(`Only source builds are supported on macOS.`)
if (try_source) {
core.info(`Will try building from source.`)
try_binary = false
} else {
core.warning(`Trying binary build at your own risk.`)
}
}
}
async function downloadBinary() {
const urls = [
new URL(`https://github.com/ilammy/setup-nasm/raw/mirror/releasebuilds/${version}/${platform}/nasm-${version}-${platform}.zip`),
new URL(`https://www.nasm.us/pub/nasm/releasebuilds/${version}/${platform}/nasm-${version}-${platform}.zip`),
]
const buffer = await fetchFirstBuffer(urls)
const zip = new AdmZip(buffer)
// Pull out the one binary we're interested in from the downloaded archive,
// overwrite anything that's there, and make sure the file is executable.
const nasmEntry = `nasm-${version}/${nasm}`
zip.extractEntryTo(nasmEntry, absNasmDir, false, true)
if (!fs.existsSync(absNasmFile)) {
core.debug(`nasm executable missing: ${absNasmFile}`)
throw new Error(`failed to extract to '${absNasmDir}'`)
}
fs.chmodSync(absNasmFile, '755')
const ndisasmEntry = `nasm-${version}/${ndisasm}`
zip.extractEntryTo(ndisasmEntry, absNasmDir, false, true)
if (!fs.existsSync(absNdisasmFile)) {
core.debug(`ndisasm executable missing: ${absNdisasmFile}`)
throw new Error(`failed to extract to '${absNasmDir}'`)
}
fs.chmodSync(absNdisasmFile, '755')
core.debug(`extracted NASM to '${absNasmDir}'`)
}
async function buildFromSource() {
const urls = [
new URL(`https://github.com/ilammy/setup-nasm/raw/mirror/releasebuilds/${version}/nasm-${version}.tar.gz`),
new URL(`https://www.nasm.us/pub/nasm/releasebuilds/${version}/nasm-${version}.tar.gz`),
]
const buffer = await fetchFirstBuffer(urls)
await extractTGZ(buffer, absNasmDir)
// The tarball has all content in a versioned subdirectory: "nasm-2.16.01".
const sourceDir = path.join(absNasmDir, `nasm-${version}`)
core.debug(`extracted NASM to '${sourceDir}'`)
// NASM uses the usual "./configure && make", but make sure we extracted
// everything correctly before jumping in.
const configurePath = path.join(sourceDir, 'configure')
if (!fs.existsSync(configurePath)) {
core.debug(`configure script missing: ${configurePath}`)
throw new Error(`failed to extract to '${sourceDir}'`)
}
// Now we can run "./configure". Node.js does not allow to change current
// working directory for the current process, so we use absolute paths.
execute([configurePath], {cwd: sourceDir})
// Now comes the fun part! Somehow, despite smoking Autocrack, NASM manages
// to botch up platform detection. Or that's Apple thinking different again,
// I don't know. Whatever it is, here are magic patches to make things work.
if (platform == 'linux' || platform == 'macosx') {
if (version.match(/2.14/)) {
appendFile(path.join(sourceDir, 'include/compiler.h'), [
'#include <time.h>'
])
}
}
if (platform == 'macosx') {
if (version.match(/2.14/)) {
appendFile(path.join(sourceDir, 'config/config.h'), [
'#define HAVE_SNPRINTF 1',
'#define HAVE_VSNPRINTF 1',
'#define HAVE_INTTYPES_H 1'
])
}
if (version.match(/2.13/)) {
appendFile(path.join(sourceDir, 'config/config.h'), [
'#define HAVE_STRLCPY 1',
'#define HAVE_DECL_STRLCPY 1',
'#define HAVE_SNPRINTF 1',
'#define HAVE_VSNPRINTF 1',
'#define HAVE_INTTYPES_H 1'
])
}
if (version.match(/2.12/)) {
appendFile(path.join(sourceDir, 'config.h'), [
'#define HAVE_STRLCPY 1',
'#define HAVE_DECL_STRLCPY 1',
'#define HAVE_SNPRINTF 1',
'#define HAVE_VSNPRINTF 1'
])
}
}
// Finally, build the damn binary.
execute(['make', 'nasm', 'ndisasm'], {cwd: sourceDir})
core.debug(`compiled NASM in '${sourceDir}'`)
// The binary is expected at a slightly different place...
fs.renameSync(path.join(sourceDir, nasm), absNasmFile)
fs.renameSync(path.join(sourceDir, ndisasm), absNdisasmFile)
}
var made_it = false
if (try_binary && !made_it) {
try {
core.info('Downloading binary distribution...')
await downloadBinary()
made_it = true
}
catch (error) {
core.info(`binaries did not work: ${error}`)
}
}
if (try_source && !made_it) {
try {
core.info('Downloading source code...')
await buildFromSource()
made_it = true
}
catch (error) {
core.warning(`source code did not work: ${error}`)
}
}
if (!made_it) {
throw new Error("I'm sorry, Dave. I'm afraid I can't do that.")
}
execute([absNasmFile, '-version'])
execute([absNdisasmFile, '-version'])
core.addPath(absNasmDir)
}
function execute(cmdline, extra_options) {
core.startGroup(`${cmdline.join(' ')}`)
const options = {stdio: 'inherit'}
Object.assign(options, extra_options)
const result = spawn(cmdline[0], cmdline.slice(1), options)
core.endGroup()
if (result.error) {
core.debug(`failed to spawn process: ${result.error}`)
throw result.error
}
if (result.status !== 0) {
const command = path.basename(cmdline[0])
const error = new Error(`${command} failed: exit code ${result.status}`)
core.debug(`${error}`)
throw error
}
return result
}
function appendFile(path, strings) {
fs.appendFileSync(path, '\n' + strings.join('\n') + '\n')
}
async function fetchFirstBuffer(urls) {
let last_error
for (const url of urls) {
try {
return await fetchBuffer(url)
}
catch (error) {
last_error = error
}
}
throw last_error
}
async function fetchBuffer(url) {
core.debug(`downloading ${url}...`)
const result = await fetch(url, {compress: false})
if (!result.ok) {
const error = new Error(`HTTP GET failed: ${result.statusText}`)
core.debug(`failed to fetch URL: ${error}`)
throw error
}
const buffer = await result.buffer()
core.debug(`fetched ${buffer.length} bytes`)
return buffer
}
async function extractTGZ(buffer, directory) {
core.info('Extracting source code...')
// Yes, I love async programming very much. So straightforward!
const gunzip = util.promisify(zlib.gunzip)
async function * data() {
yield await gunzip(buffer)
}
const tarball = stream.Readable.from(data())
.pipe(tar.extract(directory))
// Stream promise API is not available on GitHub Actions. Drain manually.
const finished = util.promisify(stream.finished)
return finished(tarball)
}
main().catch((e) => core.setFailed(`could not install NASM: ${e}`))