Debian Codegraph @

src/interceptor/generate_interceptors

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2
3 # Copyright (c) 2022 Firebuild Inc.
4 # All rights reserved.
5 # Free for personal use and commercial trial.
6 # Non-trial commercial use requires licenses available from https://firebuild.com.
7 # Modification and redistribution are permitted, but commercial use of
8 # derivative works is subject to the same requirements of this license
9 #
10 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16 # SOFTWARE.
17
18
19 import os
20 import sys
21 from jinja2 import Environment, FileSystemLoader
22
23
24 if len(sys.argv) != 2:
25 print("Usage: ./generate_interceptors outputdir", file=sys.stderr)
26 exit(1)
27 outdir = sys.argv[1]
28
29 supported_platforms = ['linux', 'darwin']
30 if sys.platform.startswith('linux'):
31 target = "linux"
32 elif sys.platform.startswith('darwin'):
33 target = "darwin"
34 else:
35 print("Unsupported platform: {}".format(platform.system()))
36 exit(1)
37
38
39 libc_outputs = ['decl.h', 'def.c', 'impl.c', 'list.txt', 'reset.c']
40 syscall_outputs = ['decl.h', 'def.c', 'impl_syscalls.c.inc', 'reset.c']
41 env = Environment(loader=FileSystemLoader('.'),
42 line_statement_prefix='###',
43 trim_blocks=True,
44 lstrip_blocks=True,
45 keep_trailing_newline=True,
46 extensions=['jinja2.ext.do'])
47
48 # Use a practically unique temporary filename, see #314
49 tmpsuffix = ".tmp." + str(os.getpid())
50
51 # Time related functions defined on 32 bit architectures
52 time64_functions = set({
53 "__adjtime64",
54 "__clock_adjtime64",
55 "__clock_gettime64",
56 "__clock_settime64",
57 "__futimens64",
58 "__futimes64",
59 "__futimesat64",
60 "__gettimeofday64",
61 "__lutimes64",
62 "__ntp_gettime64",
63 "__ntp_gettimex64",
64 "__recvmmsg64",
65 "__recvmsg64",
66 "__sendmmsg64",
67 "__sendmsg64",
68 "__settimeofday64",
69 "__time64",
70 "__utime64",
71 "__utimensat64",
72 "__utimes64"
73 })
74
75 remapped_time64_functions = set(
76 [x.replace("64","").replace("__","") for x in time64_functions] +
77 ["ioctl",
78 "fcntl",
79 "fcntl64",
80 "fstat64",
81 "fstatat64",
82 "lstat64",
83 "stat64",
84 "wait3",
85 "wait4"]
86 )
87
88 remapped_file64_functions = set({
89 "creat",
90 "fallocate",
91 "fcntl",
92 "fgetpos",
93 "fopen",
94 "freopen",
95 "fseeko",
96 "fsetpos",
97 "fstat",
98 "fstatat",
99 "fstatfs",
100 "fstatvfs",
101 "ftello",
102 "ftruncate",
103 "lockf",
104 "lseek",
105 "lstat",
106 "mkostemp",
107 "mkostemps",
108 "mkstemp",
109 "mkstemps",
110 "open",
111 "__open_2",
112 "openat",
113 "__openat_2",
114 "posix_fallocate",
115 "pread",
116 "preadv",
117 "preadv2",
118 "pwrite",
119 "pwritev",
120 "pwritev2",
121 "__recvmmsg",
122 "__recvmsg",
123 "scandir",
124 "scandirat",
125 "__sendmmsg",
126 "__sendmsg",
127 "stat",
128 "statfs",
129 "statvfs",
130 "tmpfile",
131 "truncate",
132 })
133
134 # Those functions are remapped to 64 bit variants, but interception is safe
135 # because the affected passed and returned values are passed and returned as
136 # references and the interception does not use or alter their value.
137 safe_remapped_functions = set({
138 "adjtime",
139 "clock_adjtime",
140 "clock_gettime",
141 "clock_settime",
142 "creat",
143 "fcntl",
144 "fcntl64",
145 "fopen",
146 "freopen",
147 "fstatfs",
148 "fstatvfs",
149 "futimens",
150 "gettimeofday",
151 "ioctl",
152 "mkostemp",
153 "mkostemps",
154 "mkstemp",
155 "mkstemps",
156 "ntp_gettime",
157 "ntp_gettimex",
158 "open",
159 "__open_2",
160 "openat",
161 "__openat_2",
162 "recvmmsg",
163 "recvmsg",
164 "scandir",
165 "scandirat",
166 "__sendmmsg",
167 "sendmmsg",
168 "sendmsg",
169 "statfs",
170 "statvfs",
171 "time",
172 "tmpfile",
173 "utime",
174 "utimensat",
175 "utimes",
176 "wait3",
177 "wait4"
178 })
179 # Best effort to try to debug as many parameters as easily doable.
180 def add_debug_to_dict(type, name, dict):
181 debug_type_to_when_and_how = {
182 "int": ("before", "%d"),
183 "unsigned int": ("before", "%u"),
184 "mode_t": ("before", "%\" PRImode \""),
185 "uid_t": ("before", "%u"),
186 "gid_t": ("before", "%u"),
187 "long": ("before", "%ld"),
188 "ssize_t": ("before", "%\" PRIssize \""),
189 "off_t": ("before", "%\" PRIoff \""),
190 "off64_t": ("before", "%\" PRIoff64 \""),
191 "unsigned long": ("before", "%lu"),
192 "size_t": ("before", "%\" PRIsize \""),
193 "const char *": ("before", "\\\"%s\\\""),
194 "char *": ("after", "\\\"%s\\\""), # assume the call modifies, so log at the end
195 "FILE *": ("before", "%p"),
196 "DIR *": ("before", "%p"),
197 }
198
199 if type in debug_type_to_when_and_how:
200 (when, fmt) = debug_type_to_when_and_how[type]
201
202 if name == 'ret':
203 when = "after"
204
205 dict['debug_' + when + '_fmt'] += ", " + name + "=" + fmt
206 dict['debug_' + when + '_args'] += ", " + name
207
208
209 # Split the C parameter specification of a function, at spaces that are outside of parentheses.
210 # E.g. "int (*compar)(void *, void *), void *arg" -> ["int (*compar)(void *, void *)", "void *arg"]
211 def split_param_spec(sig):
212 sig = sig.strip()
213 if not sig:
214 return []
215
216 ret = []
217 start_pos = 0
218 pos = 0
219 nest = 0
220 while pos <= len(sig):
221 if pos == len(sig) or (sig[pos] == ',' and nest == 0):
222 ret.append(sig[start_pos:pos].strip())
223 start_pos = pos + 1
224 elif sig[pos] == '(':
225 nest += 1
226 elif sig[pos] == ')':
227 nest -= 1
228 pos += 1
229 return ret
230
231
232 # For one parameter specification of a C function, extract the type and the name into a dictionary.
233 #
234 # E.g. "int pipefd[2]" -> name: "pipefd"
235 # type: "int[2]"
236 # type_and_name: "int pipefd[2]"
237 # vatype: "int *"
238 # vatype_and_name: "int *pipefd"
239 #
240 # E.g. "int (*compar)(void *, void *)" -> name: "compar"
241 # type, vatype: "int (*)(void *, void *)"
242 # type_and_name, vatype_and_name: "int (*compar)(void *, void *)"
243 #
244 def get_arg(sig):
245 arg = {}
246 sig = sig.strip()
247 name_end = len(sig)
248 dimension = 0
249 # Handle array declaration, e.g. "[2]" in "int pipefd[2]".
250 while name_end > 0 and sig[name_end - 1] == ']':
251 name_end = sig.rindex('[', 0, name_end)
252 dimension += 1
253 subscript_begin = name_end
254 # Handle function pointer parameter, e.g. "int (*compar)(void *, void *)".
255 # Walk backwards from the end, locate the beginning of the parameter list.
256 if name_end > 0 and sig[name_end - 1] == ')':
257 pos = name_end - 1
258 nest = 1
259 while pos > 0 and nest > 0:
260 if sig[pos - 1] == ')':
261 nest += 1
262 elif sig[pos - 1] == '(':
263 nest -= 1
264 pos -= 1
265 # pos now points to the parameter list, e.g. "(void *, void *)". Still need to walk back through a ')'.
266 name_end = sig.rindex(')', 0, pos)
267 # name_end is now the end of the variable name. Let's find the sequence of alphanumeric + '_' characters.
268 name_start = name_end
269 while name_start > 0 and (sig[name_start - 1].isalnum() or sig[name_start - 1] == '_'):
270 name_start -= 1
271 # The variable name is between name_start and name_end, the rest is the signature.
272 arg['name'] = sig[name_start:name_end].strip()
273 arg['type'] = sig[0:name_start].strip() + sig[name_end:].strip()
274 arg['type_and_name'] = sig[0:name_start] + arg['name'] + sig[name_end:].strip() # it's essentially sig
275 arg['vatype'] = sig[0:name_start].strip() + dimension * '*' + sig[name_end:subscript_begin].strip()
276 arg['vatype_and_name'] = sig[0:name_start] + ('*' * dimension) + arg['name'] + sig[name_end:subscript_begin].strip()
277 return arg
278
279
280 # Given a method signature (return type, types and names of parameters)
281 # as strings, generates various values for the convenience of templates.
282 # Supports arrays, but does not support function pointers.
283 #
284 # For the debug info to work, requires a space before the start,
285 # e.g. "char *" and not "char*".
286 #
287 # E.g.
288 # rettype = "int"
289 # sig = "const char *pathname, int flags, int pipefd[2], ..."
290 # ->
291 # args = [{
292 # 'name': "pathname",
293 # 'type': "const char *",
294 # 'type_and_name': "const char *pathname",
295 # 'vatype': "const char *",
296 # 'vatype_and_name': "const char *pathname",
297 # }, {
298 # 'name': "flags"
299 # 'type': "int",
300 # 'type_and_name': "int flags",
301 # 'vatype': "int",
302 # 'vatype_and_name': "int flags",
303 # }, {
304 # 'name': "pipefd",
305 # 'type': "int[2]",
306 # 'type_and_name': "int pipefd[2]",
307 # 'vatype': "int *",
308 # 'vatype_and_name': "int *pipefd",
309 # }]
310 # vararg = True
311 # types_str = "const char *, int, int[2], ..."
312 # sig_str = "const char *pathname, int flags, int pipefd[2], ..."
313 # names_str = "pathname, flags, pipefd"
314 #
315 # debug_before_fmt ≈ ", pathname = \"%s\", flags = %d"
316 # debug_before_args ≈ ", pathname, flags"
317 # debug_after_fmt ≈ ", ret = %d"
318 # debug_after_args ≈ ", ret"
319 def add_signature_to_dict(rettype, sig, dict):
320 dict['args'] = []
321 dict['vararg'] = False
322 dict['sig_str'] = sig
323
324 dict['debug_before_fmt'] = ''
325 dict['debug_before_args'] = ''
326 dict['debug_after_fmt'] = ''
327 dict['debug_after_args'] = ''
328
329 params = split_param_spec(sig)
330 for type_and_name in params:
331 type_and_name = type_and_name.strip()
332 if type_and_name == '...':
333 dict['vararg'] = True
334 else:
335 arg = get_arg(type_and_name)
336 dict['args'].append(arg)
337
338 add_debug_to_dict(arg['type'], arg['name'], dict)
339
340 dict['types_str'] = ', '.join(arg['type'] for arg in dict['args'])
341 if dict['vararg']:
342 dict['types_str'] += ', ...'
343 dict['names_str'] = ', '.join(arg['name'] for arg in dict['args'])
344
345 add_debug_to_dict(rettype, 'ret', dict)
346
347 return dict
348
349 def extend_or_add_ifdef_guard(fun_dict, base_guard, extension):
350 if 'ifdef_guard' not in fun_dict or fun_dict['ifdef_guard'] is None:
351 fun_dict['ifdef_guard'] = base_guard + " && " + extension
352 else:
353 fun_dict['ifdef_guard'] = fun_dict['ifdef_guard'] + " && " + extension
354
355 def extend_before_lines(fun_dict, extension):
356 if 'before_lines' not in fun_dict or fun_dict['before_lines'] is None:
357 fun_dict['before_lines'] = extension
358 else:
359 fun_dict['before_lines'] = fun_dict['before_lines'] + extension
360
361 # Keep track of the functions we've already generated.
362 generated={}
363
364
365 # Generate stuff for the given libc / kernel method.
366 #
367 # Makes sure to exit with an error if there's a skip() or another
368 # generate() call somewhere else for the same method.
369 #
370 # rettype: method's return type, as string
371 # funcs: one or more function names, or syscall names if start with "SYS_",
372 # as (list of) string
373 # sig: the function signature, as string
374 # tpl: the template file to use, default is 'tpl.c'
375 # msg: the message type, default is the first func
376 # success: the success condition, default depends on rettype
377 # dict: further parameters to pass to the template,
378 # see the template for their documentation
379 def generate(rettype, funcs, sig, **dict):
380 if type(funcs) == str:
381 funcs = [funcs]
382
383 if 'platforms' in dict:
384 for platform in dict['platforms']:
385 if platform not in supported_platforms:
386 print("Unsupported platform: {}".format(platform))
387 exit(1)
388 if target not in dict['platforms']:
389 return
390
391 if 'tpl' not in dict:
392 dict['tpl'] = 'tpl.c.jinja2'
393 else:
394 dict['tpl'] = 'tpl_' + dict['tpl'] + '.c.jinja2'
395 template = env.get_template(dict['tpl'])
396
397 dict['target'] = target
398
399 if 'msg' not in dict:
400 candidate = funcs[0]
401 if dict['tpl'] == 'tpl_once.c.jinja2':
402 candidate = 'gen_call'
403 if candidate.startswith("__"):
404 candidate = candidate.lstrip("_")
405 for suffix in ("_nocancel", "64"):
406 if candidate.endswith(suffix):
407 candidate = candidate[:-len(suffix)]
408 dict['msg'] = candidate
409
410 if 'success' not in dict:
411 if rettype == 'void':
412 dict['success'] = "true /* default success condition for void rettype */"
413 elif '*' in rettype:
414 dict['success'] = "ret != NULL /* default success condition for pointer rettype */"
415 else:
416 dict['success'] = "ret >= 0 /* default success condition for scalar rettype */"
417
418 add_signature_to_dict(rettype, sig, dict)
419
420 if 'msg_skip_fields' in dict:
421 for msg_skip in dict['msg_skip_fields']:
422 if msg_skip != "error_no" and msg_skip not in [arg['name'] for arg in dict['args']]:
423 print("generate_interceptors: invalid msg_skip_fields value '" + msg_skip + "' for func '" + funcs[0] + "'")
424 exit(1)
425
426 for func in funcs:
427 fun_dict = dict.copy()
428 if func in generated and func not in ["gettimeofday", "__gettimeofday", "vfork", "SYS_vfork", "__vfork"]:
429 print("generate_interceptors: Error: Already generated '" + func + "'", file=sys.stderr)
430 exit(1)
431 generated[func] = True
432
433 if func[:4] == 'SYS_':
434 syscall = True
435 outputs = syscall_outputs
436 call_ic_orig_func = "ic_orig_" + func
437 else:
438 syscall = False
439 outputs = libc_outputs
440 call_ic_orig_func = "get_ic_orig_" + func + "()"
441 if target == "darwin" and func in {"__fstat", "__fstatat", "__lstat", "__stat"}:
442 if 'ifdef_guard' not in fun_dict or fun_dict['ifdef_guard'] is None:
443 fun_dict['ifdef_guard'] = "#if defined(__aarch64__)"
444 if func.endswith("_time64") or func in time64_functions:
445 extend_or_add_ifdef_guard(fun_dict, glibc_ge(2, 34), "defined(__TIMESIZE) && (__TIMESIZE == 32)")
446 if target == "linux" and func in remapped_time64_functions \
447 and func not in safe_remapped_functions:
448 extend_before_lines(fun_dict, ["#if defined(_TIME_BITS) && (_TIME_BITS == 64)",
449 " assert(0 && \"intercepting " + func + "() when 64bit time variant is the default is not supported.\");",
450 "#endif"])
451 if target == "linux" and func in remapped_file64_functions \
452 and func not in safe_remapped_functions:
453 extend_before_lines(fun_dict, ["#if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS == 64)",
454 " assert(0 && \"intercepting " + func + "() when 64bit offset variant is the default is not supported.\");",
455 "#endif"])
456 if target == 'darwin' and (func.endswith("_unlocked") or func.endswith("_chk") \
457 or func.endswith("64") or func.endswith("64v2")):
458 continue
459 for gen in outputs:
460 rendered = template.render(gen=gen, rettype=rettype, func=func, syscall=syscall,
461 call_ic_orig_func=call_ic_orig_func, **fun_dict)
462 if rendered:
463 with open(outdir + "/gen_" + gen + tmpsuffix, "a") as f:
464 f.write(rendered)
465
466
467 # Do not intercept the given libc / kernel method.
468 #
469 # This does two things:
470 #
471 # Creates a "#define get_ic_orig_func() func" redirect so that you can always
472 # call get_ic_orig_foo()(args) in the interceptor code, without worrying whether
473 # that method is overridden or not.
474 #
475 # Also makes sure to exit with an error if there's a
476 # generate() call somewhere else for the same method.
477 #
478 # You can pass multiple function names at once.
479 def skip(*list):
480 for func in list:
481 generate('', func, '',
482 tpl="skip")
483
484
485 def glibc_ge(major, minor):
486 return "#if FB_GLIBC_PREREQ({}, {})".format(major, minor)
487
488 def not_glibc_ge(major, minor):
489 return "#if !FB_GLIBC_PREREQ({}, {})".format(major, minor)
490
491 def apple_ge(major, minor):
492 return '#if (defined __APPLE__) && (__MAC_OS_X_VERSION_MIN_REQUIRED >= {}{}00)'.format(str(major).zfill(2), str(minor).zfill(2))
493
494 # Initialize the output files with their headers.
495 # Also truncate them before we'll reopen them plenty of times for appending.
496 for gen in set(libc_outputs + syscall_outputs):
497 with open(outdir + "/gen_" + gen + tmpsuffix, "w") as f:
498 f.write("/* Auto-generated by generate_interceptors, do not edit */\n\n")
499
500
501 # Intercept vararg open() and friends
502 generate("int", ["open", "open64", "__open64", "SYS_open", "__open", "__open_nocancel"] + (["__open64_nocancel"] if target == "linux" else ["open$NOCANCEL"]), "const char *pathname, int flags, ...",
503 tpl="open",
504 msg_skip_fields=["pathname"])
505 generate("int", ["openat", "openat64", "SYS_openat"] + (["__openat", "openat$NOCANCEL"] if target == "darwin" else []), "int dirfd, const char *pathname, int flags, ...",
506 tpl="open",
507 msg_skip_fields=["pathname"],
508 msg="open")
509 # Intercept SYS_openat2 (Linux 5.6+, glibc 2.43+). Note: It's not the same as the glibc symbols __openat[64]_2.
510 # When resolve_flags are set, don't canonicalize the path since the kernel will resolve it differently.
511 for func, guard in [("openat2", glibc_ge(2, 43)), ("SYS_openat2", None)]:
512 generate("int", func, "int dirfd, const char *pathname, const struct open_how *how, size_t size",
513 platforms=["linux"],
514 ifdef_guard=guard,
515 tpl="open",
516 before_lines=["const int flags = how ? how->flags : 0;",
517 "const mode_t mode = how ? how->mode : 0;",
518 "const uint64_t resolve_flags = how ? how->resolve : 0;"],
519 msg_skip_fields=["pathname", "how", "size"],
520 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, flags);",
521 "if (__OPEN_NEEDS_MODE(flags)) fbbcomm_builder_open_set_mode(&ic_msg, mode);",
522 "fbbcomm_builder_open_set_resolve_flags(&ic_msg, resolve_flags);",
523 "if (resolve_flags) {",
524 " fbbcomm_builder_open_set_pathname(&ic_msg, pathname);",
525 "} else {",
526 " BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(open, dirfd, pathname);",
527 "}",
528 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, pre_open_sent);"],
529 msg="open")
530
531 # Intercept open_2 variants
532 generate("int", ["__open_2", "__open64_2"], "const char *pathname, int flags",
533 platforms=["linux"],
534 tpl="open",
535 msg_skip_fields=["pathname"],
536 msg="open")
537 generate("int", ["__openat_2", "__openat64_2"], "int dirfd, const char *pathname, int flags",
538 platforms=["linux"],
539 tpl="open",
540 msg_skip_fields=["pathname"],
541 msg="open")
542
543 # Intercept creat()
544 generate("int", ["creat", "creat64", "SYS_creat"], "const char *pathname, mode_t mode",
545 tpl="open",
546 before_lines=["const int flags = O_CREAT | O_WRONLY | O_TRUNC;"],
547 msg_skip_fields=["pathname"],
548 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
549 "fbbcomm_builder_open_set_flags(&ic_msg, flags);",
550 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, pre_open_sent);"],
551 msg="open")
552
553 # Intercept fopen
554 def open_ack_condition(msg):
555 return "success " \
556 "&& !is_path_at_locations(fbbcomm_builder_" + msg + "_get_pathname(&ic_msg), fbbcomm_builder_" + msg + "_get_pathname_len(&ic_msg), &read_only_locations) " \
557 "&& !is_path_at_locations(fbbcomm_builder_" + msg + "_get_pathname(&ic_msg), fbbcomm_builder_" + msg + "_get_pathname_len(&ic_msg), &ignore_locations)"
558
559 # Note: confusingly open()'s and fopen()'s manual uses the word "mode" for something completely different.
560 generate("FILE *", ["fopen", "fopen64"], "const char *pathname, const char *mode",
561 before_lines=["int open_flags = intercept_fopen_mode_to_open_flags_helper(mode);",
562 "bool pre_open_sent = i_am_intercepting && maybe_send_pre_open(AT_FDCWD, pathname, open_flags);"],
563 after_lines=["int fd = safe_fileno(ret);",
564 "if (i_am_intercepting && success) clear_notify_on_read_write_state(fd);",
565 "assert(!voidp_set_contains(&popened_streams, ret));"],
566 msg="open",
567 msg_skip_fields=["pathname", "mode"],
568 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, open_flags);",
569 "if (open_flags & O_CREAT) fbbcomm_builder_open_set_mode(&ic_msg, 0666);",
570 "if (success) fbbcomm_builder_open_set_ret(&ic_msg, fd);",
571 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
572 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, pre_open_sent);"],
573 ack_condition=open_ack_condition("open"))
574
575 # Intercept freopen
576 generate("FILE *", ["freopen", "freopen64"], "const char *pathname, const char *mode, FILE *stream",
577 before_lines=["int open_flags = intercept_fopen_mode_to_open_flags_helper(mode);",
578 "bool pre_open_sent = i_am_intercepting && maybe_send_pre_open(AT_FDCWD, pathname, open_flags);",
579 "int oldfd = safe_fileno(stream);",
580 "if (i_am_intercepting) clear_notify_on_read_write_state(oldfd);"],
581 after_lines=["int newfd = safe_fileno(ret);",
582 "if (i_am_intercepting && success) clear_notify_on_read_write_state(newfd);"],
583 msg_skip_fields=["pathname", "mode", "stream"],
584 msg_add_fields=["fbbcomm_builder_freopen_set_flags(&ic_msg, intercept_fopen_mode_to_open_flags_helper(mode));",
585 "if (oldfd >= 0) fbbcomm_builder_freopen_set_oldfd(&ic_msg, oldfd);",
586 "if (success) fbbcomm_builder_freopen_set_ret(&ic_msg, newfd);",
587 "BUILDER_SET_ABSOLUTE_CANONICAL(freopen, pathname);",
588 "fbbcomm_builder_freopen_set_pre_open_sent(&ic_msg, pre_open_sent);"],
589 ack_condition=open_ack_condition("freopen"))
590
591 # High level stream operation only
592 generate("FILE *", "fdopen", "int fd, const char *mode",
593 msg=None,
594 after_lines=["assert(!voidp_set_contains(&popened_streams, ret));"])
595
596 generate("int", ["shm_open"] + (["__shm_open"] if target == "darwin" else []), "const char *name, int oflag, " + ("mode_t mode" if target == 'linux' else "..."),
597 send_ret_on_success=True,
598 tpl="shm_open")
599 generate("int", "shm_unlink", "const char *name",
600 tpl="once")
601 generate("int", "shmget", "key_t key, size_t size, int shmflg",
602 tpl="once")
603 generate("int", ["memfd_create", "SYS_memfd_create"], "const char *name, unsigned int flags",
604 platforms=['linux'],
605 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
606 send_ret_on_success=True,
607 send_msg_on_error=False)
608 generate("int", ["timerfd_create", "SYS_timerfd_create"], "int clockid, int flags",
609 platforms=['linux'],
610 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
611 msg_skip_fields=["clockid"],
612 send_ret_on_success=True,
613 send_msg_on_error=False)
614 generate("int", ["epoll_create", "SYS_epoll_create"], "int size",
615 platforms=['linux'],
616 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
617 msg_skip_fields=["size"],
618 send_ret_on_success=True,
619 send_msg_on_error=False)
620 generate("int", ["epoll_create1", "SYS_epoll_create1"], "int flags",
621 platforms=['linux'],
622 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
623 msg="epoll_create",
624 send_ret_on_success=True,
625 send_msg_on_error=False)
626 # SYS_eventfd only takes the initial value as parameter.
627 # glibc's eventfd() corresponds to SYS_eventfd2 which takes an additional flags parameter.
628 generate("int", "SYS_eventfd", "unsigned int initval",
629 platforms=['linux'],
630 msg="eventfd",
631 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
632 msg_skip_fields=["initval"],
633 msg_add_fields=["fbbcomm_builder_eventfd_set_flags(&ic_msg, 0);"],
634 send_ret_on_success=True,
635 send_msg_on_error=False)
636 generate("int", ["eventfd", "SYS_eventfd2"], "unsigned int initval, int flags",
637 platforms=['linux'],
638 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
639 msg_skip_fields=["initval"],
640 send_ret_on_success=True,
641 send_msg_on_error=False)
642 generate("int", "signalfd", "int fd, const sigset_t *mask, int flags",
643 platforms=['linux'],
644 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
645 msg_skip_fields=["mask"],
646 send_ret_on_success=True,
647 send_msg_on_error=False)
648 generate("int", "SYS_signalfd", "int fd, const sigset_t *mask, size_t sizemask",
649 platforms=['linux'],
650 msg="signalfd",
651 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
652 msg_skip_fields=["mask", "sizemask"],
653 msg_add_fields=["fbbcomm_builder_signalfd_set_flags(&ic_msg, 0);"],
654 send_ret_on_success=True,
655 send_msg_on_error=False)
656 generate("int", "SYS_signalfd4", "int fd, const sigset_t *mask, size_t sizemask, int flags",
657 platforms=['linux'],
658 msg="signalfd",
659 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
660 msg_skip_fields=["mask", "sizemask"],
661 send_ret_on_success=True,
662 send_msg_on_error=False)
663
664 # Intercept close and fclose
665 # Don't call the actual method on the supervisor connection fd.
666 generate("int", ["close", "SYS_close", "__close_nocancel"] + (["close$NOCANCEL"] if target == "darwin" else ["__close"]), "int fd",
667 before_lines=["if (i_am_intercepting) set_notify_on_read_write_state(fd);"])
668 generate("int", "fclose", "FILE *stream",
669 before_lines=["int fd = safe_fileno(stream); /* save it here, we can't do fileno() after the fclose() */",
670 "if (i_am_intercepting) set_notify_on_read_write_state(fd);",
671 "/* close() may be intercepted inside fclose() */",
672 "#ifndef __APPLE__",
673 "FB_THREAD_LOCAL(interception_recursion_depth)++;",
674 "#endif",
675 "voidp_set_erase(&popened_streams, stream);"],
676 after_lines=["#ifndef __APPLE__",
677 "FB_THREAD_LOCAL(interception_recursion_depth)--;",
678 "#endif"],
679 send_msg_condition="fd != -1 && strcmp(FB_THREAD_LOCAL(intercept_on), \"fclose\") == 0",
680 msg="close",
681 msg_skip_fields=["stream"],
682 msg_add_fields=["fbbcomm_builder_close_set_fd(&ic_msg, fd);"])
683
684 # Intercept closefrom and close_range
685 generate("void", ["closefrom"], "int lowfd",
686 platforms=['linux'],
687 tpl="closefrom",
688 send_msg_on_error=False)
689 # The manpage says "unsigned int flags" but in unistd.h it's "int flags".
690 generate("int", ["close_range", "SYS_close_range"], "unsigned int first, unsigned int last, int flags",
691 platforms=['linux'],
692 tpl="close_range")
693
694 # Unlike fclose(), fcloseall() only closes the high level streams and not the underlying fds.
695 # So we don't need to notify the supervisor. We need to clear the popened_streams set, though.
696 generate("int", "fcloseall", "",
697 platforms=['linux'],
698 msg=None,
699 after_lines=["voidp_set_clear(&popened_streams);"])
700
701 # Intercept opendir, closedir (no need to intercept fdopendir)
702 generate("DIR *", "opendir", "const char *pathname",
703 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(dirfd(ret));"],
704 msg="open",
705 msg_skip_fields=["pathname"],
706 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, O_RDONLY | O_CLOEXEC | O_DIRECTORY);",
707 "if (success) fbbcomm_builder_open_set_ret(&ic_msg, get_ic_orig_dirfd()(ret));",
708 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
709 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"],
710 ack_condition=open_ack_condition("open"))
711 generate("DIR *", "__opendir2", "const char *pathname, int flags",
712 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(dirfd(ret));"],
713 platforms=['darwin'],
714 msg="open",
715 msg_skip_fields=["pathname", "flags"],
716 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, flags | O_RDONLY | O_CLOEXEC | O_DIRECTORY);",
717 "if (success) fbbcomm_builder_open_set_ret(&ic_msg, get_ic_orig_dirfd()(ret));",
718 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
719 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"],
720 ack_condition=open_ack_condition("open"))
721 generate("int", "closedir", "DIR *dirp",
722 before_lines=["int fd = safe_dirfd(dirp); /* save it here, we can't do dirfd() after the closedir() */"],
723 msg="close",
724 msg_skip_fields=["dirp"],
725 msg_add_fields=["fbbcomm_builder_close_set_fd(&ic_msg, fd);"])
726
727 generate("int", "scandir", "const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)",
728 msg="scandirat",
729 msg_skip_fields=["dirp", "namelist", "filter", "compar"],
730 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(scandirat, dirp);"])
731 generate("int", "scandir64", "const char *dirp, struct dirent64 ***namelist, int (*filter)(const struct dirent64 *), int (*compar)(const struct dirent64 **, const struct dirent64 **)",
732 msg="scandirat",
733 msg_skip_fields=["dirp", "namelist", "filter", "compar"],
734 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(scandirat, dirp);"])
735 generate("int", "scandirat", "int dirfd, const char *dirp, struct dirent ***namelist, int (*filter)(const struct dirent *), int (*compar)(const struct dirent **, const struct dirent **)",
736 platforms=['linux'],
737 msg_skip_fields=["dirp", "namelist", "filter", "compar"],
738 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(scandirat, dirfd, dirp);"])
739 generate("int", "scandirat64", "int dirfd, const char *dirp, struct dirent64 ***namelist, int (*filter)(const struct dirent64 *), int (*compar)(const struct dirent64 **, const struct dirent64 **)",
740 msg_skip_fields=["dirp", "namelist", "filter", "compar"],
741 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(scandirat, dirfd, dirp);"])
742
743 generate("int", ["mkdir", "SYS_mkdir"], "const char *pathname, mode_t mode",
744 msg_skip_fields=["pathname"],
745 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(mkdir, pathname);"])
746 generate("int", ["mkdirat", "SYS_mkdirat"], "int dirfd, const char *pathname, mode_t mode",
747 msg_skip_fields=["pathname"],
748 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(mkdir, dirfd, pathname);"],
749 msg="mkdir")
750
751 # Intercept the remove, rmdir, unlink families
752 generate("int", ["unlink", "remove", "SYS_unlink"] + (["__unlink"] if target == "darwin" else []), "const char *pathname",
753 before_lines=["bool pre_open_sent = i_am_intercepting && maybe_send_pre_open(AT_FDCWD, pathname, O_WRONLY | O_TRUNC);"],
754 msg_skip_fields=["pathname"],
755 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(unlink, pathname);",
756 "fbbcomm_builder_unlink_set_pre_open_sent(&ic_msg, pre_open_sent);"])
757 generate("int", ["unlinkat", "SYS_unlinkat"] + (["__unlinkat"] if target == "darwin" else []), "int dirfd, const char *pathname, int flags",
758 before_lines=["bool pre_open_sent = i_am_intercepting && maybe_send_pre_open(dirfd, pathname, O_WRONLY | O_TRUNC);"],
759 msg_skip_fields=["pathname"],
760 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(unlink, dirfd, pathname);",
761 "fbbcomm_builder_unlink_set_pre_open_sent(&ic_msg, pre_open_sent);"],
762 msg="unlink")
763 generate("int", ["rmdir", "SYS_rmdir"] + (["__rmdir"] if target == "darwin" else []), "const char *pathname",
764 before_lines=["bool pre_open_sent = i_am_intercepting && maybe_send_pre_open(AT_FDCWD, pathname, O_WRONLY | O_TRUNC);"],
765 msg_skip_fields=["pathname"],
766 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(rmdir, pathname);",
767 "fbbcomm_builder_rmdir_set_pre_open_sent(&ic_msg, pre_open_sent);"])
768
769 # Intercept the rename family
770 generate("int", ["rename", "SYS_rename"] + (["__rename"] if target == "darwin" else []), "const char *oldpath, const char *newpath",
771 before_lines=["if (i_am_intercepting) {",
772 " send_pre_open_without_ack_request(AT_FDCWD, oldpath);",
773 " send_pre_open(AT_FDCWD, newpath);",
774 "}"],
775 msg_skip_fields=["oldpath", "newpath"],
776 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(rename, oldpath);",
777 "BUILDER_SET_ABSOLUTE_CANONICAL(rename, newpath);"],
778 ack_condition="true")
779 generate("int", ["renameat", "SYS_renameat"] + (["__renameat"] if target == "darwin" else []), "int olddirfd, const char *oldpath, int newdirfd, const char *newpath",
780 before_lines=["if (i_am_intercepting) {",
781 " send_pre_open_without_ack_request(olddirfd, oldpath);",
782 " send_pre_open(newdirfd, newpath);",
783 "}"],
784 msg_skip_fields=["oldpath", "newpath"],
785 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(rename, olddirfd, oldpath);",
786 "BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(rename, newdirfd, newpath);"],
787 msg="rename",
788 ack_condition="true")
789 for func_guard in [("SYS_renameat2", None), ("renameat2", glibc_ge(2, 28))]:
790 (func, ifdef_guard) = func_guard
791 generate("int", func, "int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags",
792 platforms=['linux'],
793 ifdef_guard=ifdef_guard,
794 before_lines=["if (i_am_intercepting) {",
795 " send_pre_open_without_ack_request(olddirfd, oldpath);",
796 " send_pre_open(newdirfd, newpath);",
797 "}"],
798 msg_skip_fields=["oldpath", "newpath"],
799 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(rename, olddirfd, oldpath);",
800 "BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(rename, newdirfd, newpath);"],
801 msg="rename",
802 ack_condition="true")
803
804 # Intercept operations that read from a file descriptor.
805 # FIXME also intercept mmap with PROT_READ
806 generate("ssize_t", ["read", "SYS_read", "__read_nocancel"] + (["__read"] if target == "linux" else []), "int fd, void *buf, size_t count",
807 tpl="read",
808 msg_skip_fields=["buf", "count"])
809 generate("ssize_t", "__read_chk", "int fd, void *buf, size_t count, size_t fortify_size",
810 tpl="read",
811 msg_skip_fields=["buf", "count", "fortify_size"])
812 generate("ssize_t", "readv", "int fd, const struct iovec *iov, int iovcnt",
813 tpl="read",
814 msg_skip_fields=["iov", "iovcnt"])
815 # Note: SYS_readv is like readv() but takes longs rather than ints.
816 generate("ssize_t", "SYS_readv", "long fd, const struct iovec *iov, unsigned long iovcnt",
817 tpl="read",
818 msg_skip_fields=["iov", "iovcnt"])
819 generate("ssize_t", "pread", "int fd, void *buf, size_t count, off_t offset",
820 tpl="read",
821 is_pread="true",
822 msg_skip_fields=["buf", "count", "offset"])
823 generate("ssize_t", "__pread_chk", "int fd, void *buf, size_t count, __off_t offset, size_t fortify_size",
824 tpl="read",
825 is_pread="true",
826 msg_skip_fields=["buf", "count", "offset", "fortify_size"])
827 generate("ssize_t", ["pread64", "__pread64", "__pread64_nocancel", "SYS_pread64"], "int fd, void *buf, size_t count, off64_t offset",
828 platforms=['linux'],
829 tpl="read",
830 is_pread="true",
831 msg_skip_fields=["buf", "count", "offset"])
832 generate("ssize_t", "__pread64_chk", "int fd, void *buf, size_t count, off64_t offset, size_t fortify_size",
833 platforms=['linux'],
834 tpl="read",
835 is_pread="true",
836 msg_skip_fields=["buf", "count", "offset", "fortify_size"])
837 generate("ssize_t", "preadv", "int fd, const struct iovec *iov, int iovcnt, off_t offset",
838 tpl="read",
839 is_pread="true",
840 msg_skip_fields=["iov", "iovcnt", "offset"])
841 # Note: SYS_preadv is like preadv() but takes longs rather than ints and splits the offset in two.
842 # The manpage says "These arguments contain, respectively, the low order and high order 32 bits of offset."
843 # This seems to be true on 32-bit architectures only. On 64-bit they take 64 bits each, making offset_h unused.
844 generate("ssize_t", "SYS_preadv", "long fd, const struct iovec *iov, unsigned long iovcnt, unsigned long offset_l, unsigned long offset_h",
845 tpl="read",
846 is_pread="true",
847 msg_skip_fields=["iov", "iovcnt", "offset_l", "offset_h"])
848 generate("ssize_t", "preadv64", "int fd, const struct iovec *iov, int iovcnt, off64_t offset",
849 platforms=['linux'],
850 tpl="read",
851 is_pread="true",
852 msg_skip_fields=["iov", "iovcnt", "offset"])
853 generate("ssize_t", "preadv2", "int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags",
854 platforms=['linux'],
855 tpl="read",
856 is_pread="offset != -1",
857 msg_skip_fields=["iov", "iovcnt", "offset", "flags"])
858 # Note: SYS_preadv2 is like preadv2() but takes longs rather than ints and splits the offset in two.
859 # The manpage says "These arguments contain, respectively, the low order and high order 32 bits of offset."
860 # This seems to be true on 32-bit architectures only. On 64-bit they take 64 bits each, making offset_h unused.
861 generate("ssize_t", "SYS_preadv2", "long fd, const struct iovec *iov, unsigned long iovcnt, unsigned long offset_l, unsigned long offset_h, int flags",
862 platforms=['linux'],
863 tpl="read",
864 before_lines=["off64_t offset = sizeof(long) >= 8 ? offset_l : (off64_t)offset_h << 32 | offset_l;"],
865 is_pread="offset != -1",
866 msg_skip_fields=["iov", "iovcnt", "offset_l", "offset_h", "flags"])
867 generate("ssize_t", "preadv64v2", "int fd, const struct iovec *iov, int iovcnt, off64_t offset, int flags",
868 platforms=['linux'],
869 tpl="read",
870 is_pread="offset != -1",
871 msg_skip_fields=["iov", "iovcnt", "offset", "flags"])
872 generate("size_t", ["fread", "fread_unlocked"] + (["__fread"] if target == "darwin" else []), "void *ptr, size_t size, size_t nmemb, FILE *stream",
873 tpl="read",
874 before_lines=["int fd = safe_fileno(stream);"],
875 send_msg_condition="fd != -1",
876 success="ret > 0 || !ferror(stream)",
877 msg_skip_fields=["ptr", "size", "nmemb", "stream"],
878 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
879 generate("size_t", ["__fread_chk", "__fread_unlocked_chk"], "void *ptr, size_t fortify_size, size_t size, size_t nmemb, FILE *stream",
880 tpl="read",
881 before_lines=["int fd = safe_fileno(stream);"],
882 send_msg_condition="fd != -1",
883 success="ret > 0 || !ferror(stream)",
884 msg_skip_fields=["ptr", "fortify_size", "size", "nmemb", "stream"],
885 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
886 generate("int", ["fgetc", "fgetc_unlocked", "getc", "getc_unlocked", "getw"], "FILE *stream",
887 tpl="read",
888 success="ret != EOF || !ferror(stream)",
889 before_lines=["int fd = safe_fileno(stream);"],
890 send_msg_condition="fd != -1",
891 msg_skip_fields=["stream"],
892 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
893 generate("wint_t", ["fgetwc", "fgetwc_unlocked", "getwc", "getwc_unlocked"] + (["__fgetwc"] if target == "darwin" else []), "FILE *stream",
894 tpl="read",
895 success="ret != WEOF || !ferror(stream)",
896 before_lines=["int fd = safe_fileno(stream);"],
897 send_msg_condition="fd != -1",
898 msg_skip_fields=["stream"],
899 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
900 generate("char *", ["fgets", "fgets_unlocked"], "char *s, int size, FILE *stream",
901 tpl="read",
902 success="ret != NULL || !ferror(stream)",
903 before_lines=["int fd = safe_fileno(stream);"],
904 send_msg_condition="fd != -1",
905 msg_skip_fields=["s", "size", "stream"],
906 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
907 generate("char *", ["__fgets_chk", "__fgets_unlocked_chk"], "char *s, size_t fortify_size, int size, FILE *stream",
908 success="ret != NULL || !ferror(stream)",
909 tpl="read",
910 before_lines=["int fd = safe_fileno(stream);"],
911 send_msg_condition="fd != -1",
912 msg_skip_fields=["s", "fortify_size", "size", "stream"],
913 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
914 generate("wchar_t *", ["fgetws", "fgetws_unlocked"], "wchar_t *s, int size, FILE *stream",
915 tpl="read",
916 success="ret != NULL || !ferror(stream)",
917 before_lines=["int fd = safe_fileno(stream);"],
918 send_msg_condition="fd != -1",
919 msg_skip_fields=["s", "size", "stream"],
920 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
921 generate("wchar_t *", ["__fgetws_chk", "__fgetws_unlocked_chk"], "wchar_t *s, size_t fortify_size, int size, FILE *stream",
922 success="ret != NULL || !ferror(stream)",
923 tpl="read",
924 before_lines=["int fd = safe_fileno(stream);"],
925 send_msg_condition="fd != -1",
926 msg_skip_fields=["s", "fortify_size", "size", "stream"],
927 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
928 generate("int", ["getchar", "getchar_unlocked"], "",
929 tpl="read",
930 success="ret != EOF || !ferror(stdin)",
931 before_lines=["int fd = safe_fileno(stdin);"],
932 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
933 generate("wint_t", ["getwchar", "getwchar_unlocked"], "",
934 tpl="read",
935 success="ret != WEOF || !ferror(stdin)",
936 before_lines=["int fd = safe_fileno(stdin);"],
937 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
938 generate("char *", "gets", "char *s", # should be never used, see man gets
939 tpl="read",
940 success="ret != NULL || !ferror(stdin)",
941 before_lines=["int fd = safe_fileno(stdin);"],
942 msg_skip_fields=["s"],
943 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
944 generate("char *", "__gets_chk", "char *s, size_t fortify_size", # should be never used, see man gets
945 tpl="read",
946 success="ret != NULL || !ferror(stdin)",
947 before_lines=["int fd = safe_fileno(stdin);"],
948 msg_skip_fields=["s", "fortify_size"],
949 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
950 generate("FB_SSIZE_T", "getline", "char **lineptr, size_t *n, FILE *stream",
951 tpl="read",
952 success="ret != EOF || !ferror(stream)",
953 before_lines=["int fd = safe_fileno(stream);"],
954 send_msg_condition="fd != -1",
955 msg_skip_fields=["lineptr", "n", "stream"],
956 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
957 generate("FB_SSIZE_T", ["getdelim"]+ (["__getdelim"] if target == "linux" else []), "char **lineptr, size_t *n, int delim, FILE *stream",
958 tpl="read",
959 success="ret != EOF || !ferror(stream)",
960 before_lines=["int fd = safe_fileno(stream);"],
961 send_msg_condition="fd != -1",
962 msg_skip_fields=["lineptr", "n", "delim", "stream"],
963 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
964 # glibc magic, see #343
965 generate("int", ["__uflow", "__underflow"], "FILE *stream",
966 platforms=["linux"],
967 tpl="read",
968 before_lines=["int fd = safe_fileno(stream);"],
969 send_msg_condition="fd != -1",
970 success="true",
971 msg_skip_fields=["stream"],
972 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
973 generate("wint_t", ["__wuflow", "__wunderflow"], "FILE *stream",
974 platforms=["linux"],
975 tpl="read",
976 before_lines=["int fd = safe_fileno(stream);"],
977 send_msg_condition="fd != -1",
978 success="true",
979 msg_skip_fields=["stream"],
980 msg_add_fields=["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"])
981 # Handle (__isoc99_)?v?f?w?scanf
982 for i in ['', '__isoc99_']:
983 for v in ['', 'v']:
984 for f in ['', 'f']:
985 for w in ['', 'w']:
986 func = i + v + f + w + "scanf"
987 if f == '':
988 sig_str = ''
989 names_str = ''
990 stream="stdin"
991 before_lines = ["int fd = safe_fileno(stdin);"]
992 msg_skip_fields = []
993 msg_add_fields = ["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"]
994 elif f == 'f':
995 sig_str = "FILE *stream, "
996 names_str = "stream, "
997 stream="stream"
998 before_lines = ["int fd = safe_fileno(stream);"]
999 send_msg_condition="fd != -1",
1000 msg_skip_fields = ["stream"]
1001 msg_add_fields = ["fbbcomm_builder_read_from_inherited_set_fd(&ic_msg, fd);"]
1002 if w:
1003 sig_str += "const wchar_t *format, "
1004 else:
1005 sig_str += "const char *format, "
1006 success="ret != EOF || !ferror(" + stream + ")"
1007 names_str += "format, "
1008 msg_skip_fields += ["format"]
1009 if v:
1010 sig_str += "FB_VA_LIST ap"
1011 call_orig_lines = None
1012 msg_skip_fields += ["ap"]
1013 else:
1014 sig_str += "..."
1015 call_orig_lines = ["ret = get_ic_orig_" + i + "v" + f + w + "scanf()(" + names_str + "ap);"]
1016 if i == '__isoc99_':
1017 platforms=['linux']
1018 else:
1019 platforms=['linux','darwin']
1020 generate("int", func, sig_str,
1021 platforms=platforms,
1022 tpl="read",
1023 success=success,
1024 before_lines=before_lines,
1025 call_orig_lines=call_orig_lines,
1026 msg_skip_fields=msg_skip_fields,
1027 msg_add_fields=msg_add_fields)
1028 if func == "vfscanf":
1029 generate("int", "__" + func, sig_str,
1030 platforms=["linux"],
1031 tpl="read",
1032 success=success,
1033 before_lines=before_lines,
1034 call_orig_lines=call_orig_lines,
1035 msg_skip_fields=msg_skip_fields,
1036 msg_add_fields=msg_add_fields)
1037
1038 for i in ['', '__isoc99_']:
1039 for v in ['', 'v']:
1040 for w in ['', 'w']:
1041 skip(i + v + "s" + w + "scanf")
1042
1043 generate("ssize_t", ["recv", "SYS_recv"], "int fd, void *buf, size_t len, int flags",
1044 tpl="read",
1045 msg_skip_fields=["buf", "len", "flags"])
1046 generate("ssize_t", ["__recv"], "int fd, void *buf, size_t len, int flags",
1047 platforms=['linux'],
1048 tpl="read",
1049 msg_skip_fields=["buf", "len", "flags"])
1050 generate("ssize_t", "__recv_chk", "int fd, void *buf, size_t len, size_t fortify_size, int flags",
1051 tpl="read",
1052 msg_skip_fields=["buf", "len", "fortify_size", "flags"])
1053 generate("ssize_t", ["recvfrom", "SYS_recvfrom"] + (["__recvfrom"] if target == "darwin" else []), "int fd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen",
1054 tpl="read",
1055 msg_skip_fields=["buf", "len", "flags", "src_addr", "addrlen"])
1056 generate("ssize_t", "__recvfrom_chk", "int fd, void *buf, size_t len, size_t fortify_size, int flags, struct sockaddr *src_addr, socklen_t *addrlen",
1057 tpl="read",
1058 msg_skip_fields=["buf", "len", "fortify_size", "flags", "src_addr", "addrlen"])
1059 generate("ssize_t", ["recvmsg", "SYS_recvmsg", "__recvmsg64"] + (["__recvmsg"] if target == "darwin" else []), "int fd, struct msghdr *msg, int flags",
1060 tpl="recvmsg",
1061 msg_skip_fields=["msg", "flags"])
1062 # FIXME add SYS_recvmmsg_time64
1063 generate("int", ["recvmmsg", "SYS_recvmmsg", "__recvmmsg64"], "int fd, struct mmsghdr *msgvec, unsigned int vlen, int flags, struct timespec *timeout",
1064 platforms=['linux'],
1065 tpl="recvmsg",
1066 msg_skip_fields=["msgvec", "vlen", "flags", "timeout"])
1067
1068 # Intercept operations that write to a file descriptor.
1069 # FIXME also intercept mmap with PROT_WRITE
1070 generate("ssize_t", ["write", "SYS_write", "__write_nocancel"], "int fd, const void *buf, size_t count",
1071 tpl="write",
1072 msg_skip_fields=["buf", "count"])
1073 generate("ssize_t", ["__write"], "int fd, const void *buf, size_t count",
1074 platforms=['linux'],
1075 tpl="write",
1076 msg_skip_fields=["buf", "count"])
1077 generate("ssize_t", "writev", "int fd, const struct iovec *iov, int iovcnt",
1078 tpl="write",
1079 msg_skip_fields=["iov", "iovcnt"])
1080 # Note: SYS_writev is like writev() but takes longs rather than ints.
1081 generate("ssize_t", "SYS_writev", "long fd, const struct iovec *iov, unsigned long iovcnt",
1082 tpl="write",
1083 msg_skip_fields=["iov", "iovcnt"])
1084 generate("ssize_t", "pwrite", "int fd, const void *buf, size_t count, off_t offset",
1085 tpl="write",
1086 is_pwrite="true",
1087 msg_skip_fields=["buf", "count", "offset"])
1088 generate("ssize_t", ["pwrite64", "__pwrite64", "SYS_pwrite64"], "int fd, const void *buf, size_t count, off64_t offset",
1089 platforms=['linux'],
1090 tpl="write",
1091 is_pwrite="true",
1092 msg_skip_fields=["buf", "count", "offset"])
1093 generate("ssize_t", "pwritev", "int fd, const struct iovec *iov, int iovcnt, off_t offset",
1094 tpl="write",
1095 is_pwrite="true",
1096 msg_skip_fields=["iov", "iovcnt", "offset"])
1097 # Note: SYS_pwritev is like pwritev() but takes longs rather than ints and splits the offset in two.
1098 # The manpage says "These arguments contain, respectively, the low order and high order 32 bits of offset."
1099 # This seems to be true on 32-bit architectures only. On 64-bit they take 64 bits each, making offset_h unused.
1100 generate("ssize_t", "SYS_pwritev", "long fd, const struct iovec *iov, unsigned long iovcnt, unsigned long offset_l, unsigned long offset_h",
1101 tpl="write",
1102 is_pwrite="true",
1103 msg_skip_fields=["iov", "iovcnt", "offset_l", "offset_h"])
1104 generate("ssize_t", "pwritev64", "int fd, const struct iovec *iov, int iovcnt, off64_t offset",
1105 platforms=['linux'],
1106 tpl="write",
1107 is_pwrite="true",
1108 msg_skip_fields=["iov", "iovcnt", "offset"])
1109 generate("ssize_t", "pwritev2", "int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags",
1110 platforms=['linux'],
1111 tpl="write",
1112 is_pwrite="offset != -1",
1113 msg_skip_fields=["iov", "iovcnt", "offset", "flags"])
1114 # Note: SYS_pwritev2 is like pwritev2() but takes longs rather than ints and splits the offset in two
1115 # The manpage says "These arguments contain, respectively, the low order and high order 32 bits of offset."
1116 # This seems to be true on 32-bit architectures only. On 64-bit they take 64 bits each, making offset_h unused.
1117 generate("ssize_t", "SYS_pwritev2", "long fd, const struct iovec *iov, unsigned long iovcnt, unsigned long offset_l, unsigned long offset_h, int flags",
1118 tpl="write",
1119 before_lines=["off64_t offset = sizeof(long) >= 8 ? offset_l : (off64_t)offset_h << 32 | offset_l;"],
1120 is_pwrite="offset != -1",
1121 msg_skip_fields=["iov", "iovcnt", "offset_l", "offset_h", "flags"])
1122 generate("ssize_t", "pwritev64v2", "int fd, const struct iovec *iov, int iovcnt, off64_t offset, int flags",
1123 platforms=['linux'],
1124 tpl="write",
1125 is_pwrite="offset != -1",
1126 msg_skip_fields=["iov", "iovcnt", "offset", "flags"])
1127 generate("size_t", ["fwrite", "fwrite_unlocked"], "const void *ptr, size_t size, size_t nmemb, FILE *stream",
1128 tpl="write",
1129 before_lines=["int fd = safe_fileno(stream);"],
1130 send_msg_condition="fd != -1",
1131 success="ret > 0 || !ferror(stream)",
1132 msg_skip_fields=["ptr", "size", "nmemb", "stream"],
1133 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1134 generate("int", ["fputc", "fputc_unlocked", "putc", "putc_unlocked", "putw"], "int c, FILE *stream",
1135 tpl="write",
1136 before_lines=["int fd = safe_fileno(stream);"],
1137 send_msg_condition="fd != -1",
1138 msg_skip_fields=["c", "stream"],
1139 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1140 generate("wint_t", ["fputwc", "fputwc_unlocked", "putwc", "putwc_unlocked"], "wchar_t wc, FILE *stream",
1141 tpl="write",
1142 success="ret != WEOF",
1143 before_lines=["int fd = safe_fileno(stream);"],
1144 send_msg_condition="fd != -1",
1145 msg_skip_fields=["wc", "stream"],
1146 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1147 generate("int", ["fputs", "fputs_unlocked"], "const char *s, FILE *stream",
1148 tpl="write",
1149 before_lines=["int fd = safe_fileno(stream);"],
1150 send_msg_condition="fd != -1",
1151 msg_skip_fields=["s", "stream"],
1152 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1153 generate("int", ["fputws", "fputws_unlocked"], "const wchar_t *s, FILE *stream",
1154 tpl="write",
1155 before_lines=["int fd = safe_fileno(stream);"],
1156 send_msg_condition="fd != -1",
1157 msg_skip_fields=["s", "stream"],
1158 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1159 generate("int", ["putchar", "putchar_unlocked"], "int c",
1160 tpl="write",
1161 before_lines=["int fd = safe_fileno(stdout);"],
1162 msg_skip_fields=["c"],
1163 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1164 generate("wint_t", ["putwchar", "putwchar_unlocked"], "wchar_t wc",
1165 tpl="write",
1166 success="ret != WEOF",
1167 before_lines=["int fd = safe_fileno(stdout);"],
1168 msg_skip_fields=["wc"],
1169 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1170 generate("int", "puts", "const char *s",
1171 tpl="write",
1172 before_lines=["int fd = safe_fileno(stdout);"],
1173 msg_skip_fields=["s"],
1174 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1175 # glibc magic, see #343
1176 generate("int", "__overflow", "FILE *stream, int ch",
1177 platforms=["linux"],
1178 tpl="write",
1179 before_lines=["int fd = safe_fileno(stream);"],
1180 send_msg_condition="fd != -1",
1181 success="true",
1182 msg_skip_fields=["stream", "ch"],
1183 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1184 generate("wint_t", "__woverflow", "FILE *stream, wint_t ch",
1185 platforms=["linux"],
1186 tpl="write",
1187 before_lines=["int fd = safe_fileno(stream);"],
1188 send_msg_condition="fd != -1",
1189 success="true",
1190 msg_skip_fields=["stream", "ch"],
1191 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1192 # There's no public verror() and verror_at_line().
1193 # Construct the message ourselves so that we don't have to rely on
1194 # gcc's __builtin_apply() with its arbitrarily guessed size parameter.
1195 generate("void", "error", "int status, int errnum, const char *format, ...",
1196 platforms=['linux'],
1197 tpl="error",
1198 before_lines=["int fd = safe_fileno(stderr);"],
1199 call_orig_lines=["int msglen = vsnprintf(NULL, 0, format, ap);",
1200 "va_end(ap);",
1201 "char msgbuf[msglen + 1];",
1202 "va_start(ap, format);",
1203 "vsnprintf(msgbuf, msglen + 1, format, ap);",
1204 "get_ic_orig_error()(status, errnum, \"%s\", msgbuf);"],
1205 msg_skip_fields=["status", "errnum", "format"],
1206 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1207 generate("void", "error_at_line", "int status, int errnum, const char *filename, unsigned int linenum, const char *format, ...",
1208 platforms=['linux'],
1209 tpl="error",
1210 before_lines=["int fd = safe_fileno(stderr);"],
1211 call_orig_lines=["int msglen = vsnprintf(NULL, 0, format, ap);",
1212 "va_end(ap);",
1213 "char msgbuf[msglen + 1];",
1214 "va_start(ap, format);",
1215 "vsnprintf(msgbuf, msglen + 1, format, ap);",
1216 "get_ic_orig_error_at_line()(status, errnum, filename, linenum, \"%s\", msgbuf);"],
1217 msg_skip_fields=["status", "errnum", "filename", "linenum", "format"],
1218 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1219 generate("void", ["herror", "perror"], "const char *s",
1220 tpl="write",
1221 before_lines=["int fd = safe_fileno(stderr);"],
1222 msg_skip_fields=["s"],
1223 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1224 # Handle v?(err|warn)x?
1225 for v in ['', 'v']:
1226 for e in ['err', 'warn']:
1227 for x in ['', 'x']:
1228 func = v + e + x
1229 if e == 'err':
1230 sig_str = "int status, "
1231 names_str = "status, "
1232 tpl = "error"
1233 msg_skip_fields = ["status"]
1234 else:
1235 sig_str = ''
1236 names_str = ''
1237 tpl = "write"
1238 msg_skip_fields = []
1239 sig_str += "const char *format, "
1240 names_str += "format, "
1241 msg_skip_fields += ["format"]
1242 if v:
1243 sig_str += "va_list ap"
1244 call_orig_lines = None
1245 msg_skip_fields += ["ap"]
1246 else:
1247 sig_str += "..."
1248 call_orig_lines = ["get_ic_orig_v" + e + x + "()(" + names_str + "ap);"]
1249 generate("void", func, sig_str,
1250 tpl=tpl,
1251 before_lines=["int fd = safe_fileno(stderr);"],
1252 call_orig_lines=call_orig_lines,
1253 msg_skip_fields=msg_skip_fields,
1254 msg_add_fields=["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"])
1255 # Handle (__)?v?[fd]?w?printf(_chk)?
1256 for v in ['', 'v']:
1257 for f in ['', 'f', 'd']:
1258 for w in ['', 'w']:
1259 for (c1, c2) in [('', ''), ('__', '_chk')]:
1260 if f == 'd' and w == 'w':
1261 # No [v]dwprintf() in glibc
1262 continue
1263 func = c1 + v + f + w + "printf" + c2
1264 if f == '':
1265 sig_str = ''
1266 names_str = ''
1267 before_lines = ["int fd = safe_fileno(stdout);"]
1268 msg_skip_fields = []
1269 msg_add_fields = ["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"]
1270 elif f == 'f':
1271 sig_str = "FILE *stream, "
1272 names_str = "stream, "
1273 before_lines = ["int fd = safe_fileno(stream);"]
1274 send_msg_condition="fd != -1",
1275 msg_skip_fields = ["stream"]
1276 msg_add_fields = ["fbbcomm_builder_write_to_inherited_set_fd(&ic_msg, fd);"]
1277 elif f == 'd':
1278 sig_str = "int fd, "
1279 names_str = "fd, "
1280 before_lines = []
1281 msg_skip_fields = []
1282 msg_add_fields = []
1283 if c1:
1284 sig_str += "int fortify_flag, "
1285 names_str += "fortify_flag, "
1286 msg_skip_fields += ["fortify_flag"]
1287 if w:
1288 sig_str += "const wchar_t *format, "
1289 else:
1290 sig_str += "const char *format, "
1291 names_str += "format, "
1292 msg_skip_fields += ["format"]
1293 if v:
1294 sig_str += "FB_VA_LIST ap"
1295 call_orig_lines = None
1296 msg_skip_fields += ["ap"]
1297 else:
1298 sig_str += "..."
1299 call_orig_lines = ["ret = get_ic_orig_" + c1 + "v" + f + w + "printf" + c2 + "()(" + names_str + "ap);"]
1300 generate("int", func, sig_str,
1301 tpl="write",
1302 before_lines=before_lines,
1303 call_orig_lines=call_orig_lines,
1304 msg_skip_fields=msg_skip_fields,
1305 msg_add_fields=msg_add_fields)
1306 for v in ['', 'v']:
1307 for w in ['', 'w', 'n']:
1308 for (c1, c2) in [('', ''), ('__', '_chk')]:
1309 skip(c1 + v + "s" + w + "printf" + c2)
1310 for v in ['', 'v']:
1311 for (c1, c2) in [('', ''), ('__', '_chk')]:
1312 skip(c1 + v + "asprintf" + c2)
1313
1314 for func_guard in [(["send", "SYS_send"], None),
1315 ("__send", "#if !defined(__aarch64__) || (defined(__linux__) && !__GLIBC_PREREQ(2, 34))")]:
1316 (func, ifdef_guard) = func_guard
1317 generate("ssize_t", func, "int fd, const void *buf, size_t len, int flags",
1318 platforms=(["linux"] if func == "__send" else ["darwin", "linux"]),
1319 ifdef_guard=ifdef_guard,
1320 tpl="write",
1321 msg_skip_fields=["buf", "len", "flags"])
1322 generate("ssize_t", ["sendto", "SYS_sendto"] + (["__sendto"] if target == "darwin" else []), "int fd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen",
1323 tpl="write",
1324 msg_skip_fields=["buf", "len", "flags", "dest_addr", "addrlen"])
1325 generate("ssize_t", ["sendmsg", "SYS_sendmsg", "__sendmsg64"] + (["__sendmsg"] if target == "darwin" else []), "int fd, const struct msghdr *msg, int flags",
1326 tpl="write",
1327 msg_skip_fields=["msg", "flags"])
1328 generate("int", ["sendmmsg", "SYS_sendmmsg", "__sendmmsg", "__sendmmsg64"], "int fd, struct mmsghdr *msgvec, unsigned int vlen, int flags",
1329 platforms=['linux'],
1330 tpl="write",
1331 msg_skip_fields=["msgvec", "vlen", "flags"])
1332
1333 # TODO(rbalint) report as read and write without disabling shortcutting
1334 generate("ssize_t", ["sendfile64", "SYS_sendfile64"], "int out_fd, int in_fd, off64_t *offset, size_t count",
1335 tpl="copy_file_range")
1336 generate("ssize_t", ["sendfile", "SYS_sendfile"], "int out_fd, int in_fd, off_t *offset, size_t count",
1337 platforms=['linux'],
1338 tpl="copy_file_range")
1339 generate("int", ["sendfile", "SYS_sendfile"], "int fd, int s, off_t offset, off_t *len, struct sf_hdtr *hdtr, int flags",
1340 platforms=['darwin'],
1341 tpl="copy_file_range")
1342 generate("ssize_t", ["copy_file_range", "SYS_copy_file_range"], "int fd_in, loff_t *off_in, int fd_out, loff_t *off_out, size_t len, unsigned int flags",
1343 platforms=['linux'],
1344 tpl="copy_file_range")
1345
1346 # Intercept querying or modifying the file offset
1347 # FIXME What's up with llseek, SYS_llseek, _llseek, __lseek, _IO_*seek* etc.?
1348 generate("off_t", ["lseek", "SYS_lseek", "__lseek"], "int fd, off_t offset, int whence",
1349 tpl="seek",
1350 modify_offset="offset != 0 || whence != SEEK_CUR",
1351 msg_skip_fields=["offset", "whence"])
1352 generate("off64_t", "lseek64", "int fd, off64_t offset, int whence",
1353 tpl="seek",
1354 modify_offset="offset != 0 || whence != SEEK_CUR",
1355 msg_skip_fields=["offset", "whence"])
1356 generate("int", "fseek", "FILE *stream, long offset, int whence",
1357 tpl="seek",
1358 before_lines=["int fd = safe_fileno(stream);"],
1359 modify_offset="offset != 0 || whence != SEEK_CUR",
1360 msg_skip_fields=["stream", "offset", "whence"],
1361 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1362 generate("int", "fseeko", "FILE *stream, off_t offset, int whence",
1363 tpl="seek",
1364 before_lines=["int fd = safe_fileno(stream);"],
1365 modify_offset="offset != 0 || whence != SEEK_CUR",
1366 msg_skip_fields=["stream", "offset", "whence"],
1367 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1368 for func_guard in [("fseeko64", None), ("__fseeko64", glibc_ge(2, 28))]:
1369 (func, ifdef_guard) = func_guard
1370 generate("int", func, "FILE *stream, off64_t offset, int whence",
1371 ifdef_guard=ifdef_guard,
1372 tpl="seek",
1373 before_lines=["int fd = safe_fileno(stream);"],
1374 modify_offset="offset != 0 || whence != SEEK_CUR",
1375 msg_skip_fields=["stream", "offset", "whence"],
1376 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1377 generate("long", "ftell", "FILE *stream",
1378 tpl="seek",
1379 before_lines=["int fd = safe_fileno(stream);"],
1380 modify_offset="false",
1381 msg_skip_fields=["stream"],
1382 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1383 generate("off_t", "ftello", "FILE *stream",
1384 tpl="seek",
1385 before_lines=["int fd = safe_fileno(stream);"],
1386 modify_offset="false",
1387 msg_skip_fields=["stream"],
1388 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1389 for func_guard in [("ftello64", None), ("__ftello64", glibc_ge(2, 28))]:
1390 (func, ifdef_guard) = func_guard
1391 generate("off64_t", func, "FILE *stream",
1392 ifdef_guard=ifdef_guard,
1393 tpl="seek",
1394 before_lines=["int fd = safe_fileno(stream);"],
1395 modify_offset="false",
1396 msg_skip_fields=["stream"],
1397 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1398 generate("int", "fgetpos", "FILE *stream, fpos_t *pos",
1399 tpl="seek",
1400 before_lines=["int fd = safe_fileno(stream);"],
1401 modify_offset="false",
1402 msg_skip_fields=["stream", "pos"],
1403 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1404 generate("int", "fgetpos64", "FILE *stream, fpos64_t *pos",
1405 tpl="seek",
1406 before_lines=["int fd = safe_fileno(stream);"],
1407 modify_offset="false",
1408 msg_skip_fields=["stream", "pos"],
1409 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1410 generate("int", "fsetpos", "FILE *stream, const fpos_t *pos",
1411 tpl="seek",
1412 before_lines=["int fd = safe_fileno(stream);"],
1413 modify_offset="true",
1414 msg_skip_fields=["stream", "pos"],
1415 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1416 generate("int", "fsetpos64", "FILE *stream, const fpos64_t *pos",
1417 tpl="seek",
1418 before_lines=["int fd = safe_fileno(stream);"],
1419 modify_offset="true",
1420 msg_skip_fields=["stream", "pos"],
1421 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1422 generate("void", "rewind", "FILE *stream",
1423 tpl="seek",
1424 before_lines=["int fd = safe_fileno(stream);"],
1425 modify_offset="true",
1426 msg_skip_fields=["stream"],
1427 msg_add_fields=["fbbcomm_builder_seek_in_inherited_set_fd(&ic_msg, fd);"])
1428
1429 # Intercept chdir and fchdir
1430 generate("int", ["chdir", "SYS_chdir"], "const char *pathname",
1431 msg_skip_fields=["pathname"],
1432 # Don't make pathname absolute, since the macro would calculate it after calling chdir
1433 msg_add_fields=["BUILDER_SET_CANONICAL(chdir, pathname);",
1434 "if (success) {",
1435 " char* getcwd_ret = get_ic_orig_getcwd()(ic_cwd, FB_PATH_BUFSIZE);",
1436 " (void) getcwd_ret;",
1437 " ic_cwd_len = strlen(ic_cwd);",
1438 "}"])
1439 generate("int", ["fchdir", "SYS_fchdir"], "int fd",
1440 after_lines=["if (success) {",
1441 " char* getcwd_ret = get_ic_orig_getcwd()(ic_cwd, FB_PATH_BUFSIZE);",
1442 " (void) getcwd_ret;",
1443 " ic_cwd_len = strlen(ic_cwd);",
1444 "}"])
1445
1446 # Intercept the chmod family
1447 generate("int", ["chmod", "SYS_chmod"] + (["__chmod"] if target == "darwin" else []), "const char *pathname, mode_t mode",
1448 msg="fchmodat",
1449 msg_skip_fields=["pathname"],
1450 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fchmodat, pathname);"])
1451 generate("int", "lchmod", "const char *pathname, mode_t mode",
1452 msg="fchmodat",
1453 msg_skip_fields=["pathname"],
1454 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fchmodat, pathname);",
1455 "fbbcomm_builder_fchmodat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);"])
1456 generate("int", "fchmodat", "int fd, const char *pathname, mode_t mode, int flags",
1457 msg="fchmodat",
1458 msg_skip_fields=["pathname"],
1459 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fchmodat, fd, pathname);"])
1460 # Note: SYS_fchmodat doesn't have a flags parameter
1461 generate("int", "SYS_fchmodat", "int fd, const char *pathname, mode_t mode",
1462 msg="fchmodat",
1463 msg_skip_fields=["pathname"],
1464 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fchmodat, fd, pathname);",
1465 "fbbcomm_builder_fchmodat_set_flags(&ic_msg, 0);"])
1466 generate("int", ["fchmod", "SYS_fchmod"] + (["__fchmod"] if target == "darwin" else []), "int fd, mode_t mode",
1467 msg="fchmodat")
1468
1469 # Intercept the chown family
1470 # FIXME SYS_chown32, SYS_lchown32, SYS_fchown32
1471 generate("int", ["chown", "SYS_chown"], "const char *pathname, uid_t owner, gid_t group",
1472 msg="fchownat",
1473 msg_skip_fields=["pathname"],
1474 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fchownat, pathname);"])
1475 generate("int", ["lchown", "SYS_lchown"] + (["__lchown"] if target == "darwin" else []), "const char *pathname, uid_t owner, gid_t group",
1476 msg="fchownat",
1477 msg_skip_fields=["pathname"],
1478 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fchownat, pathname);",
1479 "fbbcomm_builder_fchownat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);"])
1480 generate("int", ["fchownat", "SYS_fchownat"], "int fd, const char *pathname, uid_t owner, gid_t group, int flags",
1481 msg="fchownat",
1482 msg_skip_fields=["pathname"],
1483 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fchownat, fd, pathname);"])
1484 generate("int", ["fchown", "SYS_fchown"], "int fd, uid_t owner, gid_t group",
1485 msg="fchownat")
1486
1487 # Intercept the link, symlink and readlink families
1488 generate("int", ["link", "SYS_link"], "const char *oldpath, const char *newpath",
1489 msg_skip_fields = ["oldpath", "newpath"],
1490 msg_add_fields = ["BUILDER_SET_ABSOLUTE_CANONICAL(link, oldpath);",
1491 "BUILDER_SET_ABSOLUTE_CANONICAL(link, newpath);"])
1492 generate("int", ["linkat", "SYS_linkat"], "int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags",
1493 msg_skip_fields = ["oldpath", "newpath"],
1494 msg_add_fields = ["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(link, olddirfd, oldpath);",
1495 "BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(link, newdirfd, newpath);"],
1496 msg="link")
1497 generate("int", ["symlink", "SYS_symlink"], "const char *target, const char *newpath",
1498 msg_skip_fields = ["newpath"],
1499 msg_add_fields = ["BUILDER_SET_ABSOLUTE_CANONICAL(symlink, newpath);"])
1500 generate("int", ["symlinkat", "SYS_symlinkat"], "const char *target, int newdirfd, const char *newpath",
1501 msg_skip_fields = ["newpath"],
1502 msg_add_fields = ["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(symlink, newdirfd, newpath);"],
1503 msg="symlink")
1504
1505 generate("ssize_t", ["readlink", "SYS_readlink"], "const char *pathname, char *buf, size_t bufsiz",
1506 tpl="readlink",
1507 msg_skip_fields=["pathname", "buf"],
1508 msg_add_fields = ["BUILDER_SET_ABSOLUTE_CANONICAL(readlink, pathname);"])
1509 generate("ssize_t", "__readlink_chk", "const char *pathname, char *buf, size_t bufsiz, size_t fortify_size",
1510 tpl="readlink",
1511 msg="readlink",
1512 msg_skip_fields=["pathname", "buf", "fortify_size"],
1513 msg_add_fields = ["BUILDER_SET_ABSOLUTE_CANONICAL(readlink, pathname);"])
1514 generate("ssize_t", ["readlinkat", "SYS_readlinkat"], "int dirfd, const char *pathname, char *buf, size_t bufsiz",
1515 tpl="readlink",
1516 msg="readlink",
1517 msg_skip_fields=["pathname", "buf"],
1518 msg_add_fields = ["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(readlink, dirfd, pathname);"])
1519 generate("ssize_t", "__readlinkat_chk", "int dirfd, const char *pathname, char *buf, size_t bufsiz, size_t fortify_size",
1520 tpl="readlink",
1521 msg="readlink",
1522 msg_skip_fields=["pathname", "buf", "fortify_size"],
1523 msg_add_fields = ["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(readlink, dirfd, pathname);"])
1524 # FIXME realpath
1525
1526 # Intercept the stat family
1527 # FIXME SYS_oldstat, SYS_oldlstat, SYS_oldfstat, SYS_osf_*stat*
1528 # mysterious hacks prior to glibc 2.33
1529 generate("int", "__xstat", "int ver, const char *pathname, struct stat *stat_buf",
1530 platforms=["linux"],
1531 msg="fstatat",
1532 msg_skip_fields=["ver", "pathname", "stat_buf"],
1533 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1534 "if (success) {",
1535 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1536 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1537 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1538 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1539 "}"])
1540 generate("int", "__xstat64", "int ver, const char *pathname, struct stat64 *stat_buf",
1541 platforms=['linux'],
1542 msg="fstatat",
1543 msg_skip_fields=["ver", "pathname", "stat_buf"],
1544 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1545 "if (success) {",
1546 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1547 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1548 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1549 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1550 "}"])
1551 generate("int", "__lxstat", "int ver, const char *pathname, struct stat *stat_buf",
1552 platforms=['linux'],
1553 msg="fstatat",
1554 msg_skip_fields=["ver", "pathname", "stat_buf"],
1555 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1556 "fbbcomm_builder_fstatat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);",
1557 "if (success) {",
1558 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1559 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1560 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1561 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1562 "}"])
1563 generate("int", "__lxstat64", "int ver, const char *pathname, struct stat64 *stat_buf",
1564 platforms=['linux'],
1565 msg="fstatat",
1566 msg_skip_fields=["ver", "pathname", "stat_buf"],
1567 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1568 "fbbcomm_builder_fstatat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);",
1569 "if (success) {",
1570 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1571 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1572 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1573 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1574 "}"])
1575 generate("int", "__fxstat", "int ver, int fd, struct stat *stat_buf",
1576 platforms=['linux'],
1577 msg="fstatat",
1578 msg_skip_fields=["ver", "stat_buf"],
1579 msg_add_fields=["if (success) {",
1580 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1581 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1582 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1583 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1584 "}"])
1585 generate("int", "__fxstat64", "int ver, int fd, struct stat64 *stat_buf",
1586 platforms=['linux'],
1587 msg="fstatat",
1588 msg_skip_fields=["ver", "stat_buf"],
1589 msg_add_fields=["if (success) {",
1590 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1591 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1592 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1593 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1594 "}"])
1595 generate("int", "__fxstatat", "int ver, int fd, const char *pathname, struct stat *stat_buf, int flags",
1596 platforms=['linux'],
1597 msg="fstatat",
1598 msg_skip_fields=["ver", "pathname", "stat_buf"],
1599 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fstatat, fd, pathname);",
1600 "if (success) {",
1601 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1602 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1603 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1604 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1605 "}"])
1606 generate("int", "__fxstatat64", "int ver, int fd, const char *pathname, struct stat64 *stat_buf, int flags",
1607 platforms=['linux'],
1608 msg="fstatat",
1609 msg_skip_fields=["ver", "pathname", "stat_buf"],
1610 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fstatat, fd, pathname);",
1611 "if (success) {",
1612 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1613 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1614 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1615 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1616 "}"])
1617 # cleaned up beginning with glibc 2.33
1618 generate("int", ["stat"] + (["__stat"] if target == "darwin" else []), "const char *pathname, struct stat *stat_buf",
1619 msg="fstatat",
1620 msg_skip_fields=["pathname", "stat_buf"],
1621 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1622 "if (success) {",
1623 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1624 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1625 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1626 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1627 "}"])
1628 generate("int", ["stat64", "SYS_stat64", "__stat64_time64"], "const char *pathname, struct stat64 *stat_buf",
1629 msg="fstatat",
1630 msg_skip_fields=["pathname", "stat_buf"],
1631 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1632 "if (success) {",
1633 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1634 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1635 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1636 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1637 "}"])
1638 generate("int", ["lstat"] + (["__lstat"] if target == "darwin" else []), "const char *pathname, struct stat *stat_buf",
1639 msg="fstatat",
1640 msg_skip_fields=["pathname", "stat_buf"],
1641 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1642 "fbbcomm_builder_fstatat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);",
1643 "if (success) {",
1644 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1645 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1646 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1647 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1648 "}"])
1649 generate("int", ["lstat64", "SYS_lstat64", "__lstat64_time64"], "const char *pathname, struct stat64 *stat_buf",
1650 msg="fstatat",
1651 msg_skip_fields=["pathname", "stat_buf"],
1652 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(fstatat, pathname);",
1653 "fbbcomm_builder_fstatat_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);",
1654 "if (success) {",
1655 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1656 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1657 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1658 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1659 "}"])
1660 generate("int", ["fstat", "SYS_newfstat"] + (["__fstat"] if target == "darwin" else []), "int fd, struct stat *stat_buf",
1661 msg="fstatat",
1662 msg_skip_fields=["stat_buf"],
1663 msg_add_fields=["if (success) {",
1664 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1665 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1666 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1667 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1668 "}"])
1669 for func_guard in [(["fstat64", "SYS_fstat64", "__fstat64_time64"], None),
1670 ("__fstat64", glibc_ge(2, 33))]:
1671 (func, ifdef_guard) = func_guard
1672 generate("int", func, "int fd, struct stat64 *stat_buf",
1673 ifdef_guard=ifdef_guard,
1674 msg="fstatat",
1675 msg_skip_fields=["stat_buf"],
1676 msg_add_fields=["if (success) {",
1677 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1678 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1679 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1680 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1681 "}"])
1682 generate("int", ["fstatat", "SYS_newfstatat"] + (["__fstatat"] if target == "darwin" else []), "int fd, const char *pathname, struct stat *stat_buf, int flags",
1683 msg="fstatat",
1684 msg_skip_fields=["pathname", "stat_buf"],
1685 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fstatat, fd, pathname);",
1686 "if (success) {",
1687 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1688 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1689 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1690 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1691 "}"])
1692 generate("int", ["fstatat64", "SYS_fstatat64", "__fstatat64_time64"], "int fd, const char *pathname, struct stat64 *stat_buf, int flags",
1693 msg="fstatat",
1694 msg_skip_fields=["pathname", "stat_buf"],
1695 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fstatat, fd, pathname);",
1696 "if (success) {",
1697 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, stat_buf->st_mode);",
1698 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, stat_buf->st_size);",
1699 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, stat64_mtim_sec_to_int64(stat_buf));",
1700 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, stat64_mtim_nsec_to_int64(stat_buf));",
1701 "}"])
1702 # since glibc 2.28
1703 for func_guard in [("SYS_statx", None), ("statx", glibc_ge(2, 28))]:
1704 (func, ifdef_guard) = func_guard
1705 generate("int", func, "int fd, const char *pathname, int flags, unsigned int mask, struct statx *statx_buf",
1706 ifdef_guard=ifdef_guard,
1707 # TODO(rbalint) have separate statx() message with mask also sent
1708 msg="fstatat",
1709 # Always query type, mode and size to let the supervisor have valid fields
1710 # Save original mask to check if mtime was requested by the application
1711 before_lines=["unsigned int original_mask = mask;",
1712 "mask |= STATX_TYPE | STATX_MODE | STATX_SIZE;"],
1713 msg_skip_fields=["pathname", "mask", "statx_buf"],
1714 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(fstatat, fd, pathname);",
1715 "if (success) {",
1716 " fbbcomm_builder_fstatat_set_st_mode(&ic_msg, statx_buf->stx_mode);",
1717 " fbbcomm_builder_fstatat_set_st_size(&ic_msg, statx_buf->stx_size);",
1718 " if (original_mask & STATX_MTIME) {",
1719 " fbbcomm_builder_fstatat_set_st_mtim_sec(&ic_msg, statx_mtim_sec_to_int64(statx_buf));",
1720 " fbbcomm_builder_fstatat_set_st_mtim_nsec(&ic_msg, statx_mtim_nsec_to_int64(statx_buf));",
1721 " }",
1722 # TODO(rbalint) handle when type and mode are not returned (e.g. because they are not requested by the intercepted application, just by the interceptor modifying the mask)
1723 "}"])
1724 # Treat isfdtype() as a fstat()
1725 generate("int", "isfdtype", "int fd, int fdtype",
1726 platforms=['linux'],
1727 msg="fstatat",
1728 msg_skip_fields=["fdtype"])
1729
1730 # Disable shortcutting on the statfs family
1731 # FIXME SYS_osf_*statfs*
1732 generate("int", ["ustat", "SYS_ustat"], "dev_t dev, struct ustat *ubuf",
1733 platforms=['linux'],
1734 msg="statfs",
1735 msg_skip_fields=["dev", "ubuf"])
1736 # Note: SYS_statfs64 is like statfs64() but also takes a size parameter.
1737 generate("int", "SYS_statfs64", "const char *pathname, size_t sz, struct statfs64 *buf",
1738 platforms=['linux'],
1739 msg="statfs",
1740 msg_skip_fields=["pathname", "sz", "buf"],
1741 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(statfs, pathname);"])
1742 generate("int", ["statfs", "SYS_statfs", "__statfs"], "const char *pathname, struct statfs *buf",
1743 platforms=['linux'],
1744 msg="statfs",
1745 msg_skip_fields=["pathname", "buf"],
1746 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(statfs, pathname);"])
1747 generate("int", "statfs64", "const char *pathname, struct statfs64 *buf",
1748 platforms=['linux'],
1749 msg="statfs",
1750 msg_skip_fields=["pathname", "buf"],
1751 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(statfs, pathname);"])
1752 # Note: SYS_fstatfs64 is like fstatfs64() but also takes a size parameter.
1753 generate("int", "SYS_fstatfs64", "int fd, size_t sz, struct statfs64 *buf",
1754 platforms=['linux'],
1755 msg="statfs",
1756 msg_skip_fields=["fd", "sz", "buf"])
1757 generate("int", ["fstatfs", "SYS_fstatfs"], "int fd, struct statfs *buf",
1758 platforms=['linux'],
1759 msg="statfs",
1760 msg_skip_fields=["fd", "buf"])
1761 generate("int", "fstatfs64", "int fd, struct statfs64 *buf",
1762 platforms=['linux'],
1763 msg="statfs",
1764 msg_skip_fields=["fd", "buf"])
1765 generate("int", "statvfs", "const char *pathname, struct statvfs *buf",
1766 platforms=['linux'],
1767 msg="statfs",
1768 msg_skip_fields=["pathname", "buf"],
1769 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(statfs, pathname);"])
1770 generate("int", "statvfs64", "const char *pathname, struct statvfs64 *buf",
1771 platforms=['linux'],
1772 msg="statfs",
1773 msg_skip_fields=["pathname", "buf"],
1774 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(statfs, pathname);"])
1775 generate("int", "fstatvfs", "int fd, struct statvfs *buf",
1776 platforms=['linux'],
1777 msg="statfs",
1778 msg_skip_fields=["fd", "buf"])
1779 generate("int", "fstatvfs64", "int fd, struct statvfs64 *buf",
1780 platforms=['linux'],
1781 msg="statfs",
1782 msg_skip_fields=["fd", "buf"])
1783
1784 # Intercept lockf */
1785 generate("int", "lockf", "int fd, int cmd, off_t len")
1786 generate("int", "lockf64", "int fd, int cmd, off64_t len",
1787 platforms=['linux'],
1788 msg="lockf")
1789
1790 # Intercept fcntl and fcntl64
1791 # The return value is selectively set from tpl_fcntl.c.jinja2 for certain commands.
1792 for func_guard in [(["fcntl", "SYS_fcntl64", "SYS_fcntl", "__fcntl", "__fcntl_time64"], None),
1793 ("fcntl64", glibc_ge(2, 28))]:
1794 (func, ifdef_guard) = func_guard
1795 generate("int", func, "int fd, int cmd, ...",
1796 ifdef_guard=ifdef_guard,
1797 msg="fcntl",
1798 tpl="fcntl")
1799 generate("int", ["__fcntl_nocancel", "fcntl$NOCANCEL"], "int fd, int cmd, ...",
1800 platforms=['darwin'],
1801 msg="fcntl",
1802 tpl="fcntl")
1803
1804 # Intercept ioctl - cmd is long in glibc, int in the Linux kernel
1805 generate("int", ["ioctl", "__ioctl_time64"] + (["__ioctl"] if target == "darwin" else []), "int fd, unsigned long cmd, ...",
1806 tpl="ioctl",
1807 send_ret_on_success=True)
1808 generate("int", "SYS_ioctl", "int fd, unsigned int cmd, ...",
1809 tpl="ioctl",
1810 msg="ioctl",
1811 send_ret_on_success=True)
1812
1813 # Intercept the dup family
1814 generate("int", ["dup", "SYS_dup"], "int oldfd",
1815 after_lines=["if (i_am_intercepting && success) copy_notify_on_read_write_state(ret, oldfd);"],
1816 send_ret_on_success=True)
1817 generate("int", ["dup2", "SYS_dup2"], "int oldfd, int newfd",
1818 tpl="dup2",
1819 msg="dup3")
1820 generate("int", "__dup2", "int oldfd, int newfd",
1821 platforms=['linux'],
1822 tpl="dup2",
1823 msg="dup3")
1824 generate("int", ["dup3", "SYS_dup3"], "int oldfd, int newfd, int flags",
1825 platforms=['linux'],
1826 tpl="dup2",
1827 msg="dup3")
1828
1829
1830 # Intercept access variants
1831 generate("int", ["access", "SYS_access"], "const char *pathname, int mode",
1832 msg="faccessat",
1833 msg_skip_fields=["pathname"],
1834 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(faccessat, pathname);"])
1835 generate("int", ["euidaccess", "eaccess"], "const char *pathname, int mode",
1836 platforms=['linux'],
1837 msg="faccessat",
1838 msg_skip_fields=["pathname"],
1839 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(faccessat, pathname);",
1840 "fbbcomm_builder_faccessat_set_flags(&ic_msg, AT_EACCESS);"])
1841 # SYS_faccessat doesn't take a flags parameter.
1842 # glibc's faccessat() corresponds to SYS_faccessat2 which takes an additional flags parameter.
1843 generate("int", "SYS_faccessat", "int dirfd, const char *pathname, int mode",
1844 msg="faccessat",
1845 msg_skip_fields=["pathname"],
1846 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(faccessat, dirfd, pathname);",
1847 "fbbcomm_builder_faccessat_set_flags(&ic_msg, 0);"])
1848 generate("int", ["faccessat", "SYS_faccessat2"], "int dirfd, const char *pathname, int mode, int flags",
1849 msg_skip_fields=["pathname"],
1850 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(faccessat, dirfd, pathname);"])
1851
1852 # Intercept the (l)utime family
1853 # FIXME SYS_osf_utimes, SYS_utimensat_time{32,64}, SYS_futimesat_time32
1854 generate("int", ["utime", "SYS_utime", "__utime64"], "const char *pathname, const struct utimbuf *times",
1855 msg_skip_fields=["pathname", "times"],
1856 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(utime, pathname);",
1857 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL);",
1858 "if (times != NULL) {",
1859 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, utimbuf_mtim_sec_to_int64(times));",
1860 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, 0);",
1861 "}"])
1862 generate("int", ["utimes", "SYS_utimes", "__utimes64"], "const char *pathname, const struct timeval " + ("times[2]" if target == 'linux' else "*times"),
1863 msg="utime",
1864 msg_skip_fields=["pathname", "times"],
1865 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(utime, pathname);",
1866 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL);",
1867 "if (times != NULL) {",
1868 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, timeval_array_mtim_sec_to_int64(times));",
1869 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, timeval_array_mtim_usec_to_int64_nsec(times));",
1870 "}"])
1871 generate("int", ["lutimes", "__lutimes64"], "const char *pathname, const struct timeval " + ("times[2]" if target == 'linux' else "*times"),
1872 msg="utime",
1873 msg_skip_fields=["pathname", "times"],
1874 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(utime, pathname);",
1875 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL);",
1876 "if (times != NULL) {",
1877 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, timeval_array_mtim_sec_to_int64(&(times[1])));",
1878 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, timeval_array_mtim_usec_to_int64_nsec(&(times[1])));",
1879 "}",
1880 "fbbcomm_builder_utime_set_flags(&ic_msg, AT_SYMLINK_NOFOLLOW);"])
1881 generate("int", ["utimensat", "__utimensat64"], "int dirfd, const char *pathname, const struct timespec times[2], int flags",
1882 msg="utime",
1883 msg_skip_fields=["pathname", "times"],
1884 msg_add_fields=["BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(utime, dirfd, pathname);",
1885 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL || timespec_array_mtim_nsec_to_int64(times) == UTIME_NOW);",
1886 "if (times != NULL && timespec_array_mtim_nsec_to_int64(times) != UTIME_NOW) {",
1887 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, timespec_array_mtim_sec_to_int64(times));",
1888 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, timespec_array_mtim_nsec_to_int64(times));",
1889 "}"])
1890 generate("int", "SYS_utimensat", "int dirfd, const char *pathname, const struct timespec times[2], int flags",
1891 msg="utime",
1892 msg_skip_fields=["pathname", "times"],
1893 msg_add_fields=["if (pathname) BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(utime, dirfd, pathname);",
1894 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL || timespec_array_mtim_nsec_to_int64(times) == UTIME_NOW);",
1895 "if (times != NULL && timespec_array_mtim_nsec_to_int64(times) != UTIME_NOW) {",
1896 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, timespec_array_mtim_sec_to_int64(times));",
1897 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, timespec_array_mtim_nsec_to_int64(times));",
1898 "}"])
1899 generate("int", ["futimesat", "SYS_futimesat", "__futimesat64"], "int dirfd, const char *pathname, const struct timeval times[2]",
1900 platforms=['linux'],
1901 msg="utime",
1902 msg_skip_fields=["pathname", "times"],
1903 msg_add_fields=["if (pathname) BUILDER_MAYBE_SET_ABSOLUTE_CANONICAL(utime, dirfd, pathname);",
1904 "fbbcomm_builder_utime_set_all_utime_now(&ic_msg, times == NULL);",
1905 "if (times != NULL) {",
1906 " fbbcomm_builder_utime_set_mtim_sec(&ic_msg, timeval_array_mtim_sec_to_int64(times));",
1907 " fbbcomm_builder_utime_set_mtim_nsec(&ic_msg, timeval_array_mtim_usec_to_int64_nsec(times));",
1908 "}"])
1909
1910 # Intercept the futime family
1911 generate("int", ["futimes", "__futimes64"], "int fd, const struct timeval " + ("times[2]" if target == 'linux' else "*times"),
1912 msg="futime",
1913 msg_skip_fields=["times"],
1914 msg_add_fields=["fbbcomm_builder_futime_set_all_utime_now(&ic_msg, times == NULL);",
1915 "if (times != NULL) {",
1916 " fbbcomm_builder_futime_set_mtim_sec(&ic_msg, timeval_array_mtim_sec_to_int64(times));",
1917 " fbbcomm_builder_futime_set_mtim_nsec(&ic_msg, timeval_array_mtim_usec_to_int64_nsec(times));",
1918 "}"])
1919 generate("int", ["futimens", "__futimens64"], "int fd, const struct timespec times[2]",
1920 msg="futime",
1921 msg_skip_fields=["times"],
1922 msg_add_fields=["fbbcomm_builder_futime_set_all_utime_now(&ic_msg, times == NULL || timespec_array_mtim_nsec_to_int64(times) == UTIME_NOW);",
1923 "if (times != NULL && timespec_array_mtim_nsec_to_int64(times) != UTIME_NOW) {",
1924 " fbbcomm_builder_futime_set_mtim_sec(&ic_msg, timespec_array_mtim_sec_to_int64(times));",
1925 " fbbcomm_builder_futime_set_mtim_nsec(&ic_msg, timespec_array_mtim_nsec_to_int64(times));",
1926 "}"])
1927
1928 # Intercept dlopen
1929 # The new library's constructor may generate intercepted calls.
1930 # Also note that dlopen() does not set errno, and we always want to notify the supervisor,
1931 # in send_msg_condition we have to skip the default exception on EINTR and EFAULT.
1932 generate("void *", "dlopen", "const char *filename, int flag",
1933 tpl="dlopen",
1934 send_msg_condition="filename && !(flag & RTLD_NOLOAD)",
1935 ack_condition="new_libs_count > 0",
1936 # msg_add_fields is set in the template
1937 msg_skip_fields=["filename", "error_no"])
1938 generate("void *", "dlmopen", "Lmid_t lmid, const char *filename, int flag",
1939 platforms=['linux'],
1940 tpl="dlopen",
1941 msg="dlopen",
1942 send_msg_condition="filename && !(flag & RTLD_NOLOAD)",
1943 ack_condition="new_libs_count > 0",
1944 # msg_add_fields is set in the template
1945 msg_skip_fields=["lmid", "filename", "error_no"])
1946
1947 # Intercept the pipe family
1948 generate("int", ["pipe", "SYS_pipe", "__pipe"], "int pipefd[2]",
1949 tpl="pipe",
1950 before_lines=["int flags = 0;"],
1951 after_lines=["if (i_am_intercepting && success) { clear_notify_on_read_write_state(pipefd[0]); clear_notify_on_read_write_state(pipefd[1]); }"],
1952 msg_skip_fields=["pipefd"],
1953 msg_add_fields=["if (success) {",
1954 " fbbcomm_builder_pipe_fds_set_fd0(&ic_msg, pipefd[0]);",
1955 " fbbcomm_builder_pipe_fds_set_fd1(&ic_msg, pipefd[1]);",
1956 "}"])
1957 generate("int", ["pipe2", "SYS_pipe2"], "int pipefd[2], int flags",
1958 platforms=['linux'],
1959 tpl="pipe",
1960 after_lines=["if (i_am_intercepting && success) { clear_notify_on_read_write_state(pipefd[0]); clear_notify_on_read_write_state(pipefd[1]); }"],
1961 msg_skip_fields=["pipefd"],
1962 msg_add_fields=["if (success) {",
1963 " fbbcomm_builder_pipe_fds_set_fd0(&ic_msg, pipefd[0]);",
1964 " fbbcomm_builder_pipe_fds_set_fd1(&ic_msg, pipefd[1]);",
1965 "}"])
1966
1967 # Intercept the truncate family
1968 generate("int", ["truncate64", "SYS_truncate64"], "const char *pathname, off64_t length",
1969 before_lines=["if (i_am_intercepting) maybe_send_pre_open(AT_FDCWD, pathname, O_WRONLY | O_TRUNC);"],
1970 platforms=['linux'],
1971 msg="truncate",
1972 msg_skip_fields=["pathname"],
1973 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(truncate, pathname);"])
1974 generate("int", ["truncate", "SYS_truncate"], "const char *pathname, off_t length",
1975 before_lines=["if (i_am_intercepting) maybe_send_pre_open(AT_FDCWD, pathname, O_WRONLY | O_TRUNC);"],
1976 msg_skip_fields=["pathname"],
1977 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(truncate, pathname);"])
1978 # For our purposes, ftruncate() is just like pwrite(): modifies the file's contents
1979 # in a way other than simply writing sequential data at the current offset.
1980 generate("int", ["ftruncate64", "SYS_ftruncate64"], "int fd, off64_t len",
1981 platforms=['linux'],
1982 tpl="write",
1983 is_pwrite="true",
1984 msg_skip_fields=["len"])
1985 generate("int", ["ftruncate", "SYS_ftruncate"], "int fd, off_t len",
1986 tpl="write",
1987 is_pwrite="true",
1988 msg_skip_fields=["len"])
1989
1990 # Intercept the fallocate() family
1991 generate("int", "posix_fallocate", "int fd, off_t offset, off_t len",
1992 platforms=['linux'],
1993 is_pwrite="true",
1994 msg_skip_fields=["offset", "len"],
1995 tpl="write")
1996 generate("int", "posix_fallocate64", "int fd, off64_t offset, off64_t len",
1997 platforms=['linux'],
1998 is_pwrite="true",
1999 msg_skip_fields=["offset", "len"],
2000 tpl="write")
2001 generate("int", ["fallocate", "SYS_fallocate"], "int fd, int mode, off_t offset, off_t len",
2002 platforms=['linux'],
2003 is_pwrite="true",
2004 msg_skip_fields=["mode", "offset", "len"],
2005 tpl="write")
2006 generate("int", "fallocate64", "int fd, int mode, off64_t offset, off64_t len",
2007 platforms=['linux'],
2008 is_pwrite="true",
2009 msg_skip_fields=["mode", "offset", "len"],
2010 tpl="write")
2011
2012 # Intercept the mkstemp family
2013 # Note: these update the pathname template in place.
2014 generate("int", ["mkstemp", "mkstemp64"], "char *pathname",
2015 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
2016 send_msg_on_error=False,
2017 msg="open",
2018 msg_skip_fields=["pathname"],
2019 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, O_RDWR | O_CREAT | O_EXCL);",
2020 "fbbcomm_builder_open_set_mode(&ic_msg, 0600);",
2021 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
2022 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"
2023 "fbbcomm_builder_open_set_tmp_file(&ic_msg, true);"],
2024 send_ret_on_success=True,
2025 ack_condition="true")
2026 generate("int", ["mkostemp", "mkostemp64"], "char *pathname, int flags",
2027 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
2028 send_msg_on_error=False,
2029 msg="open",
2030 msg_skip_fields=["pathname", "flags"],
2031 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, O_RDWR | O_CREAT | O_EXCL | (flags & (O_APPEND | O_CLOEXEC | O_SYNC)));",
2032 "fbbcomm_builder_open_set_mode(&ic_msg, 0600);",
2033 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
2034 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"
2035 "fbbcomm_builder_open_set_tmp_file(&ic_msg, true);"],
2036 send_ret_on_success=True,
2037 ack_condition="true")
2038 generate("int", ["mkstemps", "mkstemps64"], "char *pathname, int suffixlen",
2039 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
2040 send_msg_on_error=False,
2041 msg="open",
2042 msg_skip_fields=["pathname", "suffixlen"],
2043 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, O_RDWR | O_CREAT | O_EXCL);",
2044 "fbbcomm_builder_open_set_mode(&ic_msg, 0600);",
2045 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
2046 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"
2047 "fbbcomm_builder_open_set_tmp_file(&ic_msg, true);"],
2048 send_ret_on_success=True,
2049 ack_condition="true")
2050 generate("int", ["mkostemps", "mkostemps64"], "char *pathname, int suffixlen, int flags",
2051 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
2052 send_msg_on_error=False,
2053 msg="open",
2054 msg_skip_fields=["pathname", "suffixlen", "flags"],
2055 msg_add_fields=["fbbcomm_builder_open_set_flags(&ic_msg, O_RDWR | O_CREAT | O_EXCL | (flags & (O_APPEND | O_CLOEXEC | O_SYNC)));",
2056 "fbbcomm_builder_open_set_mode(&ic_msg, 0600);",
2057 "BUILDER_SET_ABSOLUTE_CANONICAL(open, pathname);",
2058 "fbbcomm_builder_open_set_pre_open_sent(&ic_msg, false);"
2059 "fbbcomm_builder_open_set_tmp_file(&ic_msg, true);"],
2060 send_ret_on_success=True,
2061 ack_condition="true")
2062 generate("char *", "mkdtemp", "char *pathname",
2063 send_msg_on_error=False,
2064 msg="mkdir",
2065 msg_skip_fields=["pathname"],
2066 msg_add_fields=["fbbcomm_builder_mkdir_set_mode(&ic_msg, 0700);",
2067 "BUILDER_SET_ABSOLUTE_CANONICAL(mkdir, pathname);",
2068 "fbbcomm_builder_mkdir_set_tmp_dir(&ic_msg, true);"],
2069 ack_condition="true")
2070 # FIXME needs support on the supervisor for starting to track an fd without knowing the backing file
2071 generate("FILE *", ["tmpfile", "tmpfile64"], "",
2072 tpl="once")
2073 # "Never use these functions"
2074 # FIXME Supporting them would require supervisor work, or two messages (exclusive open, then close)
2075 generate("char *", ["mktemp"]+ (["__mktemp"] if target == "linux" else []), "char *template",
2076 success="template[0] != '\\0'",
2077 msg_skip_fields=["template"],
2078 send_msg_on_error=False,
2079 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(mktemp, template);"],
2080 diagnostic_ignored = ["-Warray-parameter="])
2081 generate("char *", ["tmpnam"] + (["tmpnam_r"] if target == "linux" else []), "char *template",
2082 msg="mktemp",
2083 msg_skip_fields=["template"],
2084 send_msg_on_error=False,
2085 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(mktemp, template);"],
2086 diagnostic_ignored = ["-Warray-parameter="])
2087 generate("char *", ["tempnam"], "const char *dir, const char *pfx",
2088 tpl="once")
2089
2090 generate("int", ["kqueue"], "",
2091 platforms=["darwin"],
2092 send_ret_on_success=True)
2093
2094 # Disable shortcutting on chroot
2095 generate("int", ["chroot", "SYS_chroot"], "const char *path",
2096 tpl="once")
2097
2098 # Skip bridge between low and high level io
2099 skip("fileno", "dirfd")
2100
2101 # Skip directory reading
2102 skip("readdir", "readdir64", "readdir_r", "readdir64_r", "SYS_readdir", "rewinddir", "seekdir", "telldir")
2103 skip("getdents", "SYS_getdents", "getdents64", "SYS_getdents64", "getdirentries", "getdirentries64")
2104 # FIXME implement scandir(at)(64)
2105
2106 # Disable shortcutting on mknod
2107 # mysterious hacks prior to glibc 2.33 (also note the pointer "dev_t *")
2108 generate("int", "__xmknod", "int ver, const char *path, mode_t mode, dev_t *dev",
2109 platforms=["linux"],
2110 tpl="once")
2111 generate("int", "__xmknodat", "int ver, int dirfd, const char *path, mode_t mode, dev_t *dev",
2112 platforms=["linux"],
2113 tpl="once")
2114 # cleaned up beginning with glibc 2.33
2115 generate("int", ["mknod", "SYS_mknod"], "const char *path, mode_t mode, dev_t dev",
2116 tpl="once")
2117 generate("int", ["mknodat", "SYS_mknodat"], "int dirfd, const char *path, mode_t mode, dev_t dev",
2118 platforms=['linux'],
2119 tpl="once")
2120 generate("int", ["mknodat", "SYS_mknodat"], "int dirfd, const char *path, mode_t mode, dev_t dev",
2121 platforms=['darwin'],
2122 ifdef_guard=apple_ge(13, 0),
2123 tpl="once")
2124
2125 # Disable shortcutting on mkfifo
2126 generate("int", "mkfifo", "const char *pathname, mode_t mode",
2127 msg_skip_fields=["pathname"],
2128 msg_add_fields=["BUILDER_SET_ABSOLUTE_CANONICAL(mkfifo, pathname);"])
2129
2130 generate("int", "mkfifoat", "int dirfd, const char *pathname, mode_t mode",
2131 platforms=['linux'],
2132 tpl="once")
2133
2134 # Intercept the exit family.
2135 # - _exit() and _Exit() terminate the process immediately, no exit handlers are run.
2136 # So we need to modify the supervisor about the exit code and resource usage before execuing it.
2137 # - exit() calls the atexit() / on_exit() handlers first. We'll notify the supervisor using the
2138 # hopefully last on_exit() handler, which is our on_exit_handler() method.
2139 # - quick_exit() calls the at_quick_exit() handlers, which, similarly to the atexit() handlers,
2140 # do not receive the exit status. So notify the supervisor before calling this method, just like
2141 # for _exit().
2142 generate("void", ["exit"] + (["__exit"] if target == "darwin" else []), "int status",
2143 tpl="exit",
2144 no_saved_errno=True)
2145 generate("void", ["_exit", "_Exit", "SYS_exit"], "int status",
2146 tpl="_exit",
2147 no_saved_errno=True)
2148 generate("void", "quick_exit", "int status",
2149 platforms=['linux'],
2150 tpl="_exit",
2151 no_saved_errno=True)
2152 # No wrapper for exit_group() in glibc 2.30.
2153 skip("exit_group")
2154 generate("void", "SYS_exit_group", "int status",
2155 tpl="_exit")
2156
2157 # Intercept fork() and variants
2158 generate("pid_t", ["fork", "SYS_fork"], "",
2159 tpl="fork")
2160 # _Fork is glibc specific
2161 # TODO(rbalint) __fork is not intercepted on OS X because fork() also calls it and intercepting
2162 # only __fork hangs "debugging with trace markers and report generation" test
2163 generate("pid_t", ["__fork", "_Fork"], "",
2164 platforms=['linux'],
2165 tpl="_fork")
2166 generate("pid_t", ["vfork", "SYS_vfork", "__vfork"], "",
2167 ifdef_guard=glibc_ge(2, 34),
2168 tpl="_fork")
2169 # NOTE: Mapping to fork() breaks the ABI since the fork handlers were not supposed to run
2170 # OTOH the fork handlers notify the supervisor about the call.
2171 generate("pid_t", ["vfork", "SYS_vfork", "__vfork"], "",
2172 ifdef_guard=not_glibc_ge(2, 34),
2173 tpl="fork")
2174
2175 # Intercept system
2176 generate("int", "system", "const char *cmd",
2177 tpl="system")
2178
2179 # Intercept popen and pclose
2180 generate("FILE *", "popen", "const char *cmd, const char *type",
2181 tpl="popen")
2182 generate("int", "pclose", "FILE *stream",
2183 tpl="pclose",
2184 # Maybe we pclose() an fopen()ed file, in that case send the "close" message (from tpl_pclose.c.jinja2)
2185 # but don't send the "pclose" message. See #642 for more info.
2186 send_msg_condition="was_popened && (success || (errno != EINTR && errno != EFAULT))",
2187 msg_skip_fields=["stream"],
2188 msg_add_fields=["fbbcomm_builder_pclose_set_fd(&ic_msg, fd);"],
2189 send_ret_on_success=True,
2190 ack_condition="true")
2191
2192 # Intercept the posix_spawn family
2193 posix_spawn_params = "pid_t *pid, const char *file, " \
2194 + "const posix_spawn_file_actions_t *file_actions, " \
2195 + "const posix_spawnattr_t *attrp, " \
2196 + "char *const argv[], char *const envp[]"
2197 generate("int", ["posix_spawn", "posix_spawnp"] + (["__posix_spawn"] if target == "darwin" else []), posix_spawn_params,
2198 tpl="posix_spawn",
2199 success="ret == 0")
2200 generate("int", ["pidfd_spawn", "pidfd_spawnp"], posix_spawn_params,
2201 tpl="posix_spawn",
2202 ifdef_guard=glibc_ge(2, 39),
2203 success="ret == 0")
2204
2205 generate("int", ["posix_spawn_file_actions_init", "posix_spawn_file_actions_destroy"], "posix_spawn_file_actions_t *file_actions",
2206 tpl="posix_spawn_file_actions",
2207 success="ret == 0")
2208 generate("int", "posix_spawn_file_actions_addopen", "posix_spawn_file_actions_t *file_actions, int fd, const char *pathname, int flags, mode_t mode",
2209 tpl="posix_spawn_file_actions",
2210 success="ret == 0")
2211 generate("int", "posix_spawn_file_actions_addclose", "posix_spawn_file_actions_t *file_actions, int fd",
2212 tpl="posix_spawn_file_actions",
2213 success="ret == 0")
2214 generate("int", "posix_spawn_file_actions_addclosefrom_np", "posix_spawn_file_actions_t *file_actions, int lowfd",
2215 platforms=['linux'],
2216 tpl="posix_spawn_file_actions",
2217 success="ret == 0")
2218 generate("int", "posix_spawn_file_actions_adddup2", "posix_spawn_file_actions_t *file_actions, int oldfd, int newfd",
2219 tpl="posix_spawn_file_actions",
2220 success="ret == 0")
2221 generate("int", "posix_spawn_file_actions_addchdir_np", "posix_spawn_file_actions_t *file_actions, const char *pathname",
2222 platforms=['linux'],
2223 ifdef_guard=glibc_ge(2, 29),
2224 tpl="posix_spawn_file_actions",
2225 success="ret == 0")
2226 generate("int", "posix_spawn_file_actions_addfchdir_np", "posix_spawn_file_actions_t *file_actions, int fd",
2227 platforms=['linux'],
2228 ifdef_guard=glibc_ge(2, 29),
2229 tpl="posix_spawn_file_actions",
2230 success="ret == 0")
2231 generate("int", "posix_spawn_file_actions_addinherit_np", "posix_spawn_file_actions_t *file_actions, int filedes",
2232 platforms=['darwin'],
2233 tpl="posix_spawn_file_actions",
2234 success="ret == 0")
2235 generate("int", "posix_spawn_file_actions_addtcsetpgrp_np", "posix_spawn_file_actions_t *file_actions, int filedes",
2236 platforms=['linux'],
2237 ifdef_guard=glibc_ge(2, 35),
2238 tpl="posix_spawn_file_actions",
2239 success="ret == 0")
2240
2241 # Insert a trace marker for clone and pthread_create
2242 generate("int", ["clone", "__clone"], "int (*fn)(void *), void *stack, int flags, void *arg, ...",
2243 platforms=['linux'],
2244 tpl="clone")
2245 # Don't bother spelling out SYS_clone's parameters, it's heavily architecture dependent
2246 generate("int", "SYS_clone", "...",
2247 platforms=['linux'],
2248 tpl="clone")
2249 generate("int", "pthread_create", "pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg",
2250 tpl="pthread_create")
2251
2252 # Intercept the wait family
2253 # Need to wait for the supervisor to ACK that it has processed what the child had done
2254 # Lock only for the communication, see #338
2255 # FIXME SYS_osf_old_wait, SYS_osf_wait4, SYS_osf_waitid
2256 generate("pid_t", ["wait"], "int *wstatus",
2257 success="ret > 0",
2258 before_lines=["int wstatus_fallback;",
2259 "if (!wstatus) wstatus = &wstatus_fallback;"],
2260 global_lock='after',
2261 send_msg_on_error=False,
2262 msg="wait",
2263 msg_skip_fields=["wstatus"],
2264 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2265 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2266 ack_condition="true")
2267 generate("pid_t", ["__wait"], "int *wstatus",
2268 platforms=['linux'],
2269 success="ret > 0",
2270 before_lines=["int wstatus_fallback;",
2271 "if (!wstatus) wstatus = &wstatus_fallback;"],
2272 global_lock='after',
2273 send_msg_on_error=False,
2274 msg="wait",
2275 msg_skip_fields=["wstatus"],
2276 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2277 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2278 ack_condition="true")
2279 generate("pid_t", ["waitpid", "SYS_waitpid"], "pid_t pid, int *wstatus, int options",
2280 global_lock='after',
2281 before_lines=["int wstatus_fallback;",
2282 "if (!wstatus) wstatus = &wstatus_fallback;"],
2283 success="ret > 0",
2284 send_msg_on_error=False,
2285 send_msg_condition="success && !WIFSTOPPED(*wstatus) && !WIFCONTINUED(*wstatus)",
2286 msg="wait",
2287 msg_skip_fields=["pid", "wstatus", "options"],
2288 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2289 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2290 ack_condition="true")
2291 generate("pid_t", ["__waitpid"], "pid_t pid, int *wstatus, int options",
2292 platforms=['linux'],
2293 global_lock='after',
2294 before_lines=["int wstatus_fallback;",
2295 "if (!wstatus) wstatus = &wstatus_fallback;"],
2296 success="ret > 0",
2297 send_msg_on_error=False,
2298 send_msg_condition="success && !WIFSTOPPED(*wstatus) && !WIFCONTINUED(*wstatus)",
2299 msg="wait",
2300 msg_skip_fields=["pid", "wstatus", "options"],
2301 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2302 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2303 ack_condition="true")
2304 generate("pid_t", ["wait3", "__wait3_time64"], "int *wstatus, int options, struct rusage *rusage",
2305 platforms=["linux"], # OS X Libc calls wait4 which is also intercepted
2306 global_lock='after',
2307 before_lines=["int wstatus_fallback;",
2308 "if (!wstatus) wstatus = &wstatus_fallback;"],
2309 success="ret > 0",
2310 send_msg_on_error=False,
2311 send_msg_condition="success && !WIFSTOPPED(*wstatus) && !WIFCONTINUED(*wstatus)",
2312 msg="wait",
2313 msg_skip_fields=["wstatus", "options", "rusage"],
2314 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2315 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2316 ack_condition="true")
2317 # __wait4 hangs the tests on MacOS
2318 generate("pid_t", ["wait4", "SYS_wait4", "__wait4_time64"], "pid_t pid, int *wstatus, int options, struct rusage *rusage",
2319 global_lock='after',
2320 before_lines=["int wstatus_fallback;",
2321 "if (!wstatus) wstatus = &wstatus_fallback;"],
2322 success="ret > 0",
2323 send_msg_on_error=False,
2324 send_msg_condition="success && !WIFSTOPPED(*wstatus) && !WIFCONTINUED(*wstatus)",
2325 msg="wait",
2326 msg_skip_fields=["pid", "wstatus", "options", "rusage"],
2327 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, ret);",
2328 "fbbcomm_builder_wait_set_wstatus(&ic_msg, *wstatus);"],
2329 ack_condition="true")
2330 # Note: See BUGS in the waitid(2) manual page for the infop==NULL case.
2331 generate("int", "waitid", "idtype_t idtype, id_t id, siginfo_t *infop, int options",
2332 global_lock='after',
2333 before_lines=["siginfo_t infop_fallback;",
2334 "if (!infop) infop = &infop_fallback;"],
2335 send_msg_on_error=False,
2336 send_msg_condition="success && !((options & WNOHANG) && (infop->si_pid == 0)) && infop->si_code != CLD_STOPPED && infop->si_code != CLD_TRAPPED && infop->si_code != CLD_CONTINUED",
2337 msg="wait",
2338 msg_skip_fields=["idtype", "id", "infop", "options"],
2339 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, infop->si_pid);",
2340 "fbbcomm_builder_wait_set_si_code(&ic_msg, infop->si_code);",
2341 "fbbcomm_builder_wait_set_si_status(&ic_msg, infop->si_status);"],
2342 ack_condition="true")
2343 # Note: Takes one more parameter than the libc wrapper.
2344 generate("int", "SYS_waitid", "idtype_t idtype, id_t id, siginfo_t *infop, int options, struct rusage *usage",
2345 global_lock='after',
2346 before_lines=["siginfo_t infop_fallback;",
2347 "if (!infop) infop = &infop_fallback;"],
2348 send_msg_on_error=False,
2349 send_msg_condition="success && !((options & WNOHANG) && (infop->si_pid == 0)) && infop->si_code != CLD_STOPPED && infop->si_code != CLD_TRAPPED && infop->si_code != CLD_CONTINUED",
2350 msg="wait",
2351 msg_skip_fields=["idtype", "id", "infop", "options", "usage"],
2352 msg_add_fields=["fbbcomm_builder_wait_set_pid(&ic_msg, infop->si_pid);",
2353 "fbbcomm_builder_wait_set_si_code(&ic_msg, infop->si_code);",
2354 "fbbcomm_builder_wait_set_si_status(&ic_msg, infop->si_status);"],
2355 ack_condition="true")
2356
2357 # Intercept the exec family
2358 # FIXME SYS_osf_execve
2359 generate("int", ["execl", "execlp"], "const char *file, const char *arg, ...",
2360 tpl="exec")
2361 # Note: execlpe exists on some systems, but not in glibc
2362 generate("int", "execle", "const char *file, const char *arg, ...",
2363 tpl="exec")
2364 generate("int", ["execv", "execvp"], "const char *file, char *const argv[]",
2365 tpl="exec")
2366 generate("int", ["execve", "SYS_execve"] + (["__execve"] if target == "darwin" else []), "const char *file, char *const argv[], char *const envp[]",
2367 tpl="exec")
2368 generate("int", "execvpe", "const char *file, char *const argv[], char *const envp[]",
2369 platforms=['linux'],
2370 tpl="exec")
2371 # Note: execveat() appeared in glibc 2.34.
2372 generate("int", ["execveat", "SYS_execveat"], "int dirfd, const char *file, char *const argv[], char *const envp[], int flags",
2373 platforms=['linux'],
2374 tpl="exec")
2375 generate("int", "fexecve", "int fd, char *const argv[], char *const envp[]",
2376 platforms=['linux'],
2377 tpl="exec")
2378
2379 # Signal handling
2380 # FIXME SYS_osf_signal, SYS_osf_old_sigsetmask, SYS_osf_old_sigaction
2381 generate("sighandler_t", ["signal", "sigset"], "int signum, " + ("sighandler_t" if target == 'linux' else 'sig_t') + " handler",
2382 tpl="signal",
2383 success="1")
2384 generate("long int", ["SYS_signal"], "int signum, sighandler_t handler",
2385 tpl="signal",
2386 success="1")
2387 generate("int", ["sigaction", "SYS_sigaction"], "int signum, const struct sigaction *act, struct sigaction *oldact",
2388 tpl="signal")
2389 # TODO(rbalint) intercepting __sigaction breaks "parallel make" test on OS X
2390 generate("int", ["__sigaction"], "int signum, const struct sigaction *act, struct sigaction *oldact",
2391 platforms=['linux'],
2392 tpl="signal")
2393
2394 # futex() doesn't have a glibc wrapper, pthread_mutex_[un]lock() maps into syscall(SYS_futex, ...).
2395 # Don't need to notify the supervisor about these, stay out of the way as much as possible.
2396 generate("long", "SYS_futex", "uint32_t *uaddr, int futex_op, uint32_t val, const struct timespec *timeout, uint32_t *uaddr2, uint32_t val3",
2397 tpl="marker_only")
2398
2399 # OS X's dyld sets up thread local variables after initializing shared libraries
2400 # causing crashes when the variables are accessed too early.
2401 # Luckily dyld's RuntimeState::setUpTLVs() calls pthread_key_create right before setting up
2402 # thread local variables and the only reason for intercepting pthread_key_create is waiting for that
2403 # and marking thread locals usable.
2404 generate("int", "pthread_key_create", "pthread_key_t *key, void (*destr_function) (void *)",
2405 platforms=['darwin'],
2406 before_lines=["#if !defined(FB_ALWAYS_USE_THREAD_LOCAL)",
2407 "thread_locals_usable = true;",
2408 "#endif"],
2409 tpl="marker_only")
2410
2411 # Skip the getcwd family: The initial working directory is part of the fingerprint
2412 skip("getcwd", "__getcwd_chk", "SYS_getcwd", "getwd", "__getwd_chk", "get_current_dir_name")
2413
2414 # Time and alarm handling: These are fine, no action required
2415 # TODO(rbalint) those may affect output if the process measures time that way
2416 # usually the calls can be ignored
2417 skip("clock", "clock_getres", "SYS_clock_getres", "SYS_clock_getres_time64", "clock_getcpuclockid")
2418 skip("sleep", "usleep", "nanosleep", "SYS_nanosleep", "clock_nanosleep", "SYS_clock_nanosleep", "SYS_clock_nanosleep_time64")
2419 skip("pause", "SYS_pause", "alarm", "SYS_alarm", "ualarm", "getitimer", "SYS_getitimer", "setitimer", "SYS_setitimer")
2420 skip("timer_create", "SYS_timer_create", "timer_delete", "SYS_timer_delete", "timer_getoverrun", "SYS_timer_getoverrun")
2421 skip("timer_settime", "SYS_timer_settime", "SYS_timer_settime_time64", "timer_gettime", "SYS_timer_gettime", "SYS_timer_gettime_time64")
2422
2423 # Getting high entropy randomness should disable shortcutting
2424 generate("ssize_t", ["getrandom", "SYS_getrandom"], "void* buf, size_t buflen, unsigned int flags",
2425 platforms=['linux'],
2426 msg_skip_fields = ["buf", "buflen"])
2427 generate("int", "getentropy", "void* buffer, size_t length",
2428 msg="getrandom",
2429 msg_skip_fields = ["buffer", "length"],
2430 # implemented by glibc as getrandom(..., 0)
2431 msg_add_fields=["fbbcomm_builder_getrandom_set_flags(&ic_msg, 0);"])
2432 generate("uint32_t", "arc4random", "",
2433 msg="getrandom",
2434 # implemented by glibc as getrandom(..., 0)
2435 msg_add_fields=["fbbcomm_builder_getrandom_set_flags(&ic_msg, 0);"],
2436 success="true",
2437 send_ret_on_success=False,
2438 no_saved_errno=True)
2439 generate("void", "arc4random_buf", "void* buf, size_t nbytes",
2440 msg="getrandom",
2441 msg_skip_fields=["buf", "nbytes"],
2442 # implemented by glibc as getrandom(..., 0)
2443 msg_add_fields=["fbbcomm_builder_getrandom_set_flags(&ic_msg, 0);"],
2444 success="true",
2445 send_ret_on_success=False,
2446 no_saved_errno=True)
2447 generate("uint32_t", "arc4random_uniform", "uint32_t upper_bound",
2448 msg="getrandom",
2449 msg_skip_fields = ["upper_bound"],
2450 # implemented by glibc as getrandom(..., 0)
2451 msg_add_fields=["fbbcomm_builder_getrandom_set_flags(&ic_msg, 0);"],
2452 success="true",
2453 send_ret_on_success=False,
2454 no_saved_errno=True)
2455
2456 # Querying current time - probably disable shortcutting, let the supervisor decide
2457 generate("time_t", ["time", "SYS_time", "__time64"], "time_t *loc",
2458 msg="clock_gettime",
2459 tpl="once")
2460 generate("int", "ftime", "struct timeb *tp",
2461 msg="clock_gettime",
2462 tpl="once")
2463 # sys/time.h declares the funcion with void *tz and not matching that generates an error
2464 generate("int", ["gettimeofday", "__gettimeofday"], "struct timeval *tv, struct timezone *tz",
2465 platforms=['linux'],
2466 ifdef_guard=not_glibc_ge(2, 31),
2467 msg="clock_gettime",
2468 tpl="once")
2469 generate("int", ["gettimeofday", "__gettimeofday"], "struct timeval *tv, void *tz",
2470 platforms=['darwin'],
2471 msg="clock_gettime",
2472 tpl="once")
2473 generate("int", ["gettimeofday", "__gettimeofday"], "struct timeval *tv, void *tz",
2474 platforms=['linux'],
2475 ifdef_guard=glibc_ge(2, 31),
2476 msg="clock_gettime",
2477 tpl="once")
2478 generate("int", "__gettimeofday64", "struct timeval *tv, void *tz",
2479 platforms=['linux'],
2480 ifdef_guard=glibc_ge(2, 34),
2481 msg="clock_gettime",
2482 tpl="once")
2483 generate("int", "SYS_gettimeofday", "struct timeval *tv, void *tz",
2484 msg="clock_gettime",
2485 tpl="once")
2486 # FIXME SYS_clock_gettime64
2487 generate("int", ["clock_gettime", "SYS_clock_gettime64", "SYS_clock_gettime", "__clock_gettime64"], "clockid_t clk_id, struct timespec *tp",
2488 msg="clock_gettime",
2489 tpl="once")
2490 generate("int", "__clock_gettime", "clockid_t clk_id, struct timespec *tp",
2491 platforms=['linux'],
2492 msg="clock_gettime",
2493 tpl="once")
2494 # FIXME SYS_osf_ntp_gettime
2495 generate("int", ["ntp_gettime", "ntp_gettimex", "__ntp_gettime64", "__ntp_gettimex64"], "struct ntptimeval *ntv",
2496 platforms=['linux'],
2497 msg="clock_gettime",
2498 tpl="once")
2499
2500 # Disable setting the time
2501 generate("int", "stime", "const time_t *t",
2502 platforms=['linux'],
2503 tpl="once")
2504 generate("int", ["settimeofday", "SYS_settimeofday", "__settimeofday64"] + (["__settimeofday"] if target == "darwin" else []), "const struct timeval *tv, const struct timezone *tz",
2505 tpl="once")
2506 # FIXME SYS_clock_settime64
2507 generate("int", ["clock_settime", "SYS_clock_settime64", "SYS_clock_settime", "__clock_settime64"], "clockid_t clk_id, const struct timespec *tp",
2508 tpl="once")
2509 # FIXME SYS_osf_adjtime, SYS_old_adjtimex
2510 generate("int", ["adjtime", "__adjtime64"], "const struct timeval *delta, struct timeval *olddelta",
2511 tpl="once")
2512 generate("int", ["adjtimex", "SYS_adjtimex", "__adjtimex"], "struct timex *buf",
2513 platforms=['linux'],
2514 tpl="once")
2515 # FIXME SYS_clock_adjtime64
2516 generate("int", ["clock_adjtime", "SYS_clock_adjtime64", "SYS_clock_adjtime", "__clock_adjtime64"], "clockid_t clk_id, struct timex *buf",
2517 platforms=['linux'],
2518 tpl="once")
2519 # FIXME SYS_osf_ntp_adjtime, SYS_osf_utc_adjtime
2520 generate("int", "ntp_adjtime", "struct timex *buf",
2521 platforms=['linux'],
2522 tpl="once")
2523
2524 # Skip scheduling parameters
2525 skip("nice", "SYS_nice", "getpriority", "SYS_getpriority", "setpriority", "SYS_setpriority")
2526 skip("getrusage", "SYS_getrusage", "profil", "SYS_profil", "acct", "SYS_acct")
2527
2528 # Process stuff
2529 skip("prctl", "SYS_prctl")
2530 skip("getpid", "SYS_getpid", "getppid", "SYS_getppid", "gettid", "SYS_gettid")
2531 skip("getpgrp", "SYS_getpgrp", "getpgid", "__getpgid", "SYS_getpgid", "setpgrp", "SYS_setpgrp", "setpgid", "SYS_setpgid")
2532 skip("getsid", "SYS_getsid", "setsid", "SYS_setsid")
2533 skip("SYS_capget")
2534 generate("int", ["pidfd_open", "SYS_pidfd_open"], "pid_t pid, unsigned int flags",
2535 platforms=['linux'],
2536 tpl="once")
2537 # can be skipped, since pidfd_open already disables shortcutting
2538 skip("pidfd_getfd", "SYS_pidfd_getfd", "pidfd_send_signal", "SYS_pidfd_send_signal")
2539 generate("mode_t", ["umask", "SYS_umask"], "mode_t mask",
2540 success="true",
2541 send_ret_on_success=True,
2542 send_msg_on_error=False)
2543 # Note: getumask is gone since glibc 2.24
2544
2545 # Pretend that seccomp() is not implemented.
2546 # This allows interception of a few commands that otherwise would use seccomp sandboxing, such as man
2547 # and friends.
2548 generate("int", "SYS_seccomp", "unsigned int operation, unsigned int flags, void *args",
2549 msg_skip_fields=["operation", "flags", "args"],
2550 msg="seccomp",
2551 call_orig_lines=["if (i_am_intercepting) {",
2552 " (void)operation; (void)flags; (void)args;",
2553 " errno = EINVAL; ret = -1;"
2554 "} else {",
2555 " ret = ic_orig_SYS_seccomp(operation, flags, args);",
2556 "}",
2557 ])
2558
2559 generate("int", ["getrlimit", "__getrlimit", "getrlimit64", "SYS_getrlimit"], "int resource, struct rlimit *rlim",
2560 msg="rlimit",
2561 msg_skip_fields=["rlim"],
2562 msg_add_fields=["fbbcomm_builder_rlimit_set_get(&ic_msg, true);",
2563 "fbbcomm_builder_rlimit_set_set(&ic_msg, false);"])
2564 generate("int", ["setrlimit", "setrlimit64", "SYS_setrlimit"] + ["__setrlimit"] if target == "darwin" else [], "int resource, const struct rlimit *rlim",
2565 msg="rlimit",
2566 msg_skip_fields=["rlim"],
2567 msg_add_fields=["fbbcomm_builder_rlimit_set_get(&ic_msg, false);",
2568 "fbbcomm_builder_rlimit_set_set(&ic_msg, true);"])
2569 generate("int", ["prlimit", "prlimit64", "SYS_prlimit64"], "pid_t pid, int resource, const struct rlimit64 *new_limit, struct rlimit64 *old_limit",
2570 platforms=['linux'],
2571 msg="rlimit",
2572 msg_skip_fields=["new_limit", "old_limit"],
2573 msg_add_fields=["fbbcomm_builder_rlimit_set_get(&ic_msg, old_limit != NULL);",
2574 "fbbcomm_builder_rlimit_set_set(&ic_msg, new_limit != NULL);"])
2575
2576 # User and group stuff
2577 # FIXME shall we notify the supervisor?
2578 # FIXME SYS_*32
2579 skip("getuid", "SYS_getuid", "getgid", "SYS_getgid", "geteuid", "SYS_geteuid", "getegid", "SYS_getegid")
2580 skip("getresuid", "SYS_getresuid", "getresgid", "SYS_getresgid")
2581 skip("getgroups", "SYS_getgroups", "group_member")
2582 generate("int", ["setuid", "SYS_setuid", "seteuid"], "uid_t uid",
2583 tpl="once")
2584 generate("int", ["setgid", "SYS_setgid", "setegid"], "gid_t gid",
2585 tpl="once")
2586 generate("int", ["setreuid", "SYS_setreuid"] + (["__setreuid"] if target == "darwin" else []), "uid_t uid, uid_t euid",
2587 tpl="once")
2588 generate("int", ["setregid", "SYS_setregid"] + (["__setregid"] if target == "darwin" else []), "gid_t gid, gid_t egid",
2589 tpl="once")
2590 generate("int", ["setresuid", "SYS_setresuid"], "uid_t uid, uid_t euid, uid_t suid",
2591 platforms=['linux'],
2592 tpl="once")
2593 generate("int", ["setresgid", "SYS_setresgid"], "gid_t gid, gid_t egid, gid_t sgid",
2594 platforms=['linux'],
2595 tpl="once")
2596 generate("int", ["setgroups", "SYS_setgroups"], ("size_t" if target == 'linux' else "int") + " size, const gid_t *list",
2597 tpl="once")
2598
2599 # Shells
2600 skip("getusershell", "endusershell", "setusershell")
2601
2602 # FIXME What to do with the getpwent() family?
2603
2604 # Tty stuff
2605 skip("ttyname", "ttyname_r", "ttyslot", "isatty", "vhangup", "SYS_vhangup", "getpass")
2606 skip("tcgetpgrp", "tcsetpgrp", "getlogin", "getlogin_r"," __getlogin_r_chk")
2607 skip("ctermid", "cuserid")
2608 generate("int", ["setlogin"] + (["__setlogin"] if target == "darwin" else []), "const char *name",
2609 tpl="once")
2610
2611 # Revoke - glibc function exists, no manpage. Does it work?
2612 skip("revoke")
2613
2614 # System stuff
2615 skip("daemon")
2616 skip("getpagesize", "__getpagesize", "SYS_getpagesize")
2617 skip("getdtablesize", "SYS_getdtablesize")
2618
2619 # Memory management
2620 skip("malloc", "calloc", "realloc", "free", "brk", "SYS_brk", "sbrk")
2621 # FIXME intercept mmap
2622 skip("mmap", "SYS_mmap", "SYS_mmap2", "mremap", "SYS_mremap", "munmap", "SYS_munmap")
2623
2624 # Hostname stuff - report gethostname, getdomainname, gethostid.
2625 # The supervisor might decide whether to disable shortcutting, or ignore this difference
2626 generate("int", ["gethostname", "SYS_gethostname"], "char *name, size_t len")
2627 generate("int", "__gethostname_chk", "char *name, size_t len, size_t fortify_size",
2628 tpl="once")
2629 generate("int", "getdomainname", "char *name, " + ("size_t" if target == 'linux' else "int") + " len",
2630 tpl="once")
2631 generate("int", "__getdomainname_chk", "char *name, size_t len, size_t fortify_size",
2632 tpl="once")
2633 # FIXME SYS_osf_gethostid
2634 generate("long", "gethostid", "",
2635 tpl="once")
2636
2637 # Disable shortcutting on sethostname, setdomainname, sethostid
2638 generate("int", ["sethostname", "SYS_sethostname"], "const char *name, " + ("size_t" if target == 'linux' else "int") + " len",
2639 tpl="once")
2640 generate("int", ["setdomainname", "SYS_setdomainname"], "const char *name, " + ("size_t" if target == 'linux' else "int") + " len",
2641 tpl="once")
2642 # FIXME SYS_osf_gethostid
2643 generate("int" if target == 'linux' else "void", "sethostid", "long hostid",
2644 tpl="once")
2645
2646 generate("int", ["socket", "SYS_socket"]+ (["__socket"] if target == "linux" else []), "int domain, int type, int protocol",
2647 after_lines=["if (i_am_intercepting && success) clear_notify_on_read_write_state(ret);"],
2648 send_ret_on_success=True)
2649 generate("int", ["connect", "SYS_connect", "__connect"], "int sockfd, const struct sockaddr *addr, socklen_t addrlen",
2650 msg_skip_fields=["addr", "addrlen"],
2651 msg_add_fields=["if (((struct sockaddr*)addr)->sa_family == AF_UNIX) {",
2652 " const char * const sun_path = ((struct sockaddr_un*)addr)->sun_path;",
2653 " fbbcomm_builder_connect_set_addr_with_length(&ic_msg, sun_path, strnlen(sun_path, sizeof(((struct sockaddr_un*)addr)->sun_path)));",
2654 "}"],
2655 )
2656 generate("int", ["bind", "SYS_bind"] + (["__bind"] if target == "darwin" else []), "int sockfd, const struct sockaddr *addr, socklen_t addrlen",
2657 msg_skip_fields=["addr", "addrlen"],
2658 msg_add_fields=["fbbcomm_builder_bind_set_sa_family(&ic_msg, addr->sa_family);",
2659 "if (((struct sockaddr*)addr)->sa_family == AF_UNIX) {",
2660 " const char * const sun_path = ((struct sockaddr_un*)addr)->sun_path;",
2661 " fbbcomm_builder_bind_set_sa_data_with_length(&ic_msg, sun_path, strnlen(sun_path, sizeof(((struct sockaddr_un*)addr)->sun_path)));",
2662 "}"])
2663
2664 generate("int", ["listen", "SYS_listen"] + (["__listen"] if target == "darwin" else []), "int sockfd, int backlog",
2665 tpl="once")
2666 generate("int", ["socketpair", "SYS_socketpair"] + (["__socketpair"] if target == "darwin" else []), "int domain, int type, int protocol, int sv[2]",
2667 after_lines=["if (i_am_intercepting && success) {",
2668 " clear_notify_on_read_write_state(sv[0]);",
2669 " clear_notify_on_read_write_state(sv[1]);",
2670 "}"],
2671 msg_skip_fields=["sv"],
2672 msg_add_fields=["if (success) {",
2673 " fbbcomm_builder_socketpair_set_fd0(&ic_msg, sv[0]);",
2674 " fbbcomm_builder_socketpair_set_fd1(&ic_msg, sv[1]);",
2675 "}"])
2676 generate("int", "SYS_socketcall", "int call, unsigned long *args",
2677 tpl="once")
2678
2679 # Intercept the pathconf family
2680 # FIXME Sometimes a retval == -1 does not denote error. Same for sysconf.
2681 # FIXME SYS_osf_[f]pathconf
2682 generate("long", "pathconf", "const char *path, int name",
2683 send_ret_on_success=True)
2684 generate("long", "fpathconf", "int fd, int name",
2685 send_ret_on_success=True)
2686
2687 # Intercept sysconf
2688 # FIXME Sometimes a retval == -1 does not denote error. Same for pathconf.
2689 generate("long", ["__sysconf"], "int name",
2690 platforms=["linux"],
2691 send_ret_on_success=True)
2692 generate("long", ["sysconf"], "int name",
2693 send_ret_on_success=True)
2694
2695 # Intercept syscall
2696 # FIXME What does syscall(SYS_syscall, ...) do? :)
2697 generate("long", "syscall", "long number, ...",
2698 platforms=["linux"],
2699 tpl="syscall",
2700 send_ret_on_success=True,
2701 ack_condition="true")
2702 generate("int", ["syscall", "__syscall"], "int number, ...",
2703 platforms=["darwin"],
2704 tpl="syscall",
2705 send_ret_on_success=True,
2706 ack_condition="true")
2707
2708 generate("int", ["__mac_syscall", "SYS___mac_syscall"], "char* policy, int call, user_addr_t arg",
2709 platforms=["darwin"],
2710 msg="mac_syscall",
2711 msg_skip_fields=["arg"],
2712 send_ret_on_success=True)
2713
2714 # FIXME This is temporary only, until intercepting confstr is implemented:
2715 #generate("size_t", "confstr", "int name, char *buf, size_t len")
2716 #generate("size_t", "__confstr_chk", "int name, char *buf, size_t len, size_t fortify_size")
2717 skip("confstr", "__confstr_chk")
2718
2719 # Network
2720 # FIXME use the "once" template instead: we need to know it can't be shortcut
2721 skip("getsockname", "SYS_getsockname", "getpeername", "SYS_getpeername")
2722 skip("getsockopt", "SYS_getsockopt", "setsockopt", "SYS_setsockopt")
2723 skip("accept", "SYS_accept", "accept4", "SYS_accept4", "shutdown", "SYS_shutdown", "sockatmark")
2724
2725 # Mounts
2726 skip("setmntent", "getmntent", "getmntent_r", "addmntent", "endmntent", "hasmntopt")
2727
2728 # FIXME Implement intercepting these:
2729 # mkdir(at)
2730 # freopen(64) - looks complicated
2731
2732 # locale related ones:
2733 # (bind)textdomain, *gettext, {set,use,new}locale, nl_langinfo, iconv*
2734 # iswalpha, towlower and friends (the locale dependant ones)
2735 # strcasecmp
2736 # strerror*, strsignal, strftime
2737 # *_l
2738
2739
2740 # Finally rename the output files.
2741 for gen in set(libc_outputs + syscall_outputs):
2742 os.rename(outdir + "/gen_" + gen + tmpsuffix, outdir + "/gen_" + gen)