-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathbase-execution-env.ts
344 lines (297 loc) · 13.4 KB
/
base-execution-env.ts
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright (c) 2024, Compiler Explorer Authors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import os from 'os';
import path from 'path';
import fs from 'fs-extra';
import temp from 'temp';
import {BuildResult, ExecutionOptions, ExecutionParams} from '../../types/compilation/compilation.interfaces.js';
import {
BasicExecutionResult,
ConfiguredRuntimeTool,
ConfiguredRuntimeTools,
ExecutableExecutionOptions,
RuntimeToolType,
UnprocessedExecResult,
} from '../../types/execution/execution.interfaces.js';
import {addHeaptrackResults} from '../artifact-utils.js';
import {assert, unwrap} from '../assert.js';
import {CompilationEnvironment} from '../compilation-env.js';
import * as exec from '../exec.js';
import {logger} from '../logger.js';
import {Packager} from '../packager.js';
import {propsFor} from '../properties.js';
import {HeaptrackWrapper} from '../runtime-tools/heaptrack-wrapper.js';
import * as utils from '../utils.js';
import {ExecutablePackageCacheMiss, IExecutionEnvironment} from './execution-env.interfaces.js';
export class LocalExecutionEnvironment implements IExecutionEnvironment {
protected packager: Packager;
protected dirPath: string;
protected buildResult: BuildResult | undefined;
protected environment: CompilationEnvironment;
protected timeoutMs: number;
protected sandboxType: string;
protected useSanitizerEnvHints: boolean;
protected maxExecOutputSize: number;
static get key() {
return 'local';
}
constructor(environment: CompilationEnvironment) {
this.environment = environment;
this.timeoutMs = this.environment.ceProps('binaryExecTimeoutMs', 2000);
this.maxExecOutputSize = this.environment.ceProps('max-executable-output-size', 32 * 1024);
this.useSanitizerEnvHints = true;
const execProps = propsFor('execution');
this.sandboxType = execProps('sandboxType', 'none');
this.packager = new Packager();
this.dirPath = 'not initialized';
}
protected async executableGet(hash: string, destinationFolder: string) {
const result = await this.environment.executableCache.get(hash);
if (!result.hit) return null;
const filepath = destinationFolder + '/' + hash;
await fs.writeFile(filepath, unwrap(result.data));
return filepath;
}
protected async loadPackageWithExecutable(hash: string, dirPath: string): Promise<BuildResult> {
const compilationResultFilename = 'compilation-result.json';
const startTime = process.hrtime.bigint();
const outputFilename = await this.executableGet(hash, dirPath);
if (outputFilename) {
logger.debug(`Using cached package ${outputFilename}`);
await this.packager.unpack(outputFilename, dirPath);
const buildResultsBuf = await fs.readFile(path.join(dirPath, compilationResultFilename));
const buildResults = JSON.parse(buildResultsBuf.toString('utf8'));
// logger.info(hash + ' => ' + JSON.stringify(buildResults));
const endTime = process.hrtime.bigint();
let inputFilename = '';
if (buildResults.inputFilename) {
inputFilename = path.join(dirPath, path.basename(buildResults.inputFilename));
}
let executableFilename = '';
if (buildResults.executableFilename) {
const execPath = utils.maskRootdir(buildResults.executableFilename);
executableFilename = path.join(dirPath, execPath);
}
return Object.assign({}, buildResults, {
code: 0,
inputFilename: inputFilename,
dirPath: dirPath,
executableFilename: executableFilename,
packageDownloadAndUnzipTime: ((endTime - startTime) / BigInt(1000000)).toString(),
});
} else {
throw new ExecutablePackageCacheMiss('Tried to get executable from cache, but got a cache miss');
}
}
async downloadExecutablePackage(hash: string): Promise<void> {
this.dirPath = await temp.mkdir({prefix: utils.ce_temp_prefix, dir: os.tmpdir()});
this.buildResult = await this.loadPackageWithExecutable(hash, this.dirPath);
}
protected getDefaultExecOptions(params: ExecutionParams): ExecutionOptions & {env: Record<string, string>} {
const env: Record<string, string> = {};
env.PATH = '';
if (params.runtimeTools) {
const runtimeEnv = params.runtimeTools.find(tool => tool.name === RuntimeToolType.env);
if (runtimeEnv) {
for (const opt of runtimeEnv.options) {
env[(opt.name = opt.value)];
}
}
}
// todo: what to do about the rest of the runtimeTools?
if (
this.buildResult &&
this.buildResult.defaultExecOptions &&
this.buildResult.defaultExecOptions.env &&
this.buildResult.defaultExecOptions.env.PATH
) {
if (env.PATH.length > 0)
env.PATH = env.PATH + path.delimiter + this.buildResult.defaultExecOptions.env.PATH;
else env.PATH = this.buildResult.defaultExecOptions.env.PATH;
}
const execOptions: ExecutionOptions & {env: Record<string, string>} = {
env,
};
if (this.buildResult && this.buildResult.preparedLdPaths) {
execOptions.ldPath = this.buildResult.preparedLdPaths;
}
return execOptions;
}
async execute(params: ExecutionParams): Promise<BasicExecutionResult> {
assert(this.buildResult);
const execExecutableOptions: ExecutableExecutionOptions = {
args: typeof params.args === 'string' ? utils.splitArguments(params.args) : params.args || [],
stdin: params.stdin || '',
ldPath: this.buildResult.preparedLdPaths || [],
env: {},
runtimeTools: params.runtimeTools,
};
const homeDir = await temp.mkdir({prefix: utils.ce_temp_prefix, dir: os.tmpdir()});
return await this.execBinary(this.buildResult.executableFilename, execExecutableOptions, homeDir);
}
protected setEnvironmentVariablesFromRuntime(
configuredTools: ConfiguredRuntimeTools,
execOptions: ExecutionOptions,
) {
for (const runtime of configuredTools) {
if (runtime.name === RuntimeToolType.env) {
for (const env of runtime.options) {
if (!execOptions.env) execOptions.env = {};
execOptions.env[env.name] = env.value;
}
}
}
}
async execBinary(
executable: string,
executeParameters: ExecutableExecutionOptions,
homeDir: string,
extraConfiguration?: any,
): Promise<BasicExecutionResult> {
try {
const execOptions: ExecutionOptions = {
maxOutput: this.maxExecOutputSize,
timeoutMs: this.timeoutMs,
ldPath: [...executeParameters.ldPath],
input: executeParameters.stdin,
customCwd: homeDir,
appHome: homeDir,
};
if (this.useSanitizerEnvHints) {
execOptions.env = {
ASAN_OPTIONS: 'color=always',
UBSAN_OPTIONS: 'color=always',
MSAN_OPTIONS: 'color=always',
LSAN_OPTIONS: 'color=always',
...executeParameters.env,
};
} else {
execOptions.env = {
...executeParameters.env,
};
}
return this.execBinaryMaybeWrapped(
executable,
executeParameters.args,
execOptions,
executeParameters,
homeDir,
);
} catch (err: UnprocessedExecResult | any) {
if (err.code && err.stderr) {
return utils.processExecutionResult(err);
} else {
return {
...utils.getEmptyExecutionResult(),
stdout: err.stdout ? utils.parseOutput(err.stdout) : [],
stderr: err.stderr ? utils.parseOutput(err.stderr) : [],
code: err.code === undefined ? -1 : err.code,
};
}
}
}
protected async execBinaryMaybeWrapped(
executable: string,
args: string[],
execOptions: ExecutionOptions,
executeParameters: ExecutableExecutionOptions,
homeDir: string,
): Promise<BasicExecutionResult> {
let runWithHeaptrack: ConfiguredRuntimeTool | undefined = undefined;
let runWithLibSegFault: ConfiguredRuntimeTool | undefined = undefined;
const lineParseOptions: Set<utils.LineParseOption> = new Set<utils.LineParseOption>();
if (!execOptions.env) execOptions.env = {};
if (executeParameters.runtimeTools) {
this.setEnvironmentVariablesFromRuntime(executeParameters.runtimeTools, execOptions);
for (const runtime of executeParameters.runtimeTools) {
if (runtime.name === RuntimeToolType.heaptrack) {
runWithHeaptrack = runtime;
} else if (runtime.name === RuntimeToolType.libsegfault) {
runWithLibSegFault = runtime;
}
}
}
if (runWithLibSegFault) {
lineParseOptions.add(utils.LineParseOption.AtFileLine);
const libSegFaultPath = this.environment.ceProps('libSegFaultPath', '/usr/lib');
const preloadSo = path.join(libSegFaultPath, 'libSegFault.so');
const tracer = path.join(libSegFaultPath, 'tracer');
if (execOptions.env.LD_PRELOAD) {
execOptions.env.LD_PRELOAD = preloadSo + ':' + execOptions.env.LD_PRELOAD;
} else {
execOptions.env.LD_PRELOAD = preloadSo;
}
execOptions.env.LIBSEGFAULT_TRACER = tracer;
for (const opt of runWithLibSegFault.options) {
if (opt.name === 'registers' && opt.value === 'yes') {
execOptions.env.LIBSEGFAULT_REGISTERS = '1';
} else if (opt.name === 'memory' && opt.value === 'yes') {
execOptions.env.LIBSEGFAULT_MEMORY = '1';
}
}
}
if (runWithHeaptrack && HeaptrackWrapper.isSupported(this.environment)) {
lineParseOptions.add(utils.LineParseOption.AtFileLine);
const wrapper = new HeaptrackWrapper(
homeDir,
exec.sandbox,
exec.execute,
runWithHeaptrack.options,
this.environment.ceProps,
this.sandboxType,
);
const execResult: UnprocessedExecResult = await wrapper.exec(executable, args, execOptions);
const processed = this.processUserExecutableExecutionResult(
execResult,
Array.from(lineParseOptions.values()),
);
if (executeParameters.runtimeTools) {
for (const runtime of executeParameters.runtimeTools) {
if (runtime.name === RuntimeToolType.heaptrack) {
await addHeaptrackResults(processed, homeDir);
}
}
}
return processed;
} else {
const execResult: UnprocessedExecResult = await exec.sandbox(executable, args, execOptions);
return this.processUserExecutableExecutionResult(execResult, Array.from(lineParseOptions.values()));
}
}
processUserExecutableExecutionResult(
input: UnprocessedExecResult,
stdErrlineParseOptions: utils.LineParseOptions,
): BasicExecutionResult {
const start = performance.now();
const stdout = utils.parseOutput(input.stdout, undefined, undefined, []);
const stderr = utils.parseOutput(input.stderr, undefined, undefined, stdErrlineParseOptions);
const end = performance.now();
return {
...input,
stdout,
stderr,
processExecutionResultTime: end - start,
};
}
}