-
Notifications
You must be signed in to change notification settings - Fork 272
/
php-asyncify.spec.ts
238 lines (225 loc) · 6.86 KB
/
php-asyncify.spec.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
import http from 'http';
import fs from 'fs';
import path from 'path';
import { NodePHP } from '..';
import { SupportedPHPVersions } from '@php-wasm/universal';
import { phpVars } from '@php-wasm/util';
// eslint-disable-next-line @nrwl/nx/enforce-module-boundaries
import InitialDockerfile from '../../../compile/Dockerfile?raw';
// Start a server to test network functions
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
});
const host = '127.0.0.1';
const port = await new Promise((resolve) => {
server.listen(0, function () {
resolve((server.address() as any).port);
});
});
const httpUrl = `http://${host}:${port}`;
const js = phpVars({
host,
port,
httpUrl,
});
const phpVersions =
'PHP' in process.env ? [process.env['PHP']] : SupportedPHPVersions;
describe.each(phpVersions)('PHP %s – asyncify', (phpVersion) => {
const topOfTheStack: Array<string> = [
// http:// stream handler
`file_get_contents(${js['httpUrl']});`,
`$fp = fopen(${js['httpUrl']}, "r");
fread($fp, 1024);
fclose($fp);`,
// `getimgsize(${js['httpUrl']});`,
// Network functions from https://www.php.net/manual/en/book.network.php
`$fp = fsockopen(${js['host']}, ${js['port']});
fwrite($fp, "GET / HTTP/1.1\\r\\n\\r\\n");
fread($fp, 10);
fclose($fp);`,
`gethostbyname(${js['httpUrl']});`,
// @TODO:
// https:// stream handler
// MySQL functions from https://www.php.net/manual/en/book.mysql.php
// PDO functions from https://www.php.net/manual/en/book.pdo.php
// Sockets functions from https://www.php.net/manual/en/book.sockets.php
];
let php: NodePHP;
beforeEach(async () => {
php = await NodePHP.load(phpVersion as any);
php.setPhpIniEntry('allow_url_fopen', '1');
});
describe.each(topOfTheStack)('%s', (networkCall) => {
test('Direct call', () => assertNoCrash(` ${networkCall}`));
describe('Function calls', () => {
test('Simple call', () =>
assertNoCrash(`function top() { ${networkCall} } top();`));
test('Via call_user_func', () =>
assertNoCrash(
`function top() { ${networkCall} } call_user_func('top'); `
));
test('Via call_user_func_array', () =>
assertNoCrash(
`function top() { ${networkCall} } call_user_func_array('top', array());`
));
});
describe('Class method calls', () => {
test('Regular method', () =>
assertNoCrash(`
class Top {
function my_method() { ${networkCall} }
}
$x = new Top();
$x->my_method();
`));
test('Via ReflectionMethod->invoke()', () =>
assertNoCrash(`
class Top {
function my_method() { ${networkCall} }
}
$reflectionMethod = new ReflectionMethod('Top', 'my_method');
$reflectionMethod->invoke(new Top());
`));
test('Via ReflectionMethod->invokeArgs()', () =>
assertNoCrash(`
class Top {
function my_method() { ${networkCall} }
}
$reflectionMethod = new ReflectionMethod('Top', 'my_method');
$reflectionMethod->invokeArgs(new Top(), array());
`));
test('Via call_user_func', () =>
assertNoCrash(`
class Top {
function my_method() { ${networkCall} }
}
call_user_func([new Top(), 'my_method']);
`));
test('Via call_user_func_array', () =>
assertNoCrash(`
class Top {
function my_method() { ${networkCall} }
}
call_user_func_array([new Top(), 'my_method'], []);
`));
test('Constructor', () =>
assertNoCrash(`
class Top {
function __construct() { ${networkCall} }
}
new Top();
`));
test('Destructor', () =>
assertNoCrash(`
class Top {
function __destruct() { ${networkCall} }
}
$x = new Top();
unset($x);
`));
test('__call', () =>
assertNoCrash(`
class Top {
function __call($method, $args) { ${networkCall} }
}
$x = new Top();
$x->test();
`));
test('__get', () =>
assertNoCrash(`
class Top {
function __get($prop) { ${networkCall} }
}
$x = new Top();
$x->test;
`));
test('__set', () =>
assertNoCrash(`
class Top {
function __set($prop, $value) { ${networkCall} }
}
$x = new Top();
$x->test = 1;
`));
test('__isset', () =>
assertNoCrash(`
class Top {
function __isset($prop) { ${networkCall} }
}
$x = new Top();
isset($x->test);
`));
test('offsetSet', () =>
assertNoCrash(`
class Top implements ArrayAccess {
function offsetExists($offset) { ${networkCall} }
function offsetGet($offset) { ${networkCall} }
function offsetSet($offset, $value) { ${networkCall} }
function offsetUnset($offset) { ${networkCall} }
}
$x = new Top();
isset($x['test']);
$a = $x['test'];
$x['test'] = 123;
unset($x['test']);
`));
});
});
async function assertNoCrash(code: string) {
try {
const result = await php.run({
code: `<?php ${code}`,
});
expect(result).toBeTruthy();
expect(result.text).toBe('');
expect(result.errors).toBeFalsy();
} catch (e) {
if (
'FIX_DOCKERFILE' in process.env &&
process.env['FIX_DOCKERFILE'] === 'true' &&
'functionsMaybeMissingFromAsyncify' in php
) {
const missingCandidates = (
php.functionsMaybeMissingFromAsyncify as string[]
)
.map((candidate) =>
candidate.replace('byn$fpcast-emu$', '')
)
.filter(
(candidate) => !Dockerfile.includes(`"${candidate}"`)
);
if (missingCandidates.length) {
addAsyncifyFunctionsToDockerfile(missingCandidates);
throw new Error(
`Asyncify crash! The following missing functions were just auto-added to the ASYNCIFY_ONLY list in the Dockerfile: \n ` +
missingCandidates.join(', ') +
`\nYou now need to rebuild PHP and re-run this test: \n` +
` npm run recompile:php:node:8.0\n` +
` node --stack-trace-limit=100 ./node_modules/.bin/nx test php-wasm-node --test-name-pattern='asyncify'\n`
);
}
const err = new Error(
`Asyncify crash! No C functions present in the stack trace were missing ` +
`from the Dockerfile. This could mean the stack trace is too short – try increasing the stack trace limit ` +
`with --stack-trace-limit=100. If you already did that, fixing this problem will likely take more digging.`
);
err.cause = e;
throw err;
}
}
}
});
let Dockerfile = InitialDockerfile;
const DockerfilePath = path.resolve(__dirname, '../../../compile/Dockerfile');
function addAsyncifyFunctionsToDockerfile(functions: string[]) {
const currentDockerfile = fs.readFileSync(DockerfilePath, 'utf8') + '';
const lookup = `export ASYNCIFY_ONLY=$'`;
const idx = currentDockerfile.indexOf(lookup) + lookup.length;
const updatedDockerfile =
currentDockerfile.substring(0, idx) +
functions.map((f) => `"${f}",\\\n`).join('') +
currentDockerfile.substring(idx);
fs.writeFileSync(DockerfilePath, updatedDockerfile);
Dockerfile = updatedDockerfile;
}