-
Notifications
You must be signed in to change notification settings - Fork 5
/
FFIMe.php
executable file
·330 lines (281 loc) · 12.1 KB
/
FFIMe.php
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
<?php
declare(strict_types=1);
namespace FFIMe;
use PHPCParser\Context;
use PHPCParser\CParser;
use PHPCParser\Node\Decl;
use PHPCParser\Node\Type;
use PHPCParser\PreProcessor\Token;
use PHPObjectSymbolResolver\Parser as ObjectParser;
class FFIMe {
const LIBC = PHP_OS_FAMILY === "Darwin" ? "/usr/lib/libSystem.B.dylib" : "/lib/x86_64-linux-gnu/libc.so.6";
const TYPES_TO_REMOVE = [
'void',
'char',
'_Bool',
'int8_t',
'uint8_t',
'int16_t',
'uint16_t',
'int32_t',
'uint32_t',
'int64_t',
'uint64_t',
'float',
'double',
];
const RECORDS_TO_REMOVE = [
'_IO_FILE_plus',
];
const VARS_TO_REMOVE = [
'_IO_2_1_stdin_',
'_IO_2_1_stdout_',
'_IO_2_1_stderr_',
'sys_errlist', // sigh to FFI
];
const FUNCTIONS_TO_REMOVE = [
];
private string $sofile;
/** @var string[] */
private array $code = [];
/** @var Decl[] contains declarations of exported symbols and typedefs */
private array $declarationAst = [];
/** @var Decl[] contains declarations of exported symbols which are not in the primary shared objects */
private array $skippedDeclarationAst = [];
/** @var Decl[] contains definitions, i.e. functions with statement bodies, non-exported variables */
private array $definitionAst = [];
/** @var string[] */
private array $numericDefines = [];
private ?array $restrictedCompiledClasses = null;
private ?array $restrictedCompiledFunctions = null;
private ?array $restrictedCompiledConstants = null;
private ?array $restrictedCompiledGlobals = null;
private Context $context;
private CParser $cparser;
/** @var string[] exported symbols */
private array $symbols;
private bool $built = false;
private bool $showWarnings = true;
const DEFAULT_SO_SEARCH_PATHS = [
'/usr/local/lib',
'/usr/lib',
];
/** @param string[] $headerSearchPaths
* @param string[] $soSearchPaths
*/
public function __construct(string $sharedObjectFile, array $headerSearchPaths = [], array $soSearchPaths = self::DEFAULT_SO_SEARCH_PATHS) {
$this->sofile = $this->findSOFile($sharedObjectFile, $soSearchPaths);
$this->context = new Context($headerSearchPaths);
$this->cparser = new CParser;
$this->symbols = array_flip(ObjectParser::parseFor($this->sofile)->getAllSymbolsRecursively());
}
public function defineInt(string $identifier, int $value): void {
$this->context->define($identifier, new Token(Token::NUMBER, (string) $value, 'php'));
}
public function defineIdentifier(string $identifier, string $value): void {
$this->context->define($identifier, new Token(Token::IDENTIFIER, $value, 'php'));
}
public function defineString(string $identifier, string $value): void {
$this->context->define($identifier, new Token(Token::LITERAL, $value, 'php'));
}
public function include(string $header): self {
if ($this->built) {
throw new \RuntimeException("Already built, cannot include twice");
}
$this->filterDeclarations($this->cparser->parse($header, $this->context)->declarations);
return $this;
}
public function showWarnings(bool $show) {
$this->showWarnings = $show;
return $this;
}
public function warning(string $message) {
if ($this->showWarnings) {
echo "[Warning] $message\n";
}
}
/** @param string class to code map */
public function getCode(): array {
return $this->code;
}
public function codeGen(string $className, string $filename): void {
$code = $this->compile($className);
file_put_contents($filename, '<?php ' . $code);
}
public function codeGenWithInstrumentation(string $className, string $filename): void {
$code = $this->compile($className, true);
file_put_contents($filename, '<?php ' . $code);
}
public function build(?string $className = null) {
$className = $className ?? $this->getDynamicClassName();
eval($this->compile($className));
return $className::ffi();
}
public function getDynamicClassName(): string {
$class = 'ffime\ffime_';
do {
$class .= mt_rand(0, 99);
} while (class_exists($class));
return $class;
}
public function restrictCompiledClasses(?array $classes) {
if ($classes && \is_string(current($classes))) {
$classes = array_fill_keys($classes, 1);
}
$this->restrictedCompiledClasses = $classes;
}
public function restrictCompiledConstants(?array $constants) {
if ($constants && \is_string(current($constants))) {
$constants = array_fill_keys($constants, 1);
}
$this->restrictedCompiledConstants = $constants;
}
public function restrictCompiledGlobals(?array $globals) {
if ($globals && \is_string(current($globals))) {
$globals = array_fill_keys($globals, 1);
}
$this->restrictedCompiledGlobals = $globals;
}
public function restrictCompiledFunctions(?array $functions) {
if ($functions && \is_string(current($functions))) {
$functions = array_fill_keys($functions, false);
}
$this->restrictedCompiledFunctions = $functions;
}
private function checkTypeForClasses(string $namespace, \ReflectionType $type) {
if ($type instanceof \ReflectionNamedType && str_starts_with($type->getName(), $namespace)) {
$this->restrictedCompiledClasses[substr($type->getName(), \strlen($namespace))] = 1;
} else {
foreach ($type->getTypes() as $subtype) {
$this->checkTypeForClasses($namespace, $subtype);
}
}
}
private function checkSignaturesForClasses(string $namespace, \ReflectionFunctionAbstract $func) {
if ($ret = $func->getReturnType()) {
$this->checkTypeForClasses($namespace, $ret);
}
foreach ($func->getParameters() as $parameter) {
if ($type = $parameter->getType()) {
$this->checkTypeForClasses($namespace, $type);
}
}
}
public function compile($className, $instrument = false): string {
if (isset($this->code[$className]) && !$instrument) {
return $this->code[$className];
}
$this->filterSymbolDeclarations();
$ffiClass = "{$className}FFI";
if (class_exists($ffiClass, false) && isset($ffiClass::$__visitedClasses)) {
$this->restrictCompiledClasses($ffiClass::$__visitedClasses);
$this->restrictCompiledConstants($ffiClass::$__visitedConstants);
$this->restrictCompiledFunctions($ffiClass::$__visitedFunctions);
$this->restrictCompiledGlobals($ffiClass::$__visitedGlobals);
}
$compiler = new Compiler($instrument, $this->restrictedCompiledFunctions, $this->restrictedCompiledClasses, $this->restrictedCompiledConstants, $this->restrictedCompiledGlobals);
$this->numericDefines = $this->context->getNumericDefines();
$code = $compiler->compile($this->sofile, $this->declarationAst, $this->definitionAst, $this->skippedDeclarationAst, $this->numericDefines, $className);
foreach ($compiler->warnings as $warning) {
$this->warning($warning);
}
if (!$instrument) {
$this->code[$className] = $code;
}
return $code;
}
/** @param string[] $searchPaths */
private function findSOFile(string $filename, array $searchPaths): string {
if (is_file($filename)) {
// no searching needed
return $filename;
}
// Under MacOS dyld (runtime linker) has a cache of specific objects tied to paths, which actually do not exist on disk. They have an equivalent path in the SDK, containing their exported symbol definitions
if (PHP_OS_FAMILY === 'Darwin' && str_starts_with($filename, '/usr/lib/')) {
if (is_file(str_replace(".dylib", ".tbd", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk$filename"))) {
return $filename;
}
}
foreach ($searchPaths as $path) {
$test = $path . '/' . $filename;
if (file_exists($test)) {
return $test;
}
}
throw new \LogicException('Could not find shared object file ' . $filename);
}
protected function isExternType(Type $type) {
while ($type instanceof Type\AttributedType) {
if ($type instanceof Type\ExplicitAttributedType && $type->kind === Type\ExplicitAttributedType::KIND_EXTERN) {
return true;
}
$type = $type->parent;
}
return false;
}
protected function filterSymbolDeclarations(): void {
$result = $skipped = [];
foreach ($this->declarationAst as $declaration) {
if ($declaration instanceof Decl\NamedDecl\ValueDecl\DeclaratorDecl\FunctionDecl) {
if (isset($this->symbols[$declaration->name]) || isset($this->symbols["_{$declaration->name}"])) {
$result[] = $declaration;
} else {
$skipped[] = $declaration;
$this->warning("Skipping {$declaration->name}, not found in object file");
}
} elseif ($declaration instanceof Decl\NamedDecl\ValueDecl\DeclaratorDecl\VarDecl) {
if ($this->isExternType($declaration->type)) {
if (isset($this->symbols[$declaration->name]) || isset($this->symbols["_{$declaration->name}"])) {
$result[] = $declaration;
} else {
$skipped[] = $declaration;
$this->warning("Skipping {$declaration->name}, not found in object file");
}
} else {
array_unshift($this->definitionAst, $declaration);
}
} else {
$result[] = $declaration;
}
}
$this->declarationAst = $result;
$this->skippedDeclarationAst = $skipped;
}
/** @param Decl[] $declarations */
protected function filterDeclarations(array $declarations) {
$result = [];
foreach ($declarations as $declaration) {
if ($declaration instanceof Decl\NamedDecl\TypeDecl\TypedefNameDecl\TypedefDecl) {
if (!in_array($declaration->name, self::TYPES_TO_REMOVE)) {
$result[] = $declaration;
}
} elseif ($declaration instanceof Decl\NamedDecl\TypeDecl\TagDecl\RecordDecl) {
if (!in_array($declaration->name, self::RECORDS_TO_REMOVE)) {
$result[] = $declaration;
}
} elseif ($declaration instanceof Decl\NamedDecl\ValueDecl\DeclaratorDecl\FunctionDecl) {
if ($declaration->stmts === null) {
// only declarations, not definitions
if (!in_array($declaration->name, self::FUNCTIONS_TO_REMOVE)) {
// Skip __ functions
$result[] = $declaration;
}
} else {
if (!in_array($declaration->name, self::FUNCTIONS_TO_REMOVE)) {
// Skip __ functions
$this->definitionAst[] = $declaration;
}
}
} elseif ($declaration instanceof Decl\NamedDecl\ValueDecl\DeclaratorDecl\VarDecl) {
if (!in_array($declaration->name, self::VARS_TO_REMOVE)) {
$result[] = $declaration;
}
} elseif ($declaration instanceof Decl\NamedDecl\TypeDecl\TagDecl\EnumDecl) {
$result[] = $declaration;
} else {
throw new \LogicException('Unknown declaration type to skip/ignore: ' . get_class($declaration));
}
}
$this->declarationAst = array_merge($this->declarationAst, $result);
}
}