repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
systemd-main/src/udev/udevadm-test.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright © 2003-2004 Greg Kroah-Hartman <[email protected]> */ #include <errno.h> #include <getopt.h> #include <signal.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <sys/signalfd.h> #include <unistd.h> #include "sd-device.h" #include "device-private.h" #include "device-util.h" #include "path-util.h" #include "string-util.h" #include "strxcpyx.h" #include "udev-builtin.h" #include "udev-event.h" #include "udevadm-util.h" #include "udevadm.h" static sd_device_action_t arg_action = SD_DEVICE_ADD; static ResolveNameTiming arg_resolve_name_timing = RESOLVE_NAME_EARLY; static const char *arg_syspath = NULL; static int help(void) { printf("%s test [OPTIONS] DEVPATH\n\n" "Test an event run.\n\n" " -h --help Show this help\n" " -V --version Show package version\n" " -a --action=ACTION|help Set action string\n" " -N --resolve-names=early|late|never When to resolve names\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "action", required_argument, NULL, 'a' }, { "resolve-names", required_argument, NULL, 'N' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, {} }; int r, c; while ((c = getopt_long(argc, argv, "a:N:Vh", options, NULL)) >= 0) switch (c) { case 'a': r = parse_device_action(optarg, &arg_action); if (r < 0) return log_error_errno(r, "Invalid action '%s'", optarg); if (r == 0) return 0; break; case 'N': arg_resolve_name_timing = resolve_name_timing_from_string(optarg); if (arg_resolve_name_timing < 0) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--resolve-names= must be early, late or never"); break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } arg_syspath = argv[optind]; if (!arg_syspath) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "syspath parameter missing."); return 1; } int test_main(int argc, char *argv[], void *userdata) { _cleanup_(udev_rules_freep) UdevRules *rules = NULL; _cleanup_(udev_event_freep) UdevEvent *event = NULL; _cleanup_(sd_device_unrefp) sd_device *dev = NULL; const char *cmd; sigset_t mask, sigmask_orig; void *val; int r; log_set_max_level(LOG_DEBUG); r = parse_argv(argc, argv); if (r <= 0) return r; printf("This program is for debugging only, it does not run any program\n" "specified by a RUN key. It may show incorrect results, because\n" "some values may be different, or not available at a simulation run.\n" "\n"); assert_se(sigprocmask(SIG_SETMASK, NULL, &sigmask_orig) >= 0); udev_builtin_init(); r = udev_rules_load(&rules, arg_resolve_name_timing); if (r < 0) { log_error_errno(r, "Failed to read udev rules: %m"); goto out; } r = find_device_with_action(arg_syspath, arg_action, &dev); if (r < 0) { log_error_errno(r, "Failed to open device '%s': %m", arg_syspath); goto out; } /* don't read info from the db */ device_seal(dev); event = udev_event_new(dev, 0, NULL, LOG_DEBUG); assert_se(sigfillset(&mask) >= 0); assert_se(sigprocmask(SIG_SETMASK, &mask, &sigmask_orig) >= 0); udev_event_execute_rules(event, -1, 60 * USEC_PER_SEC, SIGKILL, NULL, rules); FOREACH_DEVICE_PROPERTY(dev, key, value) printf("%s=%s\n", key, value); ORDERED_HASHMAP_FOREACH_KEY(val, cmd, event->run_list) { char program[UDEV_PATH_SIZE]; bool truncated; (void) udev_event_apply_format(event, cmd, program, sizeof(program), false, &truncated); if (truncated) log_warning("The command '%s' is truncated while substituting into '%s'.", program, cmd); printf("run: '%s'\n", program); } r = 0; out: udev_builtin_exit(); return r; }
5,076
32.622517
113
c
null
systemd-main/src/udev/udevadm-util.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <errno.h> #include "alloc-util.h" #include "bus-error.h" #include "bus-util.h" #include "device-private.h" #include "path-util.h" #include "udevadm-util.h" #include "unit-name.h" static int find_device_from_unit(const char *unit_name, sd_device **ret) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_free_ char *unit_path = NULL, *syspath = NULL; int r; if (!unit_name_is_valid(unit_name, UNIT_NAME_PLAIN)) return -EINVAL; if (unit_name_to_type(unit_name) != UNIT_DEVICE) return -EINVAL; r = bus_connect_system_systemd(&bus); if (r < 0) { _cleanup_free_ char *path = NULL; log_debug_errno(r, "Failed to open connection to systemd, using unit name as syspath: %m"); r = unit_name_to_path(unit_name, &path); if (r < 0) return log_debug_errno(r, "Failed to convert \"%s\" to a device path: %m", unit_name); return sd_device_new_from_path(ret, path); } unit_path = unit_dbus_path_from_name(unit_name); if (!unit_path) return -ENOMEM; r = sd_bus_get_property_string( bus, "org.freedesktop.systemd1", unit_path, "org.freedesktop.systemd1.Device", "SysFSPath", &error, &syspath); if (r < 0) return log_debug_errno(r, "Failed to get SysFSPath= dbus property for %s: %s", unit_name, bus_error_message(&error, r)); return sd_device_new_from_syspath(ret, syspath); } int find_device(const char *id, const char *prefix, sd_device **ret) { assert(id); assert(ret); if (sd_device_new_from_path(ret, id) >= 0) return 0; if (prefix && !path_startswith(id, prefix)) { _cleanup_free_ char *path = NULL; path = path_join(prefix, id); if (!path) return -ENOMEM; if (sd_device_new_from_path(ret, path) >= 0) return 0; } /* if a path is provided, then it cannot be a unit name. Let's return earlier. */ if (is_path(id)) return -ENODEV; /* Check if the argument looks like a device unit name. */ return find_device_from_unit(id, ret); } int find_device_with_action(const char *id, sd_device_action_t action, sd_device **ret) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; int r; assert(id); assert(ret); assert(action >= 0 && action < _SD_DEVICE_ACTION_MAX); r = find_device(id, "/sys", &dev); if (r < 0) return r; r = device_read_uevent_file(dev); if (r < 0) return r; r = device_set_action(dev, action); if (r < 0) return r; *ret = TAKE_PTR(dev); return 0; } int parse_device_action(const char *str, sd_device_action_t *action) { sd_device_action_t a; assert(str); assert(action); if (streq(str, "help")) { dump_device_action_table(); return 0; } a = device_action_from_string(str); if (a < 0) return a; *action = a; return 1; }
3,665
28.328
110
c
null
systemd-main/src/udev/udevadm-verify.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "conf-files.h" #include "constants.h" #include "log.h" #include "parse-argument.h" #include "pretty-print.h" #include "stat-util.h" #include "static-destruct.h" #include "strv.h" #include "udev-rules.h" #include "udevadm.h" static ResolveNameTiming arg_resolve_name_timing = RESOLVE_NAME_EARLY; static char *arg_root = NULL; static bool arg_summary = true; static bool arg_style = true; STATIC_DESTRUCTOR_REGISTER(arg_root, freep); static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("udevadm", "8", &link); if (r < 0) return log_oom(); printf("%s verify [OPTIONS] [FILE...]\n" "\n%sVerify udev rules files.%s\n\n" " -h --help Show this help\n" " -V --version Show package version\n" " -N --resolve-names=early|never When to resolve names\n" " --root=PATH Operate on an alternate filesystem root\n" " --no-summary Do not show summary\n" " --no-style Ignore style issues\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_ROOT = 0x100, ARG_NO_SUMMARY, ARG_NO_STYLE, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { "resolve-names", required_argument, NULL, 'N' }, { "root", required_argument, NULL, ARG_ROOT }, { "no-summary", no_argument, NULL, ARG_NO_SUMMARY }, { "no-style", no_argument, NULL, ARG_NO_STYLE }, {} }; int r, c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "hVN:", options, NULL)) >= 0) switch (c) { case 'h': return help(); case 'V': return print_version(); case 'N': arg_resolve_name_timing = resolve_name_timing_from_string(optarg); if (arg_resolve_name_timing < 0) return log_error_errno(arg_resolve_name_timing, "--resolve-names= takes \"early\" or \"never\""); /* * In the verifier "late" has the effect of "never", * and "never" would generate irrelevant diagnostics, * so map "never" to "late". */ if (arg_resolve_name_timing == RESOLVE_NAME_NEVER) arg_resolve_name_timing = RESOLVE_NAME_LATE; break; case ARG_ROOT: r = parse_path_argument(optarg, /* suppress_root= */ true, &arg_root); if (r < 0) return r; break; case ARG_NO_SUMMARY: arg_summary = false; break; case ARG_NO_STYLE: arg_style = false; break; case '?': return -EINVAL; default: assert_not_reached(); } if (arg_root && optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Combination of --root= and FILEs is not supported."); return 1; } static int verify_rules_file(UdevRules *rules, const char *fname) { UdevRuleFile *file; int r; r = udev_rules_parse_file(rules, fname, /* extra_checks = */ true, &file); if (r < 0) return log_error_errno(r, "Failed to parse rules file %s: %m", fname); if (r == 0) /* empty file. */ return 0; unsigned issues = udev_rule_file_get_issues(file); unsigned mask = (1U << LOG_ERR) | (1U << LOG_WARNING); if (issues & mask) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s: udev rules check failed.", fname); if (arg_style && (issues & (1U << LOG_NOTICE))) return log_warning_errno(SYNTHETIC_ERRNO(EINVAL), "%s: udev rules have style issues.", fname); return 0; } static int verify_rules_filelist(UdevRules *rules, char **files, size_t *fail_count, size_t *success_count, bool walk_dirs); static int verify_rules_dir(UdevRules *rules, const char *dir, size_t *fail_count, size_t *success_count) { int r; _cleanup_strv_free_ char **files = NULL; assert(rules); assert(dir); assert(fail_count); assert(success_count); r = conf_files_list(&files, ".rules", NULL, 0, dir); if (r < 0) return log_error_errno(r, "Failed to enumerate rules files: %m"); return verify_rules_filelist(rules, files, fail_count, success_count, /* walk_dirs */ false); } static int verify_rules_filelist(UdevRules *rules, char **files, size_t *fail_count, size_t *success_count, bool walk_dirs) { int r, rv = 0; assert(rules); assert(files); assert(fail_count); assert(success_count); STRV_FOREACH(fp, files) { if (walk_dirs && is_dir(*fp, /* follow = */ true) > 0) r = verify_rules_dir(rules, *fp, fail_count, success_count); else { r = verify_rules_file(rules, *fp); if (r < 0) ++(*fail_count); else ++(*success_count); } if (r < 0 && rv >= 0) rv = r; } return rv; } static int verify_rules(UdevRules *rules, char **files) { size_t fail_count = 0, success_count = 0; int r; assert(rules); assert(files); r = verify_rules_filelist(rules, files, &fail_count, &success_count, /* walk_dirs */ true); if (arg_summary) printf("\n%s%zu udev rules files have been checked.%s\n" " Success: %zu\n" "%s Fail: %zu%s\n", ansi_highlight(), fail_count + success_count, ansi_normal(), success_count, fail_count > 0 ? ansi_highlight_red() : "", fail_count, fail_count > 0 ? ansi_normal() : ""); return r; } int verify_main(int argc, char *argv[], void *userdata) { _cleanup_(udev_rules_freep) UdevRules *rules = NULL; int r; r = parse_argv(argc, argv); if (r <= 0) return r; rules = udev_rules_new(arg_resolve_name_timing); if (!rules) return -ENOMEM; if (optind == argc) { const char* const* rules_dirs = STRV_MAKE_CONST(CONF_PATHS("udev/rules.d")); _cleanup_strv_free_ char **files = NULL; r = conf_files_list_strv(&files, ".rules", arg_root, 0, rules_dirs); if (r < 0) return log_error_errno(r, "Failed to enumerate rules files: %m"); if (arg_root && strv_isempty(files)) return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No rules files found in %s.", arg_root); return verify_rules(rules, files); } return verify_rules(rules, strv_skip(argv, optind)); }
8,500
34.869198
125
c
null
systemd-main/src/udev/udevadm-wait.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <getopt.h> #include <unistd.h> #include "sd-event.h" #include "alloc-util.h" #include "chase.h" #include "device-monitor-private.h" #include "device-util.h" #include "errno-util.h" #include "event-util.h" #include "fd-util.h" #include "fs-util.h" #include "inotify-util.h" #include "parse-util.h" #include "path-util.h" #include "static-destruct.h" #include "string-table.h" #include "strv.h" #include "udev-util.h" #include "udevadm.h" typedef enum WaitUntil { WAIT_UNTIL_INITIALIZED, WAIT_UNTIL_ADDED, WAIT_UNTIL_REMOVED, _WAIT_UNTIL_MAX, _WAIT_UNTIL_INVALID = -EINVAL, } WaitUntil; static WaitUntil arg_wait_until = WAIT_UNTIL_INITIALIZED; static usec_t arg_timeout_usec = USEC_INFINITY; static bool arg_settle = false; static char **arg_devices = NULL; STATIC_DESTRUCTOR_REGISTER(arg_devices, strv_freep); static const char * const wait_until_table[_WAIT_UNTIL_MAX] = { [WAIT_UNTIL_INITIALIZED] = "initialized", [WAIT_UNTIL_ADDED] = "added", [WAIT_UNTIL_REMOVED] = "removed", }; DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(wait_until, WaitUntil); static int check_device(const char *path) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; int r; assert(path); if (arg_wait_until == WAIT_UNTIL_REMOVED) { r = laccess(path, F_OK); if (r == -ENOENT) return true; if (r < 0) return r; return false; } r = sd_device_new_from_path(&dev, path); if (r == -ENODEV) return false; if (r < 0) return r; if (arg_wait_until == WAIT_UNTIL_INITIALIZED) return sd_device_get_is_initialized(dev); return true; } static bool check(void) { int r; if (arg_settle) { r = udev_queue_is_empty(); if (r == 0) return false; if (r < 0) log_warning_errno(r, "Failed to check if udev queue is empty, assuming empty: %m"); } STRV_FOREACH(p, arg_devices) { r = check_device(*p); if (r <= 0) { if (r < 0) log_warning_errno(r, "Failed to check if device \"%s\" is %s, assuming not %s: %m", *p, wait_until_to_string(arg_wait_until), wait_until_to_string(arg_wait_until)); return false; } } return true; } static int check_and_exit(sd_event *event) { int r; assert(event); if (check()) { r = sd_event_exit(event, 0); if (r < 0) return r; return 1; } return 0; } static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) { const char *name; int r; assert(monitor); assert(device); if (device_for_action(device, SD_DEVICE_REMOVE) != (arg_wait_until == WAIT_UNTIL_REMOVED)) return 0; if (arg_wait_until == WAIT_UNTIL_REMOVED) /* On removed event, the received device may not contain enough information. * Let's unconditionally check all requested devices are removed. */ return check_and_exit(sd_device_monitor_get_event(monitor)); /* For other events, at first check if the received device matches with the requested devices, * to avoid calling check() so many times within a short time. */ r = sd_device_get_sysname(device, &name); if (r < 0) { log_device_warning_errno(device, r, "Failed to get sysname of received device, ignoring: %m"); return 0; } STRV_FOREACH(p, arg_devices) { const char *s; if (!path_startswith(*p, "/sys")) continue; r = path_find_last_component(*p, false, NULL, &s); if (r < 0) { log_warning_errno(r, "Failed to extract filename from \"%s\", ignoring: %m", *p); continue; } if (r == 0) continue; if (strneq(s, name, r)) return check_and_exit(sd_device_monitor_get_event(monitor)); } r = sd_device_get_devname(device, &name); if (r < 0) { if (r != -ENOENT) log_device_warning_errno(device, r, "Failed to get devname of received device, ignoring: %m"); return 0; } if (path_strv_contains(arg_devices, name)) return check_and_exit(sd_device_monitor_get_event(monitor)); FOREACH_DEVICE_DEVLINK(device, link) if (path_strv_contains(arg_devices, link)) return check_and_exit(sd_device_monitor_get_event(monitor)); return 0; } static int setup_monitor(sd_event *event, MonitorNetlinkGroup group, const char *description, sd_device_monitor **ret) { _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL; int r; assert(event); assert(ret); r = device_monitor_new_full(&monitor, group, /* fd = */ -1); if (r < 0) return r; (void) sd_device_monitor_set_receive_buffer_size(monitor, 128*1024*1024); r = sd_device_monitor_attach_event(monitor, event); if (r < 0) return r; r = sd_device_monitor_set_description(monitor, description); if (r < 0) return r; r = sd_device_monitor_start(monitor, device_monitor_handler, NULL); if (r < 0) return r; *ret = TAKE_PTR(monitor); return 0; } static int on_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata) { return check_and_exit(sd_event_source_get_event(s)); } static int setup_inotify(sd_event *event) { _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL; int r; assert(event); if (!arg_settle) return 0; r = sd_event_add_inotify(event, &s, "/run/udev" , IN_CREATE | IN_DELETE, on_inotify, NULL); if (r < 0) return r; r = sd_event_source_set_description(s, "inotify-event-source"); if (r < 0) return r; return sd_event_source_set_floating(s, true); } static int setup_timer(sd_event *event) { _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL; int r; assert(event); if (arg_timeout_usec == USEC_INFINITY) return 0; r = sd_event_add_time_relative(event, &s, CLOCK_BOOTTIME, arg_timeout_usec, 0, NULL, INT_TO_PTR(-ETIMEDOUT)); if (r < 0) return r; r = sd_event_source_set_description(s, "timeout-event-source"); if (r < 0) return r; return sd_event_source_set_floating(s, true); } static int reset_timer(sd_event *e, sd_event_source **s); static int on_periodic_timer(sd_event_source *s, uint64_t usec, void *userdata) { static unsigned counter = 0; sd_event *e; int r; assert(s); e = sd_event_source_get_event(s); /* Even if all devices exists, we try to wait for uevents to be emitted from kernel. */ if (check()) counter++; else counter = 0; if (counter >= 2) { log_debug("All requested devices popped up without receiving kernel uevents."); return sd_event_exit(e, 0); } r = reset_timer(e, &s); if (r < 0) log_warning_errno(r, "Failed to reset periodic timer event source, ignoring: %m"); return 0; } static int reset_timer(sd_event *e, sd_event_source **s) { return event_reset_time_relative(e, s, CLOCK_BOOTTIME, 250 * USEC_PER_MSEC, 0, on_periodic_timer, NULL, 0, "periodic-timer-event-source", false); } static int setup_periodic_timer(sd_event *event) { _cleanup_(sd_event_source_unrefp) sd_event_source *s = NULL; int r; assert(event); r = reset_timer(event, &s); if (r < 0) return r; /* Set the lower priority than device monitor, to make uevents always dispatched first. */ r = sd_event_source_set_priority(s, SD_EVENT_PRIORITY_NORMAL + 1); if (r < 0) return r; return sd_event_source_set_floating(s, true); } static int help(void) { printf("%s wait [OPTIONS] DEVICE [DEVICE…]\n\n" "Wait for devices or device symlinks being created.\n\n" " -h --help Print this message\n" " -V --version Print version of the program\n" " -t --timeout=SEC Maximum time to wait for the device\n" " --initialized=BOOL Wait for devices being initialized by systemd-udevd\n" " --removed Wait for devices being removed\n" " --settle Also wait for all queued events being processed\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_INITIALIZED = 0x100, ARG_REMOVED, ARG_SETTLE, }; static const struct option options[] = { { "timeout", required_argument, NULL, 't' }, { "initialized", required_argument, NULL, ARG_INITIALIZED }, { "removed", no_argument, NULL, ARG_REMOVED }, { "settle", no_argument, NULL, ARG_SETTLE }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, {} }; int c, r; while ((c = getopt_long(argc, argv, "t:hV", options, NULL)) >= 0) switch (c) { case 't': r = parse_sec(optarg, &arg_timeout_usec); if (r < 0) return log_error_errno(r, "Failed to parse -t/--timeout= parameter: %s", optarg); break; case ARG_INITIALIZED: r = parse_boolean(optarg); if (r < 0) return log_error_errno(r, "Failed to parse --initialized= parameter: %s", optarg); arg_wait_until = r ? WAIT_UNTIL_INITIALIZED : WAIT_UNTIL_ADDED; break; case ARG_REMOVED: arg_wait_until = WAIT_UNTIL_REMOVED; break; case ARG_SETTLE: arg_settle = true; break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } if (optind >= argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Too few arguments, expected at least one device path or device symlink."); arg_devices = strv_copy(argv + optind); if (!arg_devices) return log_oom(); return 1; /* work to do */ } int wait_main(int argc, char *argv[], void *userdata) { _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *udev_monitor = NULL, *kernel_monitor = NULL; _cleanup_(sd_event_unrefp) sd_event *event = NULL; int r; r = parse_argv(argc, argv); if (r <= 0) return r; STRV_FOREACH(p, arg_devices) { path_simplify(*p); if (!path_is_safe(*p)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Device path cannot contain \"..\"."); if (!is_device_path(*p)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Specified path \"%s\" does not start with \"/dev/\" or \"/sys/\".", *p); } /* Check before configuring event sources, as devices may be already initialized. */ if (check()) return 0; r = sd_event_default(&event); if (r < 0) return log_error_errno(r, "Failed to initialize sd-event: %m"); r = setup_timer(event); if (r < 0) return log_error_errno(r, "Failed to set up timeout: %m"); r = setup_inotify(event); if (r < 0) return log_error_errno(r, "Failed to set up inotify: %m"); r = setup_monitor(event, MONITOR_GROUP_UDEV, "udev-uevent-monitor-event-source", &udev_monitor); if (r < 0) return log_error_errno(r, "Failed to set up udev uevent monitor: %m"); if (arg_wait_until == WAIT_UNTIL_ADDED) { /* If --initialized=no is specified, it is not necessary to wait uevents for the specified * devices to be processed by udevd. Hence, let's listen on the kernel's uevent stream. Then, * we may be able to finish this program earlier when udevd is very busy. * Note, we still need to also setup udev monitor, as this may be invoked with a devlink * (e.g. /dev/disk/by-id/foo). In that case, the devlink may not exist when we received a * uevent from kernel, as the udevd may not finish to process the uevent yet. Hence, we need * to wait until the event is processed by udevd. */ r = setup_monitor(event, MONITOR_GROUP_KERNEL, "kernel-uevent-monitor-event-source", &kernel_monitor); if (r < 0) return log_error_errno(r, "Failed to set up kernel uevent monitor: %m"); /* This is a workaround for issues #24360 and #24450. * For some reasons, the kernel sometimes does not emit uevents for loop block device on * attach. Hence, without the periodic timer, no event source for this program will be * triggered, and this will be timed out. * Theoretically, inotify watch may be better, but this program typically expected to run in * a short time. Hence, let's use the simpler periodic timer event source here. */ r = setup_periodic_timer(event); if (r < 0) return log_error_errno(r, "Failed to set up periodic timer: %m"); } /* Check before entering the event loop, as devices may be initialized during setting up event sources. */ if (check()) return 0; r = sd_event_loop(event); if (r == -ETIMEDOUT) return log_error_errno(r, "Timed out for waiting devices being %s.", wait_until_to_string(arg_wait_until)); if (r < 0) return log_error_errno(r, "Event loop failed: %m"); return 0; }
15,878
33.594771
120
c
null
systemd-main/src/udev/udevadm.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <stdio.h> #include "alloc-util.h" #include "main-func.h" #include "pretty-print.h" #include "process-util.h" #include "selinux-util.h" #include "string-util.h" #include "udev-util.h" #include "udevadm.h" #include "udevd.h" #include "verbs.h" static int help(void) { static const char *const short_descriptions[][2] = { { "info", "Query sysfs or the udev database" }, { "trigger", "Request events from the kernel" }, { "settle", "Wait for pending udev events" }, { "control", "Control the udev daemon" }, { "monitor", "Listen to kernel and udev events" }, { "test", "Test an event run" }, { "test-builtin", "Test a built-in command" }, { "verify", "Verify udev rules files" }, { "wait", "Wait for device or device symlink" }, { "lock", "Lock a block device" }, }; _cleanup_free_ char *link = NULL; size_t i; int r; r = terminal_urlify_man("udevadm", "8", &link); if (r < 0) return log_oom(); printf("%s [--help] [--version] [--debug] COMMAND [COMMAND OPTIONS]\n\n" "Send control commands or test the device manager.\n\n" "Commands:\n", program_invocation_short_name); for (i = 0; i < ELEMENTSOF(short_descriptions); i++) printf(" %-12s %s\n", short_descriptions[i][0], short_descriptions[i][1]); printf("\nSee the %s for details.\n", link); return 0; } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "debug", no_argument, NULL, 'd' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, {} }; int c; assert(argc >= 0); assert(argv); /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long() * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */ optind = 0; while ((c = getopt_long(argc, argv, "+dhV", options, NULL)) >= 0) switch (c) { case 'd': log_set_max_level(LOG_DEBUG); break; case 'h': return help(); case 'V': return print_version(); case '?': return -EINVAL; default: assert_not_reached(); } return 1; /* work to do */ } static int version_main(int argc, char *argv[], void *userdata) { return print_version(); } static int help_main(int argc, char *argv[], void *userdata) { return help(); } static int udevadm_main(int argc, char *argv[]) { static const Verb verbs[] = { { "info", VERB_ANY, VERB_ANY, 0, info_main }, { "trigger", VERB_ANY, VERB_ANY, 0, trigger_main }, { "settle", VERB_ANY, VERB_ANY, 0, settle_main }, { "control", VERB_ANY, VERB_ANY, 0, control_main }, { "monitor", VERB_ANY, VERB_ANY, 0, monitor_main }, { "hwdb", VERB_ANY, VERB_ANY, 0, hwdb_main }, { "test", VERB_ANY, VERB_ANY, 0, test_main }, { "test-builtin", VERB_ANY, VERB_ANY, 0, builtin_main }, { "wait", VERB_ANY, VERB_ANY, 0, wait_main }, { "lock", VERB_ANY, VERB_ANY, 0, lock_main }, { "verify", VERB_ANY, VERB_ANY, 0, verify_main }, { "version", VERB_ANY, VERB_ANY, 0, version_main }, { "help", VERB_ANY, VERB_ANY, 0, help_main }, {} }; return dispatch_verb(argc, argv, verbs, NULL); } static int run(int argc, char *argv[]) { int r; if (invoked_as(argv, "udevd")) return run_udevd(argc, argv); udev_parse_config(); log_setup(); r = parse_argv(argc, argv); if (r <= 0) return r; r = mac_init(); if (r < 0) return r; return udevadm_main(argc, argv); } DEFINE_MAIN_FUNCTION(run);
4,689
32.262411
102
c
null
systemd-main/src/udev/udevadm.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include <stdio.h> #include "macro.h" int info_main(int argc, char *argv[], void *userdata); int trigger_main(int argc, char *argv[], void *userdata); int settle_main(int argc, char *argv[], void *userdata); int control_main(int argc, char *argv[], void *userdata); int monitor_main(int argc, char *argv[], void *userdata); int hwdb_main(int argc, char *argv[], void *userdata); int test_main(int argc, char *argv[], void *userdata); int builtin_main(int argc, char *argv[], void *userdata); int verify_main(int argc, char *argv[], void *userdata); int wait_main(int argc, char *argv[], void *userdata); int lock_main(int argc, char *argv[], void *userdata); static inline int print_version(void) { /* Dracut relies on the version being a single integer */ puts(STRINGIFY(PROJECT_VERSION)); return 0; }
892
34.72
65
h
null
systemd-main/src/udev/fido_id/fido_id.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Identifies FIDO CTAP1 ("U2F")/CTAP2 security tokens based on the usage declared in their report * descriptor and outputs suitable environment variables. * * Inspired by Andrew Lutomirski's 'u2f-hidraw-policy.c' */ #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <linux/hid.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "build.h" #include "device-private.h" #include "device-util.h" #include "fd-util.h" #include "fido_id_desc.h" #include "log.h" #include "macro.h" #include "main-func.h" #include "path-util.h" #include "string-util.h" #include "udev-util.h" static const char *arg_device = NULL; static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, {} }; int c; while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': printf("%s [OPTIONS...] SYSFS_PATH\n\n" " -h --help Show this help text\n" " --version Show package version\n", program_invocation_short_name); return 0; case 'v': return version(); case '?': return -EINVAL; default: assert_not_reached(); } if (argc > 2) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error: unexpected argument."); arg_device = argv[optind]; return 1; } static int run(int argc, char **argv) { _cleanup_(sd_device_unrefp) struct sd_device *device = NULL; _cleanup_free_ char *desc_path = NULL; _cleanup_close_ int fd = -EBADF; struct sd_device *hid_device; const char *sys_path; uint8_t desc[HID_MAX_DESCRIPTOR_SIZE]; ssize_t desc_len; int r; log_set_target(LOG_TARGET_AUTO); udev_parse_config(); log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; if (arg_device) { r = sd_device_new_from_syspath(&device, arg_device); if (r < 0) return log_error_errno(r, "Failed to get device from syspath %s: %m", arg_device); } else { r = device_new_from_strv(&device, environ); if (r < 0) return log_error_errno(r, "Failed to get current device from environment: %m"); } r = sd_device_get_parent(device, &hid_device); if (r < 0) return log_device_error_errno(device, r, "Failed to get parent HID device: %m"); r = sd_device_get_syspath(hid_device, &sys_path); if (r < 0) return log_device_error_errno(hid_device, r, "Failed to get syspath for HID device: %m"); desc_path = path_join(sys_path, "report_descriptor"); if (!desc_path) return log_oom(); fd = open(desc_path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NOCTTY); if (fd < 0) return log_device_error_errno(hid_device, errno, "Failed to open report descriptor at '%s': %m", desc_path); desc_len = read(fd, desc, sizeof(desc)); if (desc_len < 0) return log_device_error_errno(hid_device, errno, "Failed to read report descriptor at '%s': %m", desc_path); if (desc_len == 0) return log_device_debug_errno(hid_device, SYNTHETIC_ERRNO(EINVAL), "Empty report descriptor at '%s'.", desc_path); r = is_fido_security_token_desc(desc, desc_len); if (r < 0) return log_device_debug_errno(hid_device, r, "Failed to parse report descriptor at '%s'.", desc_path); if (r > 0) { printf("ID_FIDO_TOKEN=1\n"); printf("ID_SECURITY_TOKEN=1\n"); } return 0; } DEFINE_MAIN_FUNCTION(run);
4,432
33.1
106
c
null
systemd-main/src/udev/fido_id/fido_id_desc.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* Inspired by Andrew Lutomirski's 'u2f-hidraw-policy.c' */ #include <errno.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include "fido_id_desc.h" #define HID_RPTDESC_FIRST_BYTE_LONG_ITEM 0xfeu #define HID_RPTDESC_TYPE_GLOBAL 0x1u #define HID_RPTDESC_TYPE_LOCAL 0x2u #define HID_RPTDESC_TAG_USAGE_PAGE 0x0u #define HID_RPTDESC_TAG_USAGE 0x0u /* * HID usage for FIDO CTAP1 ("U2F") and CTAP2 security tokens. * https://fidoalliance.org/specs/fido-u2f-v1.0-ps-20141009/fido-u2f-u2f_hid.h-v1.0-ps-20141009.txt * https://fidoalliance.org/specs/fido-v2.0-ps-20190130/fido-client-to-authenticator-protocol-v2.0-ps-20190130.html#usb-discovery * https://www.usb.org/sites/default/files/hutrr48.pdf */ #define FIDO_FULL_USAGE_CTAPHID 0xf1d00001u /* * Parses a HID report descriptor and identifies FIDO CTAP1 ("U2F")/CTAP2 security tokens based on their * declared usage. * A positive return value indicates that the report descriptor belongs to a FIDO security token. * https://www.usb.org/sites/default/files/documents/hid1_11.pdf (Section 6.2.2) */ int is_fido_security_token_desc(const uint8_t *desc, size_t desc_len) { uint32_t usage = 0; for (size_t pos = 0; pos < desc_len; ) { uint8_t tag, type, size_code; size_t size; uint32_t value; /* Report descriptors consists of short items (1-5 bytes) and long items (3-258 bytes). */ if (desc[pos] == HID_RPTDESC_FIRST_BYTE_LONG_ITEM) { /* No long items are defined in the spec; skip them. * The length of the data in a long item is contained in the byte after the long * item tag. The header consists of three bytes: special long item tag, length, * actual tag. */ if (pos + 1 >= desc_len) return -EINVAL; pos += desc[pos + 1] + 3; continue; } /* The first byte of a short item encodes tag, type and size. */ tag = desc[pos] >> 4; /* Bits 7 to 4 */ type = (desc[pos] >> 2) & 0x3; /* Bits 3 and 2 */ size_code = desc[pos] & 0x3; /* Bits 1 and 0 */ /* Size is coded as follows: * 0 -> 0 bytes, 1 -> 1 byte, 2 -> 2 bytes, 3 -> 4 bytes */ size = size_code < 3 ? size_code : 4; /* Consume header byte. */ pos++; /* Extract the item value coded on size bytes. */ if (pos + size > desc_len) return -EINVAL; value = 0; for (size_t i = 0; i < size; i++) value |= (uint32_t) desc[pos + i] << (8 * i); /* Consume value bytes. */ pos += size; if (type == HID_RPTDESC_TYPE_GLOBAL && tag == HID_RPTDESC_TAG_USAGE_PAGE) { /* A usage page is a 16 bit value coded on at most 16 bits. */ if (size > 2) return -EINVAL; /* A usage page sets the upper 16 bits of a following usage. */ usage = (value & 0x0000ffffu) << 16; } if (type == HID_RPTDESC_TYPE_LOCAL && tag == HID_RPTDESC_TAG_USAGE) { /* A usage is a 32 bit value, but is prepended with the current usage page if * coded on less than 4 bytes (that is, at most 2 bytes). */ if (size == 4) usage = value; else usage = (usage & 0xffff0000u) | (value & 0x0000ffffu); if (usage == FIDO_FULL_USAGE_CTAPHID) return 1; } } return 0; }
4,053
42.591398
129
c
null
systemd-main/src/udev/fido_id/fuzz-fido-id-desc.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <linux/hid.h> #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include "fido_id_desc.h" #include "fuzz.h" #include "log.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); if (outside_size_range(size, 0, HID_MAX_DESCRIPTOR_SIZE)) return 0; (void) is_fido_security_token_desc(data, size); return 0; }
655
25.24
75
c
null
systemd-main/src/udev/fido_id/test-fido-id-desc.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdint.h> #include <stdlib.h> #include "fido_id_desc.h" #include "macro.h" #include "tests.h" TEST(is_fido_security_token_desc__fido) { static const uint8_t FIDO_HID_DESC_1[] = { 0x06, 0xd0, 0xf1, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x20, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x21, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, 0xc0, }; assert_se(is_fido_security_token_desc(FIDO_HID_DESC_1, sizeof(FIDO_HID_DESC_1)) > 0); static const uint8_t FIDO_HID_DESC_2[] = { 0x05, 0x01, 0x09, 0x06, 0xa1, 0x01, 0x05, 0x07, 0x19, 0xe0, 0x29, 0xe7, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x95, 0x01, 0x75, 0x08, 0x81, 0x01, 0x95, 0x05, 0x75, 0x01, 0x05, 0x08, 0x19, 0x01, 0x29, 0x05, 0x91, 0x02, 0x95, 0x01, 0x75, 0x03, 0x91, 0x01, 0x95, 0x06, 0x75, 0x08, 0x15, 0x00, 0x25, 0x65, 0x05, 0x07, 0x19, 0x00, 0x29, 0x65, 0x81, 0x00, 0x09, 0x03, 0x75, 0x08, 0x95, 0x08, 0xb1, 0x02, 0xc0, 0x06, 0xd0, 0xf1, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x20, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x21, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, 0xc0, }; assert_se(is_fido_security_token_desc(FIDO_HID_DESC_2, sizeof(FIDO_HID_DESC_2)) > 0); } TEST(is_fido_security_token_desc__non_fido) { /* Wrong usage page */ static const uint8_t NON_FIDO_HID_DESC_1[] = { 0x06, 0xd0, 0xf0, 0x09, 0x01, 0xa1, 0x01, 0x09, 0x20, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x21, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, 0xc0, }; assert_se(is_fido_security_token_desc(NON_FIDO_HID_DESC_1, sizeof(NON_FIDO_HID_DESC_1)) == 0); /* Wrong usage */ static const uint8_t NON_FIDO_HID_DESC_2[] = { 0x06, 0xd0, 0xf1, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x20, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x81, 0x02, 0x09, 0x21, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, 0xc0, }; assert_se(is_fido_security_token_desc(NON_FIDO_HID_DESC_2, sizeof(NON_FIDO_HID_DESC_2)) == 0); static const uint8_t NON_FIDO_HID_DESC_3[] = { 0x05, 0x01, 0x09, 0x06, 0xa1, 0x01, 0x05, 0x07, 0x19, 0xe0, 0x29, 0xe7, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x95, 0x01, 0x75, 0x08, 0x81, 0x01, 0x95, 0x05, 0x75, 0x01, 0x05, 0x08, 0x19, 0x01, 0x29, 0x05, 0x91, 0x02, 0x95, 0x01, 0x75, 0x03, 0x91, 0x01, 0x95, 0x06, 0x75, 0x08, 0x15, 0x00, 0x25, 0x65, 0x05, 0x07, 0x19, 0x00, 0x29, 0x65, 0x81, 0x00, 0x09, 0x03, 0x75, 0x08, 0x95, 0x08, 0xb1, 0x02, 0xc0, }; assert_se(is_fido_security_token_desc(NON_FIDO_HID_DESC_3, sizeof(NON_FIDO_HID_DESC_3)) == 0); } TEST(is_fido_security_token_desc__invalid) { /* Size coded on 1 byte, but no byte given */ static const uint8_t INVALID_HID_DESC_1[] = { 0x01 }; assert_se(is_fido_security_token_desc(INVALID_HID_DESC_1, sizeof(INVALID_HID_DESC_1)) < 0); /* Size coded on 2 bytes, but only 1 byte given */ static const uint8_t INVALID_HID_DESC_2[] = { 0x02, 0x01 }; assert_se(is_fido_security_token_desc(INVALID_HID_DESC_2, sizeof(INVALID_HID_DESC_2)) < 0); /* Size coded on 4 bytes, but only 3 bytes given */ static const uint8_t INVALID_HID_DESC_3[] = { 0x03, 0x01, 0x02, 0x03 }; assert_se(is_fido_security_token_desc(INVALID_HID_DESC_3, sizeof(INVALID_HID_DESC_3)) < 0); /* Long item without a size byte */ static const uint8_t INVALID_HID_DESC_4[] = { 0xfe }; assert_se(is_fido_security_token_desc(INVALID_HID_DESC_4, sizeof(INVALID_HID_DESC_4)) < 0); /* Usage pages are coded on at most 2 bytes */ static const uint8_t INVALID_HID_DESC_5[] = { 0x07, 0x01, 0x02, 0x03, 0x04 }; assert_se(is_fido_security_token_desc(INVALID_HID_DESC_5, sizeof(INVALID_HID_DESC_5)) < 0); } DEFINE_TEST_MAIN(LOG_INFO);
4,359
52.82716
105
c
null
systemd-main/src/udev/iocost/iocost.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <stdio.h> #include <unistd.h> #include "sd-device.h" #include "alloc-util.h" #include "build.h" #include "cgroup-util.h" #include "conf-parser.h" #include "devnum-util.h" #include "device-util.h" #include "main-func.h" #include "path-util.h" #include "pretty-print.h" #include "verbs.h" static char *arg_target_solution = NULL; STATIC_DESTRUCTOR_REGISTER(arg_target_solution, freep); static int parse_config(void) { static const ConfigTableItem items[] = { { "IOCost", "TargetSolution", config_parse_string, 0, &arg_target_solution }, }; int r; r = config_parse( NULL, "/etc/udev/iocost.conf", NULL, "IOCost\0", config_item_table_lookup, items, CONFIG_PARSE_WARN, NULL, NULL); if (r < 0) return r; if (!arg_target_solution) { arg_target_solution = strdup("naive"); if (!arg_target_solution) return log_oom(); } log_debug("Target solution: %s", arg_target_solution); return 0; } static int help(void) { printf("%s [OPTIONS...]\n\n" "Set up iocost model and qos solutions for block devices\n" "\nCommands:\n" " apply <path> [SOLUTION] Apply solution for the device if\n" " found, do nothing otherwise\n" " query <path> Query the known solution for\n" " the device\n" "\nOptions:\n" " -h --help Show this help\n" " --version Show package version\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, {} }; int c; assert(argc >= 1); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int get_known_solutions(sd_device *device, int log_level, char ***ret_solutions, const char **ret_selected) { _cleanup_free_ char **s = NULL; const char *value, *found; int r; assert(ret_solutions); assert(ret_selected); r = sd_device_get_property_value(device, "IOCOST_SOLUTIONS", &value); if (r == -ENOENT) return log_device_full_errno(device, log_level, r, "No iocost solution found for device."); if (r < 0) return log_device_error_errno(device, r, "Failed to query solutions from device: %m"); s = strv_split(value, WHITESPACE); if (!s) return log_oom(); if (strv_isempty(s)) return log_device_error_errno(device, SYNTHETIC_ERRNO(EINVAL), "IOCOST_SOLUTIONS exists in hwdb but is empty."); found = strv_find(s, arg_target_solution); if (found) { *ret_selected = found; log_device_debug(device, "Selected solution based on target solution: %s", *ret_selected); } else { *ret_selected = s[0]; log_device_debug(device, "Selected first available solution: %s", *ret_selected); } *ret_solutions = TAKE_PTR(s); return 0; } static int query_named_solution( sd_device *device, const char *name, const char **ret_model, const char **ret_qos) { _cleanup_free_ char *upper_name = NULL, *qos_key = NULL, *model_key = NULL; const char *qos, *model; int r; assert(name); assert(ret_qos); assert(ret_model); upper_name = strdup(name); if (!upper_name) return log_oom(); ascii_strupper(upper_name); string_replace_char(upper_name, '-', '_'); qos_key = strjoin("IOCOST_QOS_", upper_name); if (!qos_key) return log_oom(); model_key = strjoin("IOCOST_MODEL_", upper_name); if (!model_key) return log_oom(); r = sd_device_get_property_value(device, qos_key, &qos); if (r == -ENOENT) return log_device_debug_errno(device, r, "No value found for key %s, skipping iocost logic.", qos_key); if (r < 0) return log_device_error_errno(device, r, "Failed to obtain QoS for iocost solution from device: %m"); r = sd_device_get_property_value(device, model_key, &model); if (r == -ENOENT) return log_device_debug_errno(device, r, "No value found for key %s, skipping iocost logic.", model_key); if (r < 0) return log_device_error_errno(device, r, "Failed to obtain model for iocost solution from device: %m"); *ret_qos = qos; *ret_model = model; return 0; } static int apply_solution_for_path(const char *path, const char *name) { _cleanup_(sd_device_unrefp) sd_device *device = NULL; _cleanup_strv_free_ char **solutions = NULL; _cleanup_free_ char *qos = NULL, *model = NULL; const char *qos_params, *model_params; dev_t devnum; int r; r = sd_device_new_from_path(&device, path); if (r < 0) return log_error_errno(r, "Error looking up device: %m"); r = sd_device_get_devnum(device, &devnum); if (r < 0) return log_device_error_errno(device, r, "Error getting devnum: %m"); if (!name) { r = get_known_solutions(device, LOG_DEBUG, &solutions, &name); if (r == -ENOENT) return 0; if (r < 0) return r; } r = query_named_solution(device, name, &model_params, &qos_params); if (r == -ENOENT) return 0; if (r < 0) return r; if (asprintf(&qos, DEVNUM_FORMAT_STR " enable=1 ctrl=user %s", DEVNUM_FORMAT_VAL(devnum), qos_params) < 0) return log_oom(); if (asprintf(&model, DEVNUM_FORMAT_STR " model=linear ctrl=user %s", DEVNUM_FORMAT_VAL(devnum), model_params) < 0) return log_oom(); log_debug("Applying iocost parameters to %s using solution '%s'\n" "\tio.cost.qos: %s\n" "\tio.cost.model: %s\n", path, name, qos, model); r = cg_set_attribute("io", NULL, "io.cost.qos", qos); if (r < 0) { log_device_full_errno(device, r == -ENOENT ? LOG_DEBUG : LOG_ERR, r, "Failed to set io.cost.qos: %m"); return r == -ENOENT ? 0 : r; } r = cg_set_attribute("io", NULL, "io.cost.model", model); if (r < 0) { log_device_full_errno(device, r == -ENOENT ? LOG_DEBUG : LOG_ERR, r, "Failed to set io.cost.model: %m"); return r == -ENOENT ? 0 : r; } return 0; } static int query_solutions_for_path(const char *path) { _cleanup_(sd_device_unrefp) sd_device *device = NULL; _cleanup_strv_free_ char **solutions = NULL; const char *selected_solution, *model_name; int r; r = sd_device_new_from_path(&device, path); if (r < 0) return log_error_errno(r, "Error looking up device: %m"); r = sd_device_get_property_value(device, "ID_MODEL_FROM_DATABASE", &model_name); if (r == -ENOENT) { log_device_debug(device, "Missing ID_MODEL_FROM_DATABASE property, trying ID_MODEL"); r = sd_device_get_property_value(device, "ID_MODEL", &model_name); if (r == -ENOENT) { log_device_info(device, "Device model not found"); return 0; } } if (r < 0) return log_device_error_errno(device, r, "Model name for device %s is unknown", path); r = get_known_solutions(device, LOG_INFO, &solutions, &selected_solution); if (r == -ENOENT) return 0; if (r < 0) return r; log_info("Known solutions for %s model name: \"%s\"\n" "Preferred solution: %s\n" "Solution that would be applied: %s", path, model_name, arg_target_solution, selected_solution); STRV_FOREACH(s, solutions) { const char *model, *qos; if (query_named_solution(device, *s, &model, &qos) < 0) continue; log_info("%s: io.cost.qos: %s\n" "%s: io.cost.model: %s", *s, qos, *s, model); } return 0; } static int verb_query(int argc, char *argv[], void *userdata) { return query_solutions_for_path(ASSERT_PTR(argv[1])); } static int verb_apply(int argc, char *argv[], void *userdata) { return apply_solution_for_path( ASSERT_PTR(argv[1]), argc > 2 ? ASSERT_PTR(argv[2]) : NULL); } static int iocost_main(int argc, char *argv[]) { static const Verb verbs[] = { { "query", 2, 2, 0, verb_query }, { "apply", 2, 3, 0, verb_apply }, {}, }; return dispatch_verb(argc, argv, verbs, NULL); } static int run(int argc, char *argv[]) { int r; log_setup(); r = parse_argv(argc, argv); if (r <= 0) return r; r = parse_config(); if (r < 0) return r; return iocost_main(argc, argv); } DEFINE_MAIN_FUNCTION(run);
10,589
31.584615
122
c
null
systemd-main/src/udev/mtd_probe/mtd_probe.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright © 2010 - Maxim Levitsky * * mtd_probe is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * mtd_probe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mtd_probe; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <mtd/mtd-user.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "build.h" #include "fd-util.h" #include "main-func.h" #include "mtd_probe.h" static const char *arg_device = NULL; static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, {} }; int c; while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': printf("%s /dev/mtd[n]\n\n" " -h --help Show this help text\n" " --version Show package version\n", program_invocation_short_name); return 0; case 'v': return version(); case '?': return -EINVAL; default: assert_not_reached(); } if (argc > 2) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Error: unexpected argument."); arg_device = argv[optind]; return 1; } static int run(int argc, char** argv) { _cleanup_close_ int mtd_fd = -EBADF; mtd_info_t mtd_info; int r; r = parse_argv(argc, argv); if (r <= 0) return r; mtd_fd = open(argv[1], O_RDONLY|O_CLOEXEC|O_NOCTTY); if (mtd_fd < 0) return log_error_errno(errno, "Failed to open: %m"); if (ioctl(mtd_fd, MEMGETINFO, &mtd_info) < 0) return log_error_errno(errno, "MEMGETINFO ioctl failed: %m"); return probe_smart_media(mtd_fd, &mtd_info); } DEFINE_MAIN_FUNCTION(run);
2,823
30.032967
95
c
null
systemd-main/src/udev/mtd_probe/mtd_probe.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once /* * Copyright © 2010 - Maxim Levitsky * * mtd_probe is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * mtd_probe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mtd_probe; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ #include <mtd/mtd-user.h> #include "macro.h" /* Full oob structure as written on the flash */ struct sm_oob { uint32_t reserved; uint8_t data_status; uint8_t block_status; uint8_t lba_copy1[2]; uint8_t ecc2[3]; uint8_t lba_copy2[2]; uint8_t ecc1[3]; } _packed_; /* one sector is always 512 bytes, but it can consist of two nand pages */ #define SM_SECTOR_SIZE 512 /* oob area is also 16 bytes, but might be from two pages */ #define SM_OOB_SIZE 16 /* This is maximum zone size, and all devices that have more that one zone have this size */ #define SM_MAX_ZONE_SIZE 1024 /* support for small page nand */ #define SM_SMALL_PAGE 256 #define SM_SMALL_OOB_SIZE 8 int probe_smart_media(int mtd_fd, mtd_info_t *info);
1,657
30.283019
74
h
null
systemd-main/src/udev/mtd_probe/probe_smartmedia.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright © 2010 - Maxim Levitsky * * mtd_probe is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * mtd_probe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with mtd_probe; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ #include <errno.h> #include <fcntl.h> #include <mtd/mtd-user.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "mtd_probe.h" static const uint8_t cis_signature[] = { 0x01, 0x03, 0xD9, 0x01, 0xFF, 0x18, 0x02, 0xDF, 0x01, 0x20 }; int probe_smart_media(int mtd_fd, mtd_info_t* info) { int sector_size; int block_size; int size_in_megs; int spare_count; _cleanup_free_ uint8_t *cis_buffer = NULL; int offset; int cis_found = 0; cis_buffer = malloc(SM_SECTOR_SIZE); if (!cis_buffer) return log_oom(); if (info->type != MTD_NANDFLASH) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Not marked MTD_NANDFLASH."); sector_size = info->writesize; block_size = info->erasesize; size_in_megs = info->size / (1024 * 1024); if (!IN_SET(sector_size, SM_SECTOR_SIZE, SM_SMALL_PAGE)) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected sector size: %i", sector_size); switch (size_in_megs) { case 1: case 2: spare_count = 6; break; case 4: spare_count = 12; break; default: spare_count = 24; break; } for (offset = 0; offset < block_size * spare_count; offset += sector_size) { (void) lseek(mtd_fd, SEEK_SET, offset); if (read(mtd_fd, cis_buffer, SM_SECTOR_SIZE) == SM_SECTOR_SIZE) { cis_found = 1; break; } } if (!cis_found) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "CIS not found"); if (memcmp(cis_buffer, cis_signature, sizeof(cis_signature)) != 0 && memcmp(cis_buffer + SM_SMALL_PAGE, cis_signature, sizeof(cis_signature)) != 0) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "CIS signature didn't match"); printf("MTD_FTL=smartmedia\n"); return 0; }
3,158
31.234694
90
c
null
systemd-main/src/udev/net/fuzz-link-parser.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "fd-util.h" #include "fs-util.h" #include "fuzz.h" #include "link-config.h" #include "tmpfile-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(link_config_ctx_freep) LinkConfigContext *ctx = NULL; _cleanup_(unlink_tempfilep) char filename[] = "/tmp/fuzz-link-config.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; if (outside_size_range(size, 0, 65536)) return 0; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(fmkostemp_safe(filename, "r+", &f) == 0); if (size != 0) assert_se(fwrite(data, size, 1, f) == 1); fflush(f); assert_se(link_config_ctx_new(&ctx) >= 0); (void) link_load_one(ctx, filename); return 0; }
865
28.862069
85
c
null
systemd-main/src/udev/net/link-config.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-device.h" #include "sd-netlink.h" #include "condition.h" #include "conf-parser.h" #include "ethtool-util.h" #include "hashmap.h" #include "list.h" #include "net-condition.h" #include "netif-naming-scheme.h" typedef struct LinkConfigContext LinkConfigContext; typedef struct LinkConfig LinkConfig; typedef enum MACAddressPolicy { MAC_ADDRESS_POLICY_PERSISTENT, MAC_ADDRESS_POLICY_RANDOM, MAC_ADDRESS_POLICY_NONE, _MAC_ADDRESS_POLICY_MAX, _MAC_ADDRESS_POLICY_INVALID = -EINVAL, } MACAddressPolicy; typedef struct Link { int ifindex; const char *ifname; const char *new_name; char **altnames; LinkConfig *config; sd_device *device; sd_device_action_t action; char *kind; char *driver; uint16_t iftype; uint32_t flags; struct hw_addr_data hw_addr; struct hw_addr_data permanent_hw_addr; unsigned name_assign_type; unsigned addr_assign_type; } Link; struct LinkConfig { char *filename; char **dropins; NetMatch match; LIST_HEAD(Condition, conditions); char *description; struct hw_addr_data hw_addr; MACAddressPolicy mac_address_policy; NamePolicy *name_policy; NamePolicy *alternative_names_policy; char *name; char **alternative_names; char *alias; uint32_t txqueues; uint32_t rxqueues; uint32_t txqueuelen; uint32_t mtu; uint32_t gso_max_segments; size_t gso_max_size; uint64_t speed; Duplex duplex; int autonegotiation; uint32_t advertise[N_ADVERTISE]; uint32_t wol; char *wol_password_file; uint8_t *wol_password; NetDevPort port; int features[_NET_DEV_FEAT_MAX]; netdev_channels channels; netdev_ring_param ring; int rx_flow_control; int tx_flow_control; int autoneg_flow_control; netdev_coalesce_param coalesce; uint8_t mdi; uint32_t sr_iov_num_vfs; OrderedHashmap *sr_iov_by_section; LIST_FIELDS(LinkConfig, configs); }; int link_config_ctx_new(LinkConfigContext **ret); LinkConfigContext* link_config_ctx_free(LinkConfigContext *ctx); DEFINE_TRIVIAL_CLEANUP_FUNC(LinkConfigContext*, link_config_ctx_free); int link_load_one(LinkConfigContext *ctx, const char *filename); int link_config_load(LinkConfigContext *ctx); bool link_config_should_reload(LinkConfigContext *ctx); int link_new(LinkConfigContext *ctx, sd_netlink **rtnl, sd_device *device, Link **ret); Link *link_free(Link *link); DEFINE_TRIVIAL_CLEANUP_FUNC(Link*, link_free); int link_get_config(LinkConfigContext *ctx, Link *link); int link_apply_config(LinkConfigContext *ctx, sd_netlink **rtnl, Link *link); const char *mac_address_policy_to_string(MACAddressPolicy p) _const_; MACAddressPolicy mac_address_policy_from_string(const char *p) _pure_; /* gperf lookup function */ const struct ConfigPerfItem* link_config_gperf_lookup(const char *key, GPERF_LEN_TYPE length); CONFIG_PARSER_PROTOTYPE(config_parse_ifalias); CONFIG_PARSER_PROTOTYPE(config_parse_rx_tx_queues); CONFIG_PARSER_PROTOTYPE(config_parse_txqueuelen); CONFIG_PARSER_PROTOTYPE(config_parse_wol_password); CONFIG_PARSER_PROTOTYPE(config_parse_mac_address_policy); CONFIG_PARSER_PROTOTYPE(config_parse_name_policy); CONFIG_PARSER_PROTOTYPE(config_parse_alternative_names_policy);
3,564
29.211864
94
h
null
systemd-main/src/udev/scsi_id/scsi.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once /* * scsi.h * * General scsi and linux scsi specific defines and structs. * * Copyright (C) IBM Corp. 2003 * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation version 2 of the License. */ #include <scsi/scsi.h> struct scsi_ioctl_command { unsigned inlen; /* excluding scsi command length */ unsigned outlen; unsigned char data[1]; /* on input, scsi command starts here then opt. data */ }; /* * Default 5 second timeout */ #define DEF_TIMEOUT 5000 #define SENSE_BUFF_LEN 32 /* * The request buffer size passed to the SCSI INQUIRY commands, use 254, * as this is a nice value for some devices, especially some of the usb * mass storage devices. */ #define SCSI_INQ_BUFF_LEN 254 /* * SCSI INQUIRY vendor and model (really product) lengths. */ #define VENDOR_LENGTH 8 #define MODEL_LENGTH 16 #define INQUIRY_CMD 0x12 #define INQUIRY_CMDLEN 6 /* * INQUIRY VPD page 0x83 identifier descriptor related values. Reference the * SCSI Primary Commands specification for details. */ /* * id type values of id descriptors. These are assumed to fit in 4 bits. */ #define SCSI_ID_VENDOR_SPECIFIC 0 #define SCSI_ID_T10_VENDOR 1 #define SCSI_ID_EUI_64 2 #define SCSI_ID_NAA 3 #define SCSI_ID_RELPORT 4 #define SCSI_ID_TGTGROUP 5 #define SCSI_ID_LUNGROUP 6 #define SCSI_ID_MD5 7 #define SCSI_ID_NAME 8 /* * Supported NAA values. These fit in 4 bits, so the "don't care" value * cannot conflict with real values. */ #define SCSI_ID_NAA_DONT_CARE 0xff #define SCSI_ID_NAA_IEEE_REG 0x05 #define SCSI_ID_NAA_IEEE_REG_EXTENDED 0x06 /* * Supported Code Set values. */ #define SCSI_ID_BINARY 1 #define SCSI_ID_ASCII 2 struct scsi_id_search_values { u_char id_type; u_char naa_type; u_char code_set; }; /* * Following are the "true" SCSI status codes. Linux has traditionally * used a 1 bit right and masked version of these. So now CHECK_CONDITION * and friends (in <scsi/scsi.h>) are deprecated. */ #define SCSI_CHECK_CONDITION 0x02 #define SCSI_CONDITION_MET 0x04 #define SCSI_BUSY 0x08 #define SCSI_IMMEDIATE 0x10 #define SCSI_IMMEDIATE_CONDITION_MET 0x14 #define SCSI_RESERVATION_CONFLICT 0x18 #define SCSI_COMMAND_TERMINATED 0x22 #define SCSI_TASK_SET_FULL 0x28 #define SCSI_ACA_ACTIVE 0x30 #define SCSI_TASK_ABORTED 0x40
2,699
25.732673
81
h
null
systemd-main/src/udev/scsi_id/scsi_id.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once /* * Copyright © IBM Corp. 2003 */ #define MAX_PATH_LEN 512 /* * MAX_ATTR_LEN: maximum length of the result of reading a sysfs * attribute. */ #define MAX_ATTR_LEN 256 /* * MAX_SERIAL_LEN: the maximum length of the serial number, including * added prefixes such as vendor and product (model) strings. */ #define MAX_SERIAL_LEN 256 /* * MAX_BUFFER_LEN: maximum buffer size and line length used while reading * the config file. */ #define MAX_BUFFER_LEN 256 struct scsi_id_device { char vendor[9]; char model[17]; char revision[5]; char kernel[64]; char serial[MAX_SERIAL_LEN]; char serial_short[MAX_SERIAL_LEN]; unsigned type; int use_sg; /* Always from page 0x80 e.g. 'B3G1P8500RWT' - may not be unique */ char unit_serial_number[MAX_SERIAL_LEN]; /* NULs if not set - otherwise hex encoding using lower-case e.g. '50014ee0016eb572' */ char wwn[17]; /* NULs if not set - otherwise hex encoding using lower-case e.g. '0xe00000d80000' */ char wwn_vendor_extension[17]; /* NULs if not set - otherwise decimal number */ char tgpt_group[8]; }; int scsi_std_inquiry(struct scsi_id_device *dev_scsi, const char *devname); int scsi_get_serial(struct scsi_id_device *dev_scsi, const char *devname, int page_code, int len); /* * Page code values. */ enum page_code { PAGE_83_PRE_SPC3 = -0x83, PAGE_UNSPECIFIED = 0x00, PAGE_80 = 0x80, PAGE_83 = 0x83, };
1,626
24.421875
95
h
null
systemd-main/src/udev/v4l_id/v4l_id.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (c) 2009 Filippo Argiolas <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details: */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <linux/videodev2.h> #include "build.h" #include "fd-util.h" #include "main-func.h" static const char *arg_device = NULL; static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, {} }; int c; while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': printf("%s [OPTIONS...] DEVICE\n\n" "Video4Linux device identification.\n\n" " -h --help Show this help text\n" " --version Show package version\n", program_invocation_short_name); return 0; case 'v': return version(); case '?': return -EINVAL; default: assert_not_reached(); } if (!argv[optind]) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "DEVICE argument missing."); arg_device = argv[optind]; return 1; } static int run(int argc, char *argv[]) { _cleanup_close_ int fd = -EBADF; struct v4l2_capability v2cap; int r; r = parse_argv(argc, argv); if (r <= 0) return r; fd = open(arg_device, O_RDONLY|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(errno, "Failed to open %s: %m", arg_device); if (ioctl(fd, VIDIOC_QUERYCAP, &v2cap) == 0) { int capabilities; printf("ID_V4L_VERSION=2\n"); printf("ID_V4L_PRODUCT=%s\n", v2cap.card); printf("ID_V4L_CAPABILITIES=:"); if (v2cap.capabilities & V4L2_CAP_DEVICE_CAPS) capabilities = v2cap.device_caps; else capabilities = v2cap.capabilities; if ((capabilities & V4L2_CAP_VIDEO_CAPTURE) > 0 || (capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE) > 0) printf("capture:"); if ((capabilities & V4L2_CAP_VIDEO_OUTPUT) > 0 || (capabilities & V4L2_CAP_VIDEO_OUTPUT_MPLANE) > 0) printf("video_output:"); if ((capabilities & V4L2_CAP_VIDEO_OVERLAY) > 0) printf("video_overlay:"); if ((capabilities & V4L2_CAP_AUDIO) > 0) printf("audio:"); if ((capabilities & V4L2_CAP_TUNER) > 0) printf("tuner:"); if ((capabilities & V4L2_CAP_RADIO) > 0) printf("radio:"); printf("\n"); } return 0; } DEFINE_MAIN_FUNCTION(run);
3,880
33.04386
83
c
null
systemd-main/src/update-done/update-done.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "fileio-label.h" #include "selinux-util.h" #include "time-util.h" #define MESSAGE \ "# This file was created by systemd-update-done. Its only \n" \ "# purpose is to hold a timestamp of the time this directory\n" \ "# was updated. See man:systemd-update-done.service(8).\n" static int apply_timestamp(const char *path, struct timespec *ts) { _cleanup_free_ char *message = NULL; int r; /* * We store the timestamp both as mtime of the file and in the file itself, * to support filesystems which cannot store nanosecond-precision timestamps. */ if (asprintf(&message, MESSAGE "TIMESTAMP_NSEC=" NSEC_FMT "\n", timespec_load_nsec(ts)) < 0) return log_oom(); r = write_string_file_atomic_label_ts(path, message, ts); if (r == -EROFS) log_debug_errno(r, "Cannot create \"%s\", file system is read-only.", path); else if (r < 0) return log_error_errno(r, "Failed to write \"%s\": %m", path); return 0; } int main(int argc, char *argv[]) { struct stat st; int r, q = 0; log_setup(); if (stat("/usr", &st) < 0) { log_error_errno(errno, "Failed to stat /usr: %m"); return EXIT_FAILURE; } r = mac_init(); if (r < 0) return EXIT_FAILURE; r = apply_timestamp("/etc/.updated", &st.st_mtim); q = apply_timestamp("/var/.updated", &st.st_mtim); return r < 0 || q < 0 ? EXIT_FAILURE : EXIT_SUCCESS; }
1,855
29.933333
92
c
null
systemd-main/src/user-sessions/user-sessions.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "fileio.h" #include "fileio-label.h" #include "fs-util.h" #include "main-func.h" #include "log.h" #include "selinux-util.h" #include "string-util.h" static int run(int argc, char *argv[]) { int r; if (argc != 2) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program requires one argument."); log_setup(); umask(0022); r = mac_init(); if (r < 0) return r; /* We only touch /run/nologin. See create_shutdown_run_nologin_or_warn() for details. */ if (streq(argv[1], "start")) return unlink_or_warn("/run/nologin"); if (streq(argv[1], "stop")) return create_shutdown_run_nologin_or_warn(); return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown verb '%s'.", argv[1]); } DEFINE_MAIN_FUNCTION(run);
1,058
23.627907
96
c
null
systemd-main/src/userdb/userdbd-manager.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-bus.h" #include "sd-event.h" typedef struct Manager Manager; #include "hashmap.h" #include "ratelimit.h" #define USERDB_WORKERS_MIN 3 #define USERDB_WORKERS_MAX 4096 struct Manager { sd_event *event; Set *workers_fixed; /* Workers 0…USERDB_WORKERS_MIN */ Set *workers_dynamic; /* Workers USERD_WORKERS_MIN+1…USERDB_WORKERS_MAX */ int listen_fd; RateLimit worker_ratelimit; sd_event_source *deferred_start_worker_event_source; }; int manager_new(Manager **ret); Manager* manager_free(Manager *m); DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free); int manager_startup(Manager *m);
720
20.848485
83
h
null
systemd-main/src/userdb/userdbd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/stat.h> #include <sys/types.h> #include "daemon-util.h" #include "userdbd-manager.h" #include "log.h" #include "main-func.h" #include "signal-util.h" /* This service offers two Varlink services, both implementing io.systemd.UserDatabase: * * → io.systemd.NameServiceSwitch: this is a compatibility interface for glibc NSS: it responds to * name lookups by checking the classic NSS interfaces and responding that. * * → io.systemd.Multiplexer: this multiplexes lookup requests to all Varlink services that have a * socket in /run/systemd/userdb/. It's supposed to simplify clients that don't want to implement * the full iterative logic on their own. * * → io.systemd.DropIn: this makes JSON user/group records dropped into /run/userdb/ available as * regular users. */ static int run(int argc, char *argv[]) { _cleanup_(manager_freep) Manager *m = NULL; _unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL; int r; log_setup(); umask(0022); if (argc != 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments."); if (setenv("SYSTEMD_BYPASS_USERDB", "io.systemd.NameServiceSwitch:io.systemd.Multiplexer:io.systemd.DropIn", 1) < 0) return log_error_errno(errno, "Failed to set $SYSTEMD_BYPASS_USERDB: %m"); assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, -1) >= 0); r = manager_new(&m); if (r < 0) return log_error_errno(r, "Could not create manager: %m"); r = manager_startup(m); if (r < 0) return log_error_errno(r, "Failed to start up daemon: %m"); notify_stop = notify_start(NOTIFY_READY, NOTIFY_STOPPING); r = sd_event_loop(m->event); if (r < 0) return log_error_errno(r, "Event loop failed: %m"); return 0; } DEFINE_MAIN_FUNCTION(run);
2,050
33.183333
124
c
null
systemd-main/src/vconsole/vconsole-setup.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2016 Michal Soltys <[email protected]> ***/ #include <errno.h> #include <fcntl.h> #include <limits.h> #include <linux/kd.h> #include <linux/tiocl.h> #include <linux/vt.h> #include <stdbool.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sysexits.h> #include <termios.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "creds-util.h" #include "env-file.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "io-util.h" #include "locale-util.h" #include "lock-util.h" #include "log.h" #include "proc-cmdline.h" #include "process-util.h" #include "signal-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "virt.h" typedef enum VCMeta { VC_KEYMAP, VC_KEYMAP_TOGGLE, VC_FONT, VC_FONT_MAP, VC_FONT_UNIMAP, _VC_META_MAX, _VC_META_INVALID = -EINVAL, } VCMeta; typedef struct Context { char *config[_VC_META_MAX]; } Context; static const char * const vc_meta_names[_VC_META_MAX] = { [VC_KEYMAP] = "vconsole.keymap", [VC_KEYMAP_TOGGLE] = "vconsole.keymap_toggle", [VC_FONT] = "vconsole.font", [VC_FONT_MAP] = "vconsole.font_map", [VC_FONT_UNIMAP] = "vconsole.font_unimap", }; /* compatibility with obsolete multiple-dot scheme */ static const char * const vc_meta_compat_names[_VC_META_MAX] = { [VC_KEYMAP_TOGGLE] = "vconsole.keymap.toggle", [VC_FONT_MAP] = "vconsole.font.map", [VC_FONT_UNIMAP] = "vconsole.font.unimap", }; static const char * const vc_env_names[_VC_META_MAX] = { [VC_KEYMAP] = "KEYMAP", [VC_KEYMAP_TOGGLE] = "KEYMAP_TOGGLE", [VC_FONT] = "FONT", [VC_FONT_MAP] = "FONT_MAP", [VC_FONT_UNIMAP] = "FONT_UNIMAP", }; static void context_done(Context *c) { assert(c); for (VCMeta i = 0; i < _VC_META_MAX; i++) free(c->config[i]); } static void context_merge_config( Context *dst, Context *src, Context *src_compat) { assert(dst); assert(src); for (VCMeta i = 0; i < _VC_META_MAX; i++) if (src->config[i]) free_and_replace(dst->config[i], src->config[i]); else if (src_compat && src_compat->config[i]) free_and_replace(dst->config[i], src_compat->config[i]); } static const char* context_get_config(Context *c, VCMeta meta) { assert(c); assert(meta >= 0 && meta < _VC_META_MAX); if (meta == VC_KEYMAP) return isempty(c->config[VC_KEYMAP]) ? SYSTEMD_DEFAULT_KEYMAP : c->config[VC_KEYMAP]; return empty_to_null(c->config[meta]); } static int context_read_creds(Context *c) { _cleanup_(context_done) Context v = {}; int r; assert(c); r = read_credential_strings_many( vc_meta_names[VC_KEYMAP], &v.config[VC_KEYMAP], vc_meta_names[VC_KEYMAP_TOGGLE], &v.config[VC_KEYMAP_TOGGLE], vc_meta_names[VC_FONT], &v.config[VC_FONT], vc_meta_names[VC_FONT_MAP], &v.config[VC_FONT_MAP], vc_meta_names[VC_FONT_UNIMAP], &v.config[VC_FONT_UNIMAP]); if (r < 0) log_warning_errno(r, "Failed to import credentials, ignoring: %m"); context_merge_config(c, &v, NULL); return 0; } static int context_read_env(Context *c) { _cleanup_(context_done) Context v = {}; int r; assert(c); r = parse_env_file( NULL, "/etc/vconsole.conf", vc_env_names[VC_KEYMAP], &v.config[VC_KEYMAP], vc_env_names[VC_KEYMAP_TOGGLE], &v.config[VC_KEYMAP_TOGGLE], vc_env_names[VC_FONT], &v.config[VC_FONT], vc_env_names[VC_FONT_MAP], &v.config[VC_FONT_MAP], vc_env_names[VC_FONT_UNIMAP], &v.config[VC_FONT_UNIMAP]); if (r < 0) { if (r != -ENOENT) log_warning_errno(r, "Failed to read /etc/vconsole.conf, ignoring: %m"); return r; } context_merge_config(c, &v, NULL); return 0; } static int context_read_proc_cmdline(Context *c) { _cleanup_(context_done) Context v = {}, w = {}; int r; assert(c); r = proc_cmdline_get_key_many( PROC_CMDLINE_STRIP_RD_PREFIX, vc_meta_names[VC_KEYMAP], &v.config[VC_KEYMAP], vc_meta_names[VC_KEYMAP_TOGGLE], &v.config[VC_KEYMAP_TOGGLE], vc_meta_names[VC_FONT], &v.config[VC_FONT], vc_meta_names[VC_FONT_MAP], &v.config[VC_FONT_MAP], vc_meta_names[VC_FONT_UNIMAP], &v.config[VC_FONT_UNIMAP], vc_meta_compat_names[VC_KEYMAP_TOGGLE], &w.config[VC_KEYMAP_TOGGLE], vc_meta_compat_names[VC_FONT_MAP], &w.config[VC_FONT_MAP], vc_meta_compat_names[VC_FONT_UNIMAP], &w.config[VC_FONT_UNIMAP]); if (r < 0) { if (r != -ENOENT) log_warning_errno(r, "Failed to read /proc/cmdline, ignoring: %m"); return r; } context_merge_config(c, &v, &w); return 0; } static void context_load_config(Context *c) { assert(c); /* Load data from credentials (lowest priority) */ (void) context_read_creds(c); /* Load data from configuration file (middle priority) */ (void) context_read_env(c); /* Let the kernel command line override /etc/vconsole.conf (highest priority) */ (void) context_read_proc_cmdline(c); } static int verify_vc_device(int fd) { unsigned char data[] = { TIOCL_GETFGCONSOLE, }; return RET_NERRNO(ioctl(fd, TIOCLINUX, data)); } static int verify_vc_allocation(unsigned idx) { char vcname[sizeof("/dev/vcs") + DECIMAL_STR_MAX(unsigned) - 2]; xsprintf(vcname, "/dev/vcs%u", idx); return RET_NERRNO(access(vcname, F_OK)); } static int verify_vc_allocation_byfd(int fd) { struct vt_stat vcs = {}; if (ioctl(fd, VT_GETSTATE, &vcs) < 0) return -errno; return verify_vc_allocation(vcs.v_active); } static int verify_vc_kbmode(int fd) { int curr_mode; /* * Make sure we only adjust consoles in K_XLATE or K_UNICODE mode. * Otherwise we would (likely) interfere with X11's processing of the * key events. * * https://lists.freedesktop.org/archives/systemd-devel/2013-February/008573.html */ if (ioctl(fd, KDGKBMODE, &curr_mode) < 0) return -errno; return IN_SET(curr_mode, K_XLATE, K_UNICODE) ? 0 : -EBUSY; } static int toggle_utf8_vc(const char *name, int fd, bool utf8) { int r; struct termios tc = {}; assert(name); assert(fd >= 0); r = ioctl(fd, KDSKBMODE, utf8 ? K_UNICODE : K_XLATE); if (r < 0) return log_warning_errno(errno, "Failed to %s UTF-8 kbdmode on %s: %m", enable_disable(utf8), name); r = loop_write(fd, utf8 ? "\033%G" : "\033%@", SIZE_MAX, false); if (r < 0) return log_warning_errno(r, "Failed to %s UTF-8 term processing on %s: %m", enable_disable(utf8), name); r = tcgetattr(fd, &tc); if (r >= 0) { SET_FLAG(tc.c_iflag, IUTF8, utf8); r = tcsetattr(fd, TCSANOW, &tc); } if (r < 0) return log_warning_errno(errno, "Failed to %s iutf8 flag on %s: %m", enable_disable(utf8), name); log_debug("UTF-8 kbdmode %sd on %s", enable_disable(utf8), name); return 0; } static int toggle_utf8_sysfs(bool utf8) { int r; r = write_string_file("/sys/module/vt/parameters/default_utf8", one_zero(utf8), WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) return log_warning_errno(r, "Failed to %s sysfs UTF-8 flag: %m", enable_disable(utf8)); log_debug("Sysfs UTF-8 flag %sd", enable_disable(utf8)); return 0; } static int keyboard_load_and_wait(const char *vc, Context *c, bool utf8) { const char *map, *map_toggle, *args[8]; unsigned i = 0; pid_t pid; int r; assert(vc); assert(c); map = context_get_config(c, VC_KEYMAP); map_toggle = context_get_config(c, VC_KEYMAP_TOGGLE); /* An empty map means kernel map */ if (!map) return 0; args[i++] = KBD_LOADKEYS; args[i++] = "-q"; args[i++] = "-C"; args[i++] = vc; if (utf8) args[i++] = "-u"; args[i++] = map; if (map_toggle) args[i++] = map_toggle; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd = NULL; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(loadkeys)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_LOADKEYS, pid, WAIT_LOG); } static int font_load_and_wait(const char *vc, Context *c) { const char *font, *map, *unimap, *args[9]; unsigned i = 0; pid_t pid; int r; assert(vc); assert(c); font = context_get_config(c, VC_FONT); map = context_get_config(c, VC_FONT_MAP); unimap = context_get_config(c, VC_FONT_UNIMAP); /* Any part can be set independently */ if (!font && !map && !unimap) return 0; args[i++] = KBD_SETFONT; args[i++] = "-C"; args[i++] = vc; if (map) { args[i++] = "-m"; args[i++] = map; } if (unimap) { args[i++] = "-u"; args[i++] = unimap; } if (font) args[i++] = font; args[i++] = NULL; if (DEBUG_LOGGING) { _cleanup_free_ char *cmd = NULL; cmd = strv_join((char**) args, " "); log_debug("Executing \"%s\"...", strnull(cmd)); } r = safe_fork("(setfont)", FORK_RESET_SIGNALS|FORK_CLOSE_ALL_FDS|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG, &pid); if (r < 0) return r; if (r == 0) { execv(args[0], (char **) args); _exit(EXIT_FAILURE); } return wait_for_terminate_and_check(KBD_SETFONT, pid, WAIT_LOG); } /* * A newly allocated VT uses the font from the source VT. Here * we update all possibly already allocated VTs with the configured * font. It also allows to restart systemd-vconsole-setup.service, * to apply a new font to all VTs. * * We also setup per-console utf8 related stuff: kbdmode, term * processing, stty iutf8. */ static void setup_remaining_vcs(int src_fd, unsigned src_idx, bool utf8) { struct console_font_op cfo = { .op = KD_FONT_OP_GET, .width = UINT_MAX, .height = UINT_MAX, .charcount = UINT_MAX, }; struct unimapinit adv = {}; struct unimapdesc unimapd; _cleanup_free_ struct unipair* unipairs = NULL; _cleanup_free_ void *fontbuf = NULL; int log_level = LOG_WARNING; int r; unipairs = new(struct unipair, USHRT_MAX); if (!unipairs) return (void) log_oom(); /* get metadata of the current font (width, height, count) */ r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) { /* We might be called to operate on the dummy console (to setup keymap * mainly) when fbcon deferred takeover is used for example. In such case, * setting font is not supported and is expected to fail. */ if (errno == ENOSYS) log_level = LOG_DEBUG; log_full_errno(log_level, errno, "KD_FONT_OP_GET failed while trying to get the font metadata: %m"); } else { /* verify parameter sanity first */ if (cfo.width > 32 || cfo.height > 32 || cfo.charcount > 512) log_warning("Invalid font metadata - width: %u (max 32), height: %u (max 32), count: %u (max 512)", cfo.width, cfo.height, cfo.charcount); else { /* * Console fonts supported by the kernel are limited in size to 32 x 32 and maximum 512 * characters. Thus with 1 bit per pixel it requires up to 65536 bytes. The height always * requires 32 per glyph, regardless of the actual height - see the comment above #define * max_font_size 65536 in drivers/tty/vt/vt.c for more details. */ fontbuf = malloc_multiply((cfo.width + 7) / 8 * 32, cfo.charcount); if (!fontbuf) { log_oom(); return; } /* get fonts from the source console */ cfo.data = fontbuf; r = ioctl(src_fd, KDFONTOP, &cfo); if (r < 0) log_warning_errno(errno, "KD_FONT_OP_GET failed while trying to read the font data: %m"); else { unimapd.entries = unipairs; unimapd.entry_ct = USHRT_MAX; r = ioctl(src_fd, GIO_UNIMAP, &unimapd); if (r < 0) log_warning_errno(errno, "GIO_UNIMAP failed while trying to read unicode mappings: %m"); else cfo.op = KD_FONT_OP_SET; } } } if (cfo.op != KD_FONT_OP_SET) log_full(log_level, "Fonts will not be copied to remaining consoles"); for (unsigned i = 1; i <= 63; i++) { char ttyname[sizeof("/dev/tty63")]; _cleanup_close_ int fd_d = -EBADF; if (i == src_idx || verify_vc_allocation(i) < 0) continue; /* try to open terminal */ xsprintf(ttyname, "/dev/tty%u", i); fd_d = open_terminal(ttyname, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd_d < 0) { log_warning_errno(fd_d, "Unable to open tty%u, fonts will not be copied: %m", i); continue; } if (verify_vc_kbmode(fd_d) < 0) continue; (void) toggle_utf8_vc(ttyname, fd_d, utf8); if (cfo.op != KD_FONT_OP_SET) continue; r = ioctl(fd_d, KDFONTOP, &cfo); if (r < 0) { int last_errno, mode; /* The fonts couldn't have been copied. It might be due to the * terminal being in graphical mode. In this case the kernel * returns -EINVAL which is too generic for distinguishing this * specific case. So we need to retrieve the terminal mode and if * the graphical mode is in used, let's assume that something else * is using the terminal and the failure was expected as we * shouldn't have tried to copy the fonts. */ last_errno = errno; if (ioctl(fd_d, KDGETMODE, &mode) >= 0 && mode != KD_TEXT) log_debug("KD_FONT_OP_SET skipped: tty%u is not in text mode", i); else log_warning_errno(last_errno, "KD_FONT_OP_SET failed, fonts will not be copied to tty%u: %m", i); continue; } /* Copy unicode translation table unimapd is a ushort count and a pointer * to an array of struct unipair { ushort, ushort }. */ r = ioctl(fd_d, PIO_UNIMAPCLR, &adv); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAPCLR failed, unimaps might be incorrect for tty%u: %m", i); continue; } r = ioctl(fd_d, PIO_UNIMAP, &unimapd); if (r < 0) { log_warning_errno(errno, "PIO_UNIMAP failed, unimaps might be incorrect for tty%u: %m", i); continue; } log_debug("Font and unimap successfully copied to %s", ttyname); } } static int find_source_vc(char **ret_path, unsigned *ret_idx) { int r, err = 0; _cleanup_free_ char *path = new(char, sizeof("/dev/tty63")); if (!path) return log_oom(); for (unsigned i = 1; i <= 63; i++) { _cleanup_close_ int fd = -EBADF; r = verify_vc_allocation(i); if (r < 0) { if (!err) err = -r; continue; } sprintf(path, "/dev/tty%u", i); fd = open_terminal(path, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (!err) err = -fd; continue; } r = verify_vc_kbmode(fd); if (r < 0) { if (!err) err = -r; continue; } /* all checks passed, return this one as a source console */ *ret_idx = i; *ret_path = TAKE_PTR(path); return TAKE_FD(fd); } return log_error_errno(err, "No usable source console found: %m"); } static int verify_source_vc(char **ret_path, const char *src_vc) { _cleanup_close_ int fd = -EBADF; char *path; int r; fd = open_terminal(src_vc, O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_error_errno(fd, "Failed to open %s: %m", src_vc); r = verify_vc_device(fd); if (r < 0) return log_error_errno(r, "Device %s is not a virtual console: %m", src_vc); r = verify_vc_allocation_byfd(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not allocated: %m", src_vc); r = verify_vc_kbmode(fd); if (r < 0) return log_error_errno(r, "Virtual console %s is not in K_XLATE or K_UNICODE: %m", src_vc); path = strdup(src_vc); if (!path) return log_oom(); *ret_path = path; return TAKE_FD(fd); } int main(int argc, char **argv) { _cleanup_(context_done) Context c = {}; _cleanup_free_ char *vc = NULL; _cleanup_close_ int fd = -EBADF; bool utf8, keyboard_ok; unsigned idx = 0; int r; log_setup(); umask(0022); if (argv[1]) fd = verify_source_vc(&vc, argv[1]); else fd = find_source_vc(&vc, &idx); if (fd < 0) return EXIT_FAILURE; utf8 = is_locale_utf8(); context_load_config(&c); /* Take lock around the remaining operation to avoid being interrupted by a tty reset operation * performed for services with TTYVHangup=yes. */ r = lock_generic(fd, LOCK_BSD, LOCK_EX); if (r < 0) { log_error_errno(r, "Failed to lock console: %m"); return EXIT_FAILURE; } (void) toggle_utf8_sysfs(utf8); (void) toggle_utf8_vc(vc, fd, utf8); r = font_load_and_wait(vc, &c); keyboard_ok = keyboard_load_and_wait(vc, &c, utf8) == 0; if (idx > 0) { if (r == 0) setup_remaining_vcs(fd, idx, utf8); else if (r == EX_OSERR) /* setfont returns EX_OSERR when ioctl(KDFONTOP/PIO_FONTX/PIO_FONTX) fails. * This might mean various things, but in particular lack of a graphical * console. Let's be generous and not treat this as an error. */ log_notice("Setting fonts failed with a \"system error\", ignoring."); else log_warning("Setting source virtual console failed, ignoring remaining ones"); } return IN_SET(r, 0, EX_OSERR) && keyboard_ok ? EXIT_SUCCESS : EXIT_FAILURE; }
21,675
33.904992
129
c
null
systemd-main/src/xdg-autostart-generator/fuzz-xdg-desktop.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fd-util.h" #include "fs-util.h" #include "fuzz.h" #include "rm-rf.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" #include "xdg-autostart-service.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(unlink_tempfilep) char name[] = "/tmp/fuzz-xdg-desktop.XXXXXX"; _cleanup_close_ int fd = -EBADF; _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL; _cleanup_(rm_rf_physical_and_freep) char *tmpdir = NULL; if (outside_size_range(size, 0, 65536)) return 0; /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(mkdtemp_malloc("/tmp/fuzz-xdg-desktop-XXXXXX", &tmpdir) >= 0); fd = mkostemp_safe(name); assert_se(fd >= 0); assert_se(write(fd, data, size) == (ssize_t) size); assert_se(service = xdg_autostart_service_parse_desktop(name)); assert_se(service->name = strdup("fuzz-xdg-desktop.service")); (void) xdg_autostart_service_generate_unit(service, tmpdir); return 0; }
1,351
32.8
83
c
null
systemd-main/src/xdg-autostart-generator/test-xdg-autostart.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fd-util.h" #include "fs-util.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" #include "xdg-autostart-service.h" TEST(translate_name) { _cleanup_free_ char *t = NULL; assert_se(t = xdg_autostart_service_translate_name("a-b.blub.desktop")); assert_se(streq(t, "app-a\\[email protected]")); } static void test_xdg_format_exec_start_one(const char *exec, const char *expected) { _cleanup_free_ char* out = NULL; xdg_autostart_format_exec_start(exec, &out); log_info("In: '%s', out: '%s', expected: '%s'", exec, out, expected); assert_se(streq(out, expected)); } TEST(xdg_format_exec_start) { _cleanup_free_ char *home = NULL; _cleanup_free_ char *expected1 = NULL, *expected2 = NULL; assert_se(get_home_dir(&home) >= 0); test_xdg_format_exec_start_one("/bin/sleep 100", "/bin/sleep 100"); /* All standardised % identifiers are stripped. */ test_xdg_format_exec_start_one("/bin/sleep %f \"%F\" %u %U %d %D\t%n %N %i %c %k %v %m", "/bin/sleep"); /* Unknown % identifier currently remain, but are escaped. */ test_xdg_format_exec_start_one("/bin/sleep %X \"%Y\"", "/bin/sleep %%X %%Y"); test_xdg_format_exec_start_one("/bin/sleep \";\\\"\"", "/bin/sleep \";\\\"\""); /* tilde is expanded only if standalone or at the start of a path */ expected1 = strjoin("/bin/ls ", home); test_xdg_format_exec_start_one("/bin/ls ~", expected1); expected2 = strjoin("/bin/ls ", home, "/foo"); test_xdg_format_exec_start_one("/bin/ls \"~/foo\"", expected2); test_xdg_format_exec_start_one("/bin/ls ~foo", "/bin/ls ~foo"); test_xdg_format_exec_start_one("/bin/ls foo~", "/bin/ls foo~"); } static const char* const xdg_desktop_file[] = { ("[Desktop Entry]\n" "Exec\t =\t /bin/sleep 100\n" /* Whitespace Before/After = must be ignored */ "OnlyShowIn = A;B;\n" "NotShowIn=C;;D\\\\\\;;E\n"), /* "C", "", "D\;", "E" */ ("[Desktop Entry]\n" "Exec=a\n" "Exec=b\n"), ("[Desktop Entry]\n" "Hidden=\t true\n"), ("[Desktop Entry]\n" "Hidden=\t True\n"), }; static void test_xdg_desktop_parse_one(unsigned i, const char *s) { _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-xdg-autostart-parser.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; _cleanup_(xdg_autostart_service_freep) XdgAutostartService *service = NULL; log_info("== %s[%u] ==", __func__, i); assert_se(fmkostemp_safe(name, "r+", &f) == 0); assert_se(fwrite(s, strlen(s), 1, f) == 1); rewind(f); assert_se(service = xdg_autostart_service_parse_desktop(name)); switch (i) { case 0: assert_se(streq(service->exec_string, "/bin/sleep 100")); assert_se(strv_equal(service->only_show_in, STRV_MAKE("A", "B"))); assert_se(strv_equal(service->not_show_in, STRV_MAKE("C", "D\\;", "E"))); assert_se(!service->hidden); break; case 1: /* The second entry is not permissible and will be ignored (and error logged). */ assert_se(streq(service->exec_string, "a")); break; case 2: case 3: assert_se(service->hidden); break; } } TEST(xdg_desktop_parse) { for (size_t i = 0; i < ELEMENTSOF(xdg_desktop_file); i++) test_xdg_desktop_parse_one(i, xdg_desktop_file[i]); } DEFINE_TEST_MAIN(LOG_DEBUG);
3,741
34.638095
111
c
null
systemd-main/src/xdg-autostart-generator/xdg-autostart-condition.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "main-func.h" #include "strv.h" /* * This binary is intended to be run as an ExecCondition= in units generated * by the xdg-autostart-generator. It does the appropriate checks against * XDG_CURRENT_DESKTOP that are too advanced for simple ConditionEnvironment= * matches. */ static int run(int argc, char *argv[]) { _cleanup_strv_free_ char **only_show_in = NULL, **not_show_in = NULL, **desktops = NULL; const char *xdg_current_desktop; if (argc != 3) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Wrong argument count. Expected the OnlyShowIn= and NotShowIn= sets, each colon separated."); xdg_current_desktop = getenv("XDG_CURRENT_DESKTOP"); if (xdg_current_desktop) { desktops = strv_split(xdg_current_desktop, ":"); if (!desktops) return log_oom(); } only_show_in = strv_split(argv[1], ":"); not_show_in = strv_split(argv[2], ":"); if (!only_show_in || !not_show_in) return log_oom(); /* Each desktop in XDG_CURRENT_DESKTOP needs to be matched in order. */ STRV_FOREACH(d, desktops) { if (strv_contains(only_show_in, *d)) return 0; if (strv_contains(not_show_in, *d)) return 1; } /* non-zero exit code when only_show_in has a proper value */ return !strv_isempty(only_show_in); } DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
1,628
34.413043
132
c
null
systemd-main/src/xdg-autostart-generator/xdg-autostart-service.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "macro.h" typedef struct XdgAutostartService { char *name; char *path; char *description; /* Name in XDG desktop file */ char *type; /* Purely as an assertion check */ char *exec_string; char *working_directory; char **only_show_in; char **not_show_in; char *try_exec; char *autostart_condition; /* This is mostly GNOME specific */ char *kde_autostart_condition; char *gnome_autostart_phase; bool hidden; bool systemd_skip; } XdgAutostartService; XdgAutostartService * xdg_autostart_service_free(XdgAutostartService *s); DEFINE_TRIVIAL_CLEANUP_FUNC(XdgAutostartService*, xdg_autostart_service_free); char *xdg_autostart_service_translate_name(const char *name); int xdg_autostart_format_exec_start(const char *exec, char **ret_exec_start); XdgAutostartService *xdg_autostart_service_parse_desktop(const char *path); int xdg_autostart_service_generate_unit(const XdgAutostartService *service, const char *dest);
1,105
28.891892
94
h
piclas
piclas-master/src/piclas.h
!=================================================================================================================================== ! Here, preprocessor variables for different equation systems and abbreviations for specific expressions are defined !=================================================================================================================================== ! Abbrevations #ifndef __FILENAME__ #define __FILENAME__ __FILE__ #endif #define __STAMP__ __FILENAME__,__LINE__,__DATE__,__TIME__ ! Calculate GCC version #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) ! Size of data types #define SIZEOF_F(x) (STORAGE_SIZE(x)/8) #define SIZE_LOG KIND(.TRUE.) #define SIZE_INT KIND(INT(1)) #define SIZE_INT4 4 #define SIZE_INT8 8 #define SIZE_REAL KIND(REAL(1)) #define SIZE_CHAR KIND('a') #ifdef DEBUG_MEMORY #define Allocate_Shared(a,b,c) Allocate_Shared_DEBUG(a,b,c,'b') #endif #ifdef MEASURE_MPI_WAIT ! Field solver #if USE_HDG #define MPIW8SIZEFIELD 4 #else #define MPIW8SIZEFIELD 2 #endif ! Particle solver #ifdef PARTICLES #define MPIW8SIZEPART 6 #else #define MPIW8SIZEPART 0 #endif ! Combination #define MPIW8SIZE (2+MPIW8SIZEFIELD+MPIW8SIZEPART) #endif ! Deactivate PURE subroutines/functions when using DEBUG #if USE_DEBUG #define PPURE #else #define PPURE PURE #endif ! Replace function with dummy function and additional argument #define UNLOCK_AND_FREE(a) UNLOCK_AND_FREE_DUMMY(a,'a') #ifdef GNU #define CHECKSAFEINT(x,k) IF(x>HUGE(1_ k).OR.x<-HUGE(1_ k)) CALL ABORT(__STAMP__,'Integer conversion failed: out of range!') #define CHECKSAFEREAL(x,k) IF(x>HUGE(1._ k).OR.x<-HUGE(1._ k)) CALL ABORT(__STAMP__,'Real conversion failed: out of range!') #elif CRAY #define CHECKSAFEINT(x,k) #define CHECKSAFEREAL(x,k) #else #define CHECKSAFEINT(x,k) IF(x>HUGE(1_ ## k).OR.x<-HUGE(1_ ## k)) CALL ABORT(__STAMP__,'Integer conversion failed: out of range!') #define CHECKSAFEREAL(x,k) IF(x>HUGE(1._ ## k).OR.x<-HUGE(1._ ## k)) CALL ABORT(__STAMP__,'Real conversion failed: out of range!') #endif ! Test for equality: read description in src/globals/globals.f90 for further infos ! for variable relative tolerance #define ALMOSTEQUALRELATIVE(x,y,tol) (ABS((x)-(y)).LE.MAX(ABS(x),ABS(y))*(tol)) ! for fixed relative tolerance (for double precision use twice the machine precision 2E-52 ~ 2.22e-16 -> 2*2.22E-16=4.44E-16) #define ALMOSTEQUAL(x,y) (ABS((x)-(y)).LE.MAX(ABS(x),ABS(y))*(4.441E-16)) #define ALMOSTALMOSTEQUAL(x,y) (ABS((x)-(y)).LE.MAX(ABS(x),ABS(y))*(1E-10)) #define ALMOSTZERO(x) (ABS(x).LE.(2.22e-16)) ! Check if the exponent is within the range of machine precision, RANGE() gives the maximum exponent of the given variable type #define CHECKEXP(x) (ABS(x).LT.REAL(RANGE(1.))) #if USE_MPI # define SWRITE IF(MPIRoot) WRITE #if USE_LOADBALANCE # define LBWRITE IF(MPIRoot.AND.(.NOT.PerformLoadBalance)) WRITE #else /*USE_LOADBALANCE*/ # define LBWRITE IF(MPIRoot) WRITE #endif /*USE_LOADBALANCE*/ # define IPWRITE(a,b) WRITE(a,b)myRank, # define LWRITE IF(myComputeNodeRank.EQ.0) WRITE # define GETTIME(a) a=MPI_WTIME() #else # define SWRITE WRITE # define LBWRITE WRITE # define IPWRITE(a,b) WRITE(a,b)0, # define LWRITE WRITE # define GETTIME(a) CALL CPU_TIME(a) #endif #define ERRWRITE(a,b) WRITE(UNIT_errOut,b) #define LOGWRITE(a,b) IF(Logging) WRITE(UNIT_logOut,b) #define LOGWRITE_BARRIER IF(Logging) CALL ReOpenLogFile() #define SDEALLOCATE(A) IF(ALLOCATED(A)) DEALLOCATE(A) #define SNULLIFY(A) IF(ASSOCIATED(A)) NULLIFY(A) #if USE_MPI #define ALLOCPOINT POINTER #define ADEALLOCATE(A) IF(ASSOCIATED(A)) NULLIFY(A) #else #define ALLOCPOINT ALLOCATABLE #define ADEALLOCATE(A) IF(ALLOCATED(A)) DEALLOCATE(A) #endif #ifdef OPTIMIZED #define PP_IJK i,0,0 #define PP_ij i,0 #else #define PP_IJK i,j,k #define PP_ij i,j #endif #ifdef INTKIND8 #define MPI_INTEGER_INT_KIND MPI_INTEGER8 #else #define MPI_INTEGER_INT_KIND MPI_INTEGER #endif ! number of entry in each line of ElemInfo #define ELEMINFOSIZE_H5 6 #if USE_MPI #define ELEMINFOSIZE 8 #else #define ELEMINFOSIZE 6 #endif /* USE_MPI*/ ! ElemInfo in H5 file #define ELEM_TYPE 1 #define ELEM_ZONE 2 #define ELEM_FIRSTSIDEIND 3 #define ELEM_LASTSIDEIND 4 #define ELEM_FIRSTNODEIND 5 #define ELEM_LASTNODEIND 6 ! ElemInfo for shared array #define ELEM_RANK 7 #define ELEM_HALOFLAG 8 ! number of entries in each line of SideInfo #define SIDEINFOSIZE_H5 5 #define SIDEINFOSIZE 8 #define SIDE_TYPE 1 #define SIDE_ID 2 #define SIDE_NBELEMID 3 #define SIDE_FLIP 4 #define SIDE_BCID 5 #define SIDE_ELEMID 6 #define SIDE_LOCALID 7 #define SIDE_NBSIDEID 8 #define SIDE_NBELEMTYPE 9 ! surface sampling entries #define SURF_SIDEID 1 #define SURF_RANK 2 #define SURF_LEADER 3 ! Predefined "PARAMETER-like" variables #define XI_MINUS 5 #define XI_PLUS 3 #define ETA_MINUS 2 #define ETA_PLUS 4 #define ZETA_MINUS 1 #define ZETA_PLUS 6 ! Entry position in ElemBCSides #define ELEM_NBR_BCSIDES 1 #define ELEM_FIRST_BCSIDE 2 ! Entry position in FIBGMToProc #define FIBGM_FIRSTPROCIND 1 #define FIBGM_NPROCS 2 #define FIBGM_NLOCALPROCS 3 ! Entry position in SideBCMetrics #define BCSIDE_SIDEID 1 #define BCSIDE_ELEMID 2 #define BCSIDE_DISTANCE 3 #define BCSIDE_RADIUS 4 #define BCSIDE_ORIGINX 5 #define BCSIDE_ORIGINY 6 #define BCSIDE_ORIGINZ 7 ! Entry position in SideToElem #define S2E_ELEM_ID 1 #define S2E_NB_ELEM_ID 2 #define S2E_LOC_SIDE_ID 3 #define S2E_NB_LOC_SIDE_ID 4 #define S2E_FLIP 5 ! Entry position in SideToElem2 #define S2E2_ELEM_ID 1 #define S2E2_SIDE_ID 2 #define S2E2_LOC_SIDE_ID 3 #define S2E2_FLIP 4 ! Entry position in ElemToSide #define E2S_SIDE_ID 1 #define E2S_FLIP 2 ! Entry position in ElemToElem #define E2E_NB_ELEM_ID 1 #define E2E_NB_LOC_SIDE_ID 2 ! Entry position in BC #define BC_TYPE 1 #define BC_STATE 2 #define BC_ALPHA 3 ! Entry position in BC #define MI_SIDEID 1 #define MI_FLIP 2 !#define DEBUGMESH ! define side indeces used in sidetype array #define PLANAR_RECT 0 #define PLANAR_NONRECT 1 #define BILINEAR 2 #define PLANAR_CURVED 3 #define CURVED 4 ! entries for PartExchange #define EXCHANGE_PROC_SIZE 2 #define EXCHANGE_PROC_TYPE 1 #define EXCHANGE_PROC_RANK 2 ! entries for PartHaloToProc #define NATIVE_ELEM_ID 1 #define NATIVE_PROC_ID 2 #define LOCAL_PROC_ID 3 !#define NATIVE_SIDE_ID 1 #define LOCAL_SEND_ID 4 ! Entry position for interface type for selecting the corresponding Riemann solver #define RIEMANN_VACUUM 0 #define RIEMANN_PML 1 #define RIEMANN_DIELECTRIC 2 #define RIEMANN_DIELECTRIC2VAC 3 #define RIEMANN_VAC2DIELECTRIC 4 #define RIEMANN_DIELECTRIC2VAC_NC 5 #define RIEMANN_VAC2DIELECTRIC_NC 6 ! formats ! print to std out like " 1.41421356237310E+000 -1.41421356237310E+000 -1.41421356237310E+000" ! (looks good and prevents the first digit of being a zero) #define WRITEFORMAT '(ES25.14E3)' ! print to csv file like "0.1414213562373095E+001,-.1414213562373095E+001,-.1414213562373095E+001" ! (does not look that good but it saves disk space) #define CSVFORMAT '(A1,E23.16E3)' ! Load Balance (LB) position in array for measuring the time that is spent on specific operations #define LB_DG 1 #define LB_DGANALYZE 2 #define LB_DGCOMM 3 #define LB_PML 4 #define LB_EMISSION 5 #define LB_TRACK 6 #define LB_INTERPOLATION 7 #define LB_DEPOSITION 8 #define LB_CARTMESHDEPO 9 #define LB_PUSH 10 #define LB_PARTANALYZE 11 #define LB_PARTCOMM 12 #define LB_DSMC 13 #define LB_DSMCANALYZE 14 #define LB_SPLITMERGE 15 #define LB_UNFP 16 #define LB_SURF 17 #define LB_SURFFLUX 18 #define LB_SURFCOMM 19 #define LB_ADAPTIVE 20 #define LB_NTIMES 20 ! DSMC_analyze indeces used in arrays #define DSMC_VELOX 1 #define DSMC_VELOY 2 #define DSMC_VELOZ 3 #define DSMC_TEMPX 4 #define DSMC_TEMPY 5 #define DSMC_TEMPZ 6 #define DSMC_NUMDENS 7 #define DSMC_TVIB 8 #define DSMC_TROT 9 #define DSMC_TELEC 10 #define DSMC_SIMPARTNUM 11 #define DSMC_TEMPMEAN 12 #define DSMC_NVARS 12 ! Sampwall_analyze indeces used in arrays #define SAMPWALL_ETRANSOLD 1 #define SAMPWALL_ETRANSNEW 2 #define SAMPWALL_EROTOLD 3 #define SAMPWALL_EROTNEW 4 #define SAMPWALL_EVIBOLD 5 #define SAMPWALL_EVIBNEW 6 #define SAMPWALL_EELECOLD 7 #define SAMPWALL_EELECNEW 8 #define SAMPWALL_DELTA_MOMENTUMX 9 #define SAMPWALL_DELTA_MOMENTUMY 10 #define SAMPWALL_DELTA_MOMENTUMZ 11 #define SAMPWALL_NVARS 11 #define MACROSURF_NVARS 6 ! Tracking method #define REFMAPPING 1 #define TRACING 2 #define TRIATRACKING 3 ! Time Step Minimum: dt_Min #define DT_MIN 1 #define DT_ANALYZE 2 #define DT_END 3 #define DT_BR_SWITCH 4 ! Secondary electron emission #define SEE_MODELS_ID 5,6,7,8,9,10,11
9,217
27.896552
133
h
piclas
piclas-master/src/output/read_userblock.c
#include <string.h> #include <stdio.h> extern char userblock_start; extern char userblock_end; extern char userblock_size; long get_userblock_size_(void) { //return (unsigned long)(&userblock_size); // Fixes mysterious bug occurring on some systems potentially due to the new GCC 7.3 // where userblock_size is wrong though the symbol is correctly defined. // Since userblock_size = userblock_end - userblock_start , we just compute it on the fly. return (unsigned long)(&userblock_end-&userblock_start); } long get_inifile_size(char* filename) { FILE* fp = fopen(filename, "rb"); fseek(fp,0,SEEK_END); long length=ftell(fp); fclose(fp); return length; } void insert_userblock(char* filename, char* inifilename, char* inifilename2) { FILE* fp = fopen(filename, "w"); rewind(fp); fprintf(fp, "{[( START USERBLOCK )]}\n"); // ini file fprintf(fp, "{[( INIFILE )]}\n"); FILE* fini = fopen(inifilename, "rb"); int c; do { c = fgetc (fini); if (c != EOF) fputc((char)c, fp); } while (c != EOF); fclose(fini); // DSMC ini file int lenIniFile2 = strlen(inifilename2); if (lenIniFile2>0) { fprintf(fp, "{[( DSMCFILE )]}\n"); FILE* fini2 = fopen(inifilename2, "rb"); int c; do { c = fgetc (fini2); if (c != EOF) fputc((char)c, fp); } while (c != EOF); fclose(fini2); } // compressed data ( as tar.xz ) fprintf(fp, "{[( COMPRESSED )]}\n"); fprintf(fp, "userblock.txt\n"); // filename fprintf(fp, "%ld\n", get_userblock_size_()); // filesize char* p = &userblock_start; while ( p != &userblock_end ) fputc(*p++, fp); fprintf(fp, "\n"); fprintf(fp, "{[( END USERBLOCK )]}\n"); fclose(fp); } void copy_userblock(char* outfilename, char* infilename) { FILE* fout = fopen(outfilename,"rb+"); FILE* fin = fopen(infilename, "r"); rewind(fout); int c; do { c = fgetc (fin); if (c != EOF) fputc((char) c, fout); } while (c != EOF); fclose(fin); fclose(fout); }
2,054
25.346154
93
c
piclas
piclas-master/src/posti/visu/pluginTypes_visu.h
/* !================================================================================================================================= ! Copyright (c) 2016 Prof. Claus-Dieter Munz ! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods. ! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/ ! ! FLEXI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ! as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ! ! FLEXI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty ! of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License v3.0 for more details. ! ! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>. !================================================================================================================================= */ #ifndef PLUGIN_DUMMY_H #define PLUGIN_DUMMY_H struct DoubleARRAY{ int len; int dim; double* data; }; struct IntARRAY{ int len; int dim; int* data; }; struct CharARRAY{ int len; int dim; char* data; }; #endif /* PLUGIN_DUMMY_H */
1,397
34.846154
130
h
piclas
piclas-master/src/posti/visu/paraviewReader/visuReader.h
/* !================================================================================================================================= ! Copyright (c) 2016 Prof. Claus-Dieter Munz ! This file is part of FLEXI, a high-order accurate framework for numerically solving PDEs with discontinuous Galerkin methods. ! For more information see https://www.flexi-project.org and https://nrg.iag.uni-stuttgart.de/ ! ! FLEXI is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ! as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ! ! FLEXI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty ! of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License v3.0 for more details. ! ! You should have received a copy of the GNU General Public License along with FLEXI. If not, see <http://www.gnu.org/licenses/>. !================================================================================================================================= */ #ifndef VISUREADER_H #define VISUREADER_H #include <vtkUnstructuredGridAlgorithm.h> #include <cstring> #include <algorithm> #include <iostream> #include <vector> #include "vtkMPI.h" #include "vtkMPICommunicator.h" #include "vtkMPIController.h" #include "vtkDataArraySelection.h" #include "vtkCallbackCommand.h" #include <vtkSmartPointer.h> #include "vtkStringArray.h" #include "../pluginTypes_visu.h" #include "vtkIOParallelModule.h" // For export macro #include "vtkMultiBlockDataSetAlgorithm.h" // MPI class vtkMultiProcessController; // MPI class VTKIOPARALLEL_EXPORT visuReader : public vtkMultiBlockDataSetAlgorithm { public: vtkTypeMacro(visuReader,vtkMultiBlockDataSetAlgorithm); static visuReader *New(); // macros to set GUI changes to variables // gui interaction vtkSetStringMacro(FileName); vtkSetStringMacro(MeshFileOverwrite); vtkSetMacro(NVisu,int); vtkSetStringMacro(NodeTypeVisu); vtkSetMacro(Avg2d,int); vtkSetMacro(DGonly,int); // Adds names of files to be read. The files are read in the order they are added. void AddFileName(const char* fname); // Remove all file names. void RemoveAllFileNames(); vtkSetStringMacro(ParameterFileOverwrite); int GetNumberOfVarArrays(); const char* GetVarArrayName(int index); int GetVarArrayStatus(const char* name); void SetVarArrayStatus(const char* name, int status); void DisableAllVarArrays(); void EnableAllVarArrays(); int GetNumberOfBCArrays(); const char* GetBCArrayName(int index); int GetBCArrayStatus(const char* name); void SetBCArrayStatus(const char* name, int status); void DisableAllBCArrays(); void EnableAllBCArrays(); // MPI void SetController(vtkMultiProcessController *); vtkGetObjectMacro(Controller, vtkMultiProcessController); // MPI void ConvertToFortran(char* fstring, const char* cstring); // struct to exchange arrays between fortran and C struct DoubleARRAY coords_DG; struct DoubleARRAY values_DG; struct IntARRAY nodeids_DG; struct DoubleARRAY coords_FV; struct DoubleARRAY values_FV; struct IntARRAY nodeids_FV; struct CharARRAY varnames; struct DoubleARRAY coordsSurf_DG; struct DoubleARRAY valuesSurf_DG; struct IntARRAY nodeidsSurf_DG; struct DoubleARRAY coordsSurf_FV; struct DoubleARRAY valuesSurf_FV; struct IntARRAY nodeidsSurf_FV; struct CharARRAY varnamesSurf; int RequestInformation(vtkInformation *, vtkInformationVector **, vtkInformationVector *); int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *); void InsertData(vtkMultiBlockDataSet* mb, int blockno, struct DoubleARRAY* coords, struct DoubleARRAY* values, struct IntARRAY* nodeids, struct CharARRAY* varnames); vtkDataArraySelection* VarDataArraySelection; vtkDataArraySelection* BCDataArraySelection; // The observer to modify this object when the array selections are modified. vtkCallbackCommand* SelectionObserver; // Callback registered with the SelectionObserver. static void SelectionModifiedCallback(vtkObject* caller, unsigned long eid, void* clientdata, void* calldata); char* FileName; int NVisu; char* NodeTypeVisu; int Avg2d; int DGonly; char* ParameterFileOverwrite; char* MeshFileOverwrite; std::vector<bool> VarNames_selected; std::vector<bool> BCNames_selected; int NumProcesses; int ProcessId; // all loaded filenames, timesteps (multiple for timeseries) std::vector<std::string> FileNames; std::vector<double> Timesteps; int FindClosestTimeStep(double requestedTimeValue); //void SetNodeTypeVisu(const char* nodetypevisu); vtkStringArray* GetNodeTypeVisuList(); protected: visuReader(); ~visuReader(); virtual int FillOutputPortInformation(int port, vtkInformation* info); private: // MPI vtkMultiProcessController *Controller; MPI_Comm mpiComm; }; #endif //VISUREADER_H
5,381
33.5
130
h
npci
npci-master/src/npci.c
#include <errno.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <string.h> #ifdef HAVE_ALLOCA_H # include <alloca.h> #elif !defined alloca # ifdef __GNUC__ # define alloca __builtin_alloca # elif defined(__DECC) # define alloca __ALLOCA # elif defined(_MSC_VER) # include <malloc.h> # define alloca _alloca # elif defined(__sun) # include <alloca.h> # else # include <stdlib.h> # endif #endif #include <Rversion.h> #if R_VERSION >= R_Version(3, 6, 2) # define USE_FC_LEN_T #endif #if R_VERSION <= R_Version(3, 3, 1) # define NO_C_HEADERS #endif #define R_NO_REMAP 1 #include <R.h> #include <Rinternals.h> #include <Rmath.h> #include <R_ext/Lapack.h> #include <R_ext/Rdynload.h> #undef NO_C_HEADERS #undef R_NO_REMAP #undef USE_FC_LEN_T #ifndef FCONE # define FCONE #endif static SEXP squaredExponential_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sig_f_sq * exp(-temp1); cov[row + col * n] = temp1; cov[col + row * n] = temp1; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } cov[row + col * n] = sig_f_sq * exp(-temp1); } } } return R_NilValue; } static SEXP matern_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double nu = exp(pars[0]); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i + 1]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; double constTerm = (1.0 - nu) * M_LN2 - Rf_lgammafn(nu); if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sqrt(2.0 * nu * temp1); temp1 = log(Rf_bessel_k(temp1, nu, 1.0)) - temp1 + nu * log(temp1); temp1 = sig_f_sq * exp(constTerm + temp1); cov[row + col * n] = temp1; cov[col + row * n] = temp1; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sqrt(2.0 * nu * temp1); temp1 = log(Rf_bessel_k(temp1, nu, 1.0)) - temp1 + nu * log(temp1); cov[row + col * n] = sig_f_sq * exp(constTerm + temp1); } } } return R_NilValue; } static SEXP exponential_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sig_f_sq * exp(-sqrt(temp1)); cov[row + col * n] = temp1; cov[col + row * n] = temp1; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } cov[row + col * n] = sig_f_sq * exp(-sqrt(temp1)); } } } return R_NilValue; } static SEXP gammaExponential_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double gamma = exp(pars[0]); gamma = 2.0 * gamma / (1.0 + gamma); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i + 1]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sig_f_sq * exp(-pow(sqrt(temp1), gamma)); cov[row + col * n] = temp1; cov[col + row * n] = temp1; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } cov[row + col * n] = sig_f_sq * exp(-pow(sqrt(temp1), gamma)); } } } return R_NilValue; } static SEXP rationalQuadratic_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double alpha = exp(pars[0]); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i + 1]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } temp1 = sig_f_sq * pow(1.0 + temp1 / (2.0 * alpha), -alpha); cov[row + col * n] = temp1; cov[col + row * n] = temp1; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double temp1 = 0.0; for (size_t i = 0; i < p; ++i) { double temp2 = (xRow[i] - x_Row[i]) / scales[i]; temp1 += temp2 * temp2; } cov[row + col * n] = sig_f_sq * pow(1.0 + temp1 / (2.0 * alpha), -alpha); } } } return R_NilValue; } static SEXP neuralNetwork_updateCovMatrix(SEXP covExpr, SEXP xtExpr, SEXP x_tExpr, SEXP parsExpr, SEXP sig_f_sqExpr) { int* dims = INTEGER(Rf_getAttrib(xtExpr, R_DimSymbol)); size_t p = (size_t) dims[0]; size_t n = (size_t) dims[1]; size_t m = (size_t) INTEGER(Rf_getAttrib(x_tExpr, R_DimSymbol))[1]; double* cov = REAL(covExpr); double* xt = REAL(xtExpr); double* x_t = REAL(x_tExpr); double* pars = REAL(parsExpr); double offset = exp(pars[0]); double* scales = (double*) alloca(p * sizeof(double)); for (size_t i = 0; i < p; ++i) scales[i] = exp(-0.5 * pars[i + 1]); double sig_f_sq = REAL(sig_f_sqExpr)[0]; if (xt == x_t) { for (size_t row = 0; row < (n - 1); ++row) { double* x_Row = x_t + row * p; for (size_t col = (row + 1); col < n; ++col) { double* xRow = xt + col * p; double crossSum = offset; double xSum = offset; double x_Sum = offset; for (size_t i = 0; i < p; ++i) { crossSum += ( xRow[i] * x_Row[i]) / scales[i]; xSum += ( xRow[i] * xRow[i]) / scales[i]; x_Sum += (x_Row[i] * x_Row[i]) / scales[i]; } crossSum = sig_f_sq * M_2_PI * asin(crossSum / sqrt((1.0 + xSum) * (1.0 + x_Sum))); cov[row + col * n] = crossSum; cov[col + row * n] = crossSum; } cov[row + row * n] = sig_f_sq; } cov[n * n - 1] = sig_f_sq; } else { for (size_t row = 0; row < n; ++row) { double* xRow = xt + row * p; for (size_t col = 0; col < m; ++col) { double* x_Row = x_t + col * p; double crossSum = offset; double xSum = offset; double x_Sum = offset; for (size_t i = 0; i < p; ++i) { crossSum += ( xRow[i] * x_Row[i]) / scales[i]; xSum += ( xRow[i] * xRow[i]) / scales[i]; x_Sum += (x_Row[i] * x_Row[i]) / scales[i]; } crossSum = sig_f_sq * M_2_PI * asin(crossSum / sqrt((1.0 + xSum) * (1.0 + x_Sum))); cov[row + col * n] = crossSum; } } } return R_NilValue; } static SEXP updateLeftFactor(SEXP LExpr, SEXP covExpr) { size_t dim = (size_t) INTEGER(Rf_getAttrib(LExpr, R_DimSymbol))[1]; double* L = REAL(LExpr); const double* cov = REAL(covExpr); memcpy(L, cov, dim * dim * sizeof(double)); for (size_t i = 0; i < dim; ++i) L[i + i * dim] += 1.0; char triangleType = 'L'; int i_dim = (int) dim; int lapackResult; F77_CALL(dpotrf)(&triangleType, &i_dim, L, &i_dim, &lapackResult FCONE); if (lapackResult < 0) return Rf_ScalarInteger(EINVAL); if (lapackResult > 0) return Rf_ScalarInteger(EDOM); for (size_t row = 0; row < dim - 1; ++row) { for (size_t col = row + 1; col < dim; ++col) { L[row + col * dim] = 0.0; } } return Rf_ScalarInteger(0.0); } #define defineFunction(_N_, _F_, _A_) { _N_, (DL_FUNC) (&_F_), _A_ } static R_CallMethodDef R_callMethods[] = { defineFunction("npci_squaredExponential_updateCovMatrix", squaredExponential_updateCovMatrix, 5), defineFunction("npci_matern_updateCovMatrix", matern_updateCovMatrix, 5), defineFunction("npci_exponential_updateCovMatrix", exponential_updateCovMatrix, 5), defineFunction("npci_gammaExponential_updateCovMatrix", gammaExponential_updateCovMatrix, 5), defineFunction("npci_rationalQuadratic_updateCovMatrix", rationalQuadratic_updateCovMatrix, 5), defineFunction("npci_neuralNetwork_updateCovMatrix", neuralNetwork_updateCovMatrix, 5), defineFunction("npci_updateLeftFactor", updateLeftFactor, 2), { NULL, NULL, 0 } }; #undef defineFunction typedef struct { const char* name; DL_FUNC function; } C_CallMethodDef; void R_init_npci(DllInfo* info) { R_registerRoutines(info, NULL, R_callMethods, NULL, NULL); R_useDynamicSymbols(info, (Rboolean) false); }
13,525
28.150862
121
c
php-src
php-src-master/TSRM/tsrm_win32.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Daniel Beulshausen <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef TSRM_WIN32_H #define TSRM_WIN32_H #include "TSRM.h" #include <windows.h> #include <sys/utime.h> #include "win32/ipc.h" struct ipc_perm { key_t key; unsigned short uid; unsigned short gid; unsigned short cuid; unsigned short cgid; unsigned short mode; unsigned short seq; }; struct shmid_ds { struct ipc_perm shm_perm; size_t shm_segsz; time_t shm_atime; time_t shm_dtime; time_t shm_ctime; unsigned short shm_cpid; unsigned short shm_lpid; short shm_nattch; }; typedef struct { FILE *stream; HANDLE prochnd; } process_pair; typedef struct { void *addr; HANDLE segment; struct shmid_ds *descriptor; } shm_pair; typedef struct { process_pair *process; shm_pair *shm; int process_size; int shm_size; char *comspec; HANDLE impersonation_token; PSID impersonation_token_sid; } tsrm_win32_globals; #ifdef ZTS # define TWG(v) TSRMG_STATIC(win32_globals_id, tsrm_win32_globals *, v) TSRMLS_CACHE_EXTERN() #else # define TWG(v) (win32_globals.v) #endif #define IPC_PRIVATE 0 #define IPC_CREAT 00001000 #define IPC_EXCL 00002000 #define IPC_NOWAIT 00004000 #define IPC_RMID 0 #define IPC_SET 1 #define IPC_STAT 2 #define IPC_INFO 3 #define SHM_R PAGE_READONLY #define SHM_W PAGE_READWRITE #define SHM_RDONLY FILE_MAP_READ #define SHM_RND FILE_MAP_WRITE #define SHM_REMAP FILE_MAP_COPY const char * tsrm_win32_get_path_sid_key(const char *pathname, size_t pathname_len, size_t *key_len); TSRM_API void tsrm_win32_startup(void); TSRM_API void tsrm_win32_shutdown(void); TSRM_API FILE *popen_ex(const char *command, const char *type, const char *cwd, const char *env); TSRM_API FILE *popen(const char *command, const char *type); TSRM_API int pclose(FILE *stream); TSRM_API int tsrm_win32_access(const char *pathname, int mode); TSRM_API int win32_utime(const char *filename, struct utimbuf *buf); TSRM_API int shmget(key_t key, size_t size, int flags); TSRM_API void *shmat(int key, const void *shmaddr, int flags); TSRM_API int shmdt(const void *shmaddr); TSRM_API int shmctl(int key, int cmd, struct shmid_ds *buf); #endif
3,084
27.831776
101
h
php-src
php-src-master/Zend/zend_alloc_sizes.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ALLOC_SIZES_H #define ZEND_ALLOC_SIZES_H #define ZEND_MM_CHUNK_SIZE ((size_t) (2 * 1024 * 1024)) /* 2 MB */ #define ZEND_MM_PAGE_SIZE (4 * 1024) /* 4 KB */ #define ZEND_MM_PAGES (ZEND_MM_CHUNK_SIZE / ZEND_MM_PAGE_SIZE) /* 512 */ #define ZEND_MM_FIRST_PAGE (1) #define ZEND_MM_MIN_SMALL_SIZE 8 #define ZEND_MM_MAX_SMALL_SIZE 3072 #define ZEND_MM_MAX_LARGE_SIZE (ZEND_MM_CHUNK_SIZE - (ZEND_MM_PAGE_SIZE * ZEND_MM_FIRST_PAGE)) /* num, size, count, pages */ #define ZEND_MM_BINS_INFO(_, x, y) \ _( 0, 8, 512, 1, x, y) \ _( 1, 16, 256, 1, x, y) \ _( 2, 24, 170, 1, x, y) \ _( 3, 32, 128, 1, x, y) \ _( 4, 40, 102, 1, x, y) \ _( 5, 48, 85, 1, x, y) \ _( 6, 56, 73, 1, x, y) \ _( 7, 64, 64, 1, x, y) \ _( 8, 80, 51, 1, x, y) \ _( 9, 96, 42, 1, x, y) \ _(10, 112, 36, 1, x, y) \ _(11, 128, 32, 1, x, y) \ _(12, 160, 25, 1, x, y) \ _(13, 192, 21, 1, x, y) \ _(14, 224, 18, 1, x, y) \ _(15, 256, 16, 1, x, y) \ _(16, 320, 64, 5, x, y) \ _(17, 384, 32, 3, x, y) \ _(18, 448, 9, 1, x, y) \ _(19, 512, 8, 1, x, y) \ _(20, 640, 32, 5, x, y) \ _(21, 768, 16, 3, x, y) \ _(22, 896, 9, 2, x, y) \ _(23, 1024, 8, 2, x, y) \ _(24, 1280, 16, 5, x, y) \ _(25, 1536, 8, 3, x, y) \ _(26, 1792, 16, 7, x, y) \ _(27, 2048, 8, 4, x, y) \ _(28, 2560, 8, 5, x, y) \ _(29, 3072, 4, 3, x, y) #endif /* ZEND_ALLOC_SIZES_H */
2,629
39.461538
99
h
php-src
php-src-master/Zend/zend_arena.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef _ZEND_ARENA_H_ #define _ZEND_ARENA_H_ #include "zend.h" #ifndef ZEND_TRACK_ARENA_ALLOC typedef struct _zend_arena zend_arena; struct _zend_arena { char *ptr; char *end; zend_arena *prev; }; static zend_always_inline zend_arena* zend_arena_create(size_t size) { zend_arena *arena = (zend_arena*)emalloc(size); arena->ptr = (char*) arena + ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena)); arena->end = (char*) arena + size; arena->prev = NULL; return arena; } static zend_always_inline void zend_arena_destroy(zend_arena *arena) { do { zend_arena *prev = arena->prev; efree(arena); arena = prev; } while (arena); } static zend_always_inline void* zend_arena_alloc(zend_arena **arena_ptr, size_t size) { zend_arena *arena = *arena_ptr; char *ptr = arena->ptr; size = ZEND_MM_ALIGNED_SIZE(size); if (EXPECTED(size <= (size_t)(arena->end - ptr))) { arena->ptr = ptr + size; } else { size_t arena_size = UNEXPECTED((size + ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena))) > (size_t)(arena->end - (char*) arena)) ? (size + ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena))) : (size_t)(arena->end - (char*) arena); zend_arena *new_arena = (zend_arena*)emalloc(arena_size); ptr = (char*) new_arena + ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena)); new_arena->ptr = (char*) new_arena + ZEND_MM_ALIGNED_SIZE(sizeof(zend_arena)) + size; new_arena->end = (char*) new_arena + arena_size; new_arena->prev = arena; *arena_ptr = new_arena; } return (void*) ptr; } static zend_always_inline void* zend_arena_calloc(zend_arena **arena_ptr, size_t count, size_t unit_size) { bool overflow; size_t size; void *ret; size = zend_safe_address(unit_size, count, 0, &overflow); if (UNEXPECTED(overflow)) { zend_error(E_ERROR, "Possible integer overflow in zend_arena_calloc() (%zu * %zu)", unit_size, count); } ret = zend_arena_alloc(arena_ptr, size); memset(ret, 0, size); return ret; } static zend_always_inline void* zend_arena_checkpoint(zend_arena *arena) { return arena->ptr; } static zend_always_inline void zend_arena_release(zend_arena **arena_ptr, void *checkpoint) { zend_arena *arena = *arena_ptr; while (UNEXPECTED((char*)checkpoint > arena->end) || UNEXPECTED((char*)checkpoint <= (char*)arena)) { zend_arena *prev = arena->prev; efree(arena); *arena_ptr = arena = prev; } ZEND_ASSERT((char*)checkpoint > (char*)arena && (char*)checkpoint <= arena->end); arena->ptr = (char*)checkpoint; } static zend_always_inline bool zend_arena_contains(zend_arena *arena, void *ptr) { while (arena) { if ((char*)ptr > (char*)arena && (char*)ptr <= arena->ptr) { return 1; } arena = arena->prev; } return 0; } #else /* Use normal allocations and keep track of them for mass-freeing. * This is intended for use with asan/valgrind. */ typedef struct _zend_arena zend_arena; struct _zend_arena { void **ptr; void **end; struct _zend_arena *prev; void *ptrs[0]; }; #define ZEND_TRACKED_ARENA_SIZE 1000 static zend_always_inline zend_arena *zend_arena_create(size_t _size) { zend_arena *arena = (zend_arena*) emalloc( sizeof(zend_arena) + sizeof(void *) * ZEND_TRACKED_ARENA_SIZE); arena->ptr = &arena->ptrs[0]; arena->end = &arena->ptrs[ZEND_TRACKED_ARENA_SIZE]; arena->prev = NULL; return arena; } static zend_always_inline void zend_arena_destroy(zend_arena *arena) { do { zend_arena *prev = arena->prev; void **ptr; for (ptr = arena->ptrs; ptr < arena->ptr; ptr++) { efree(*ptr); } efree(arena); arena = prev; } while (arena); } static zend_always_inline void *zend_arena_alloc(zend_arena **arena_ptr, size_t size) { zend_arena *arena = *arena_ptr; if (arena->ptr == arena->end) { *arena_ptr = zend_arena_create(0); (*arena_ptr)->prev = arena; arena = *arena_ptr; } return *arena->ptr++ = emalloc(size); } static zend_always_inline void* zend_arena_calloc(zend_arena **arena_ptr, size_t count, size_t unit_size) { bool overflow; size_t size; void *ret; size = zend_safe_address(unit_size, count, 0, &overflow); if (UNEXPECTED(overflow)) { zend_error(E_ERROR, "Possible integer overflow in zend_arena_calloc() (%zu * %zu)", unit_size, count); } ret = zend_arena_alloc(arena_ptr, size); memset(ret, 0, size); return ret; } static zend_always_inline void* zend_arena_checkpoint(zend_arena *arena) { return arena->ptr; } static zend_always_inline void zend_arena_release(zend_arena **arena_ptr, void *checkpoint) { while (1) { zend_arena *arena = *arena_ptr; zend_arena *prev = arena->prev; while (1) { if (arena->ptr == (void **) checkpoint) { return; } if (arena->ptr == arena->ptrs) { break; } arena->ptr--; efree(*arena->ptr); } efree(arena); *arena_ptr = prev; ZEND_ASSERT(*arena_ptr); } } static zend_always_inline bool zend_arena_contains(zend_arena *arena, void *ptr) { /* TODO: Dummy */ return 1; } #endif #endif /* _ZEND_ARENA_H_ */
6,063
25.951111
105
h
php-src
php-src-master/Zend/zend_atomic.c
/* +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Levi Morrison <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend_atomic.h" /* This file contains the non-inline copy of atomic functions. This is useful * for extensions written in languages such as Rust. C and C++ compilers are * probably going to inline these functions, but in the case they don't, this * is also where the code will go. */ /* Defined for FFI users; everyone else use ZEND_ATOMIC_BOOL_INIT. * This is NOT ATOMIC as it is meant for initialization. */ ZEND_API void zend_atomic_bool_init(zend_atomic_bool *obj, bool desired) { ZEND_ATOMIC_BOOL_INIT(obj, desired); } ZEND_API bool zend_atomic_bool_exchange(zend_atomic_bool *obj, bool desired) { return zend_atomic_bool_exchange_ex(obj, desired); } ZEND_API void zend_atomic_bool_store(zend_atomic_bool *obj, bool desired) { zend_atomic_bool_store_ex(obj, desired); } #if defined(ZEND_WIN32) || defined(HAVE_SYNC_ATOMICS) /* On these platforms it is non-const due to underlying APIs. */ ZEND_API bool zend_atomic_bool_load(zend_atomic_bool *obj) { return zend_atomic_bool_load_ex(obj); } #else ZEND_API bool zend_atomic_bool_load(const zend_atomic_bool *obj) { return zend_atomic_bool_load_ex(obj); } #endif
1,984
40.354167
78
c
php-src
php-src-master/Zend/zend_atomic.h
/* +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Levi Morrison <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_ATOMIC_H #define ZEND_ATOMIC_H #include "zend_portability.h" #include <stdbool.h> #define ZEND_GCC_PREREQ(x, y) \ ((__GNUC__ == (x) && __GNUC_MINOR__ >= (y)) || (__GNUC__ > (x))) /* Builtins are used to avoid library linkage */ #if __has_feature(c_atomic) #define HAVE_C11_ATOMICS 1 #elif ZEND_GCC_PREREQ(4, 7) #define HAVE_GNUC_ATOMICS 1 #elif defined(__GNUC__) #define HAVE_SYNC_ATOMICS 1 #elif !defined(ZEND_WIN32) #define HAVE_NO_ATOMICS 1 #endif #undef ZEND_GCC_PREREQ /* Treat zend_atomic_* types as opaque. They have definitions only for size * and alignment purposes. */ #if defined(ZEND_WIN32) || defined(HAVE_SYNC_ATOMICS) typedef struct zend_atomic_bool_s { volatile char value; } zend_atomic_bool; #elif defined(HAVE_C11_ATOMICS) typedef struct zend_atomic_bool_s { _Atomic(bool) value; } zend_atomic_bool; #else typedef struct zend_atomic_bool_s { volatile bool value; } zend_atomic_bool; #endif BEGIN_EXTERN_C() #ifdef ZEND_WIN32 #ifndef InterlockedExchange8 #define InterlockedExchange8 _InterlockedExchange8 #endif #ifndef InterlockedOr8 #define InterlockedOr8 _InterlockedOr8 #endif #define ZEND_ATOMIC_BOOL_INIT(obj, desired) ((obj)->value = (desired)) static zend_always_inline bool zend_atomic_bool_exchange_ex(zend_atomic_bool *obj, bool desired) { return InterlockedExchange8(&obj->value, desired); } /* On this platform it is non-const due to Iterlocked API*/ static zend_always_inline bool zend_atomic_bool_load_ex(zend_atomic_bool *obj) { /* Or'ing with false won't change the value. */ return InterlockedOr8(&obj->value, false); } static zend_always_inline void zend_atomic_bool_store_ex(zend_atomic_bool *obj, bool desired) { (void)InterlockedExchange8(&obj->value, desired); } #elif defined(HAVE_C11_ATOMICS) #define ZEND_ATOMIC_BOOL_INIT(obj, desired) __c11_atomic_init(&(obj)->value, (desired)) static zend_always_inline bool zend_atomic_bool_exchange_ex(zend_atomic_bool *obj, bool desired) { return __c11_atomic_exchange(&obj->value, desired, __ATOMIC_SEQ_CST); } static zend_always_inline bool zend_atomic_bool_load_ex(const zend_atomic_bool *obj) { return __c11_atomic_load(&obj->value, __ATOMIC_SEQ_CST); } static zend_always_inline void zend_atomic_bool_store_ex(zend_atomic_bool *obj, bool desired) { __c11_atomic_store(&obj->value, desired, __ATOMIC_SEQ_CST); } #elif defined(HAVE_GNUC_ATOMICS) #define ZEND_ATOMIC_BOOL_INIT(obj, desired) ((obj)->value = (desired)) static zend_always_inline bool zend_atomic_bool_exchange_ex(zend_atomic_bool *obj, bool desired) { bool prev = false; __atomic_exchange(&obj->value, &desired, &prev, __ATOMIC_SEQ_CST); return prev; } static zend_always_inline bool zend_atomic_bool_load_ex(const zend_atomic_bool *obj) { bool prev = false; __atomic_load(&obj->value, &prev, __ATOMIC_SEQ_CST); return prev; } static zend_always_inline void zend_atomic_bool_store_ex(zend_atomic_bool *obj, bool desired) { __atomic_store(&obj->value, &desired, __ATOMIC_SEQ_CST); } #elif defined(HAVE_SYNC_ATOMICS) #define ZEND_ATOMIC_BOOL_INIT(obj, desired) ((obj)->value = (desired)) static zend_always_inline bool zend_atomic_bool_exchange_ex(zend_atomic_bool *obj, bool desired) { bool prev = __sync_lock_test_and_set(&obj->value, desired); /* __sync_lock_test_and_set only does an acquire barrier, so sync * immediately after. */ __sync_synchronize(); return prev; } static zend_always_inline bool zend_atomic_bool_load_ex(zend_atomic_bool *obj) { /* Or'ing false won't change the value */ return __sync_fetch_and_or(&obj->value, false); } static zend_always_inline void zend_atomic_bool_store_ex(zend_atomic_bool *obj, bool desired) { __sync_synchronize(); obj->value = desired; __sync_synchronize(); } #elif defined(HAVE_NO_ATOMICS) #warning No atomics support detected. Please open an issue with platform details. #define ZEND_ATOMIC_BOOL_INIT(obj, desired) ((obj)->value = (desired)) static zend_always_inline void zend_atomic_bool_store_ex(zend_atomic_bool *obj, bool desired) { obj->value = desired; } static zend_always_inline bool zend_atomic_bool_load_ex(const zend_atomic_bool *obj) { return obj->value; } static zend_always_inline bool zend_atomic_bool_exchange_ex(zend_atomic_bool *obj, bool desired) { bool prev = obj->value; obj->value = desired; return prev; } #endif ZEND_API void zend_atomic_bool_init(zend_atomic_bool *obj, bool desired); ZEND_API bool zend_atomic_bool_exchange(zend_atomic_bool *obj, bool desired); ZEND_API void zend_atomic_bool_store(zend_atomic_bool *obj, bool desired); #if defined(ZEND_WIN32) || defined(HAVE_SYNC_ATOMICS) /* On these platforms it is non-const due to underlying APIs. */ ZEND_API bool zend_atomic_bool_load(zend_atomic_bool *obj); #else ZEND_API bool zend_atomic_bool_load(const zend_atomic_bool *obj); #endif END_EXTERN_C() #endif
5,682
30.572222
98
h
php-src
php-src-master/Zend/zend_build.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Stanislav Malyshev <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_BUILD_H #define ZEND_BUILD_H #define ZEND_TOSTR_(x) #x #define ZEND_TOSTR(x) ZEND_TOSTR_(x) #ifdef ZTS #define ZEND_BUILD_TS ",TS" #else #define ZEND_BUILD_TS ",NTS" #endif #if ZEND_DEBUG #define ZEND_BUILD_DEBUG ",debug" #else #define ZEND_BUILD_DEBUG #endif #if defined(ZEND_WIN32) && defined(PHP_COMPILER_ID) #define ZEND_BUILD_SYSTEM "," PHP_COMPILER_ID #else #define ZEND_BUILD_SYSTEM #endif /* for private applications */ #define ZEND_BUILD_EXTRA #endif
1,626
33.617021
75
h
php-src
php-src-master/Zend/zend_builtin_functions.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_BUILTIN_FUNCTIONS_H #define ZEND_BUILTIN_FUNCTIONS_H zend_result zend_startup_builtin_functions(void); BEGIN_EXTERN_C() ZEND_API void zend_fetch_debug_backtrace(zval *return_value, int skip_last, int options, int limit); END_EXTERN_C() #endif /* ZEND_BUILTIN_FUNCTIONS_H */
1,513
49.466667
100
h
php-src
php-src-master/Zend/zend_call_stack.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Arnaud Le Blanc <[email protected]> | +----------------------------------------------------------------------+ */ /* Inspired from Chromium's stack_util.cc */ #include "zend.h" #include "zend_globals.h" #include "zend_portability.h" #include "zend_call_stack.h" #include <stdint.h> #ifdef ZEND_WIN32 # include <processthreadsapi.h> # include <memoryapi.h> #else /* ZEND_WIN32 */ # include <sys/resource.h> # ifdef HAVE_UNISTD_H # include <unistd.h> # endif # ifdef HAVE_SYS_TYPES_H # include <sys/types.h> # endif #endif /* ZEND_WIN32 */ #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) # include <pthread.h> #endif #ifdef __FreeBSD__ # include <pthread_np.h> # include <sys/mman.h> # include <sys/sysctl.h> # include <sys/user.h> #endif #ifdef __OpenBSD__ typedef int boolean_t; # include <tib.h> # include <pthread_np.h> # include <sys/sysctl.h> # include <sys/user.h> #endif #ifdef __linux__ #include <sys/syscall.h> #endif #ifdef ZEND_CHECK_STACK_LIMIT /* Called once per process or thread */ ZEND_API void zend_call_stack_init(void) { if (!zend_call_stack_get(&EG(call_stack))) { EG(call_stack) = (zend_call_stack){0}; } switch (EG(max_allowed_stack_size)) { case ZEND_MAX_ALLOWED_STACK_SIZE_DETECT: { void *base = EG(call_stack).base; size_t size = EG(call_stack).max_size; if (UNEXPECTED(base == (void*)0)) { base = zend_call_stack_position(); size = zend_call_stack_default_size(); /* base is not the actual stack base */ size -= 32 * 1024; } EG(stack_base) = base; EG(stack_limit) = zend_call_stack_limit(base, size, EG(reserved_stack_size)); break; } case ZEND_MAX_ALLOWED_STACK_SIZE_UNCHECKED: { EG(stack_base) = (void*)0; EG(stack_limit) = (void*)0; break; } default: { ZEND_ASSERT(EG(max_allowed_stack_size) > 0); void *base = EG(call_stack).base; if (UNEXPECTED(base == (void*)0)) { base = zend_call_stack_position(); } EG(stack_base) = base; EG(stack_limit) = zend_call_stack_limit(base, EG(max_allowed_stack_size), EG(reserved_stack_size)); break; } } } #ifdef __linux__ static bool zend_call_stack_is_main_thread(void) { # ifdef HAVE_GETTID return getpid() == gettid(); # else return getpid() == syscall(SYS_gettid); # endif } # ifdef HAVE_PTHREAD_GETATTR_NP static bool zend_call_stack_get_linux_pthread(zend_call_stack *stack) { pthread_attr_t attr; int error; void *addr; size_t max_size; /* pthread_getattr_np() will return bogus values for the main thread with * musl or with some old glibc versions */ ZEND_ASSERT(!zend_call_stack_is_main_thread()); error = pthread_getattr_np(pthread_self(), &attr); if (error) { return false; } error = pthread_attr_getstack(&attr, &addr, &max_size); if (error) { return false; } # if defined(__GLIBC__) && (__GLIBC__ < 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ < 8)) { size_t guard_size; /* In glibc prior to 2.8, addr and size include the guard pages */ error = pthread_attr_getguardsize(&attr, &guard_size); if (error) { return false; } addr = (int8_t*)addr + guard_size; max_size -= guard_size; } # endif /* glibc < 2.8 */ stack->base = (int8_t*)addr + max_size; stack->max_size = max_size; return true; } # else /* HAVE_PTHREAD_GETATTR_NP */ static bool zend_call_stack_get_linux_pthread(zend_call_stack *stack) { return false; } # endif /* HAVE_PTHREAD_GETATTR_NP */ static bool zend_call_stack_get_linux_proc_maps(zend_call_stack *stack) { FILE *f; char buffer[4096]; uintptr_t addr_on_stack = (uintptr_t)&buffer; uintptr_t start, end, prev_end = 0; size_t max_size; bool found = false; struct rlimit rlim; int error; /* This method is relevant only for the main thread */ ZEND_ASSERT(zend_call_stack_is_main_thread()); /* Scan the process memory mappings to find the one containing the stack. * * The end of the stack mapping is the base of the stack. The start is * adjusted by the kernel as the stack grows. The maximum stack size is * determined by RLIMIT_STACK and the previous mapping. * * * ^ Higher addresses ^ * : : * : : * Mapping end --> |-------------------| <-- Stack base (stack start) * | | ^ * | Stack Mapping | | Stack size * | | v * Mapping start --> |-------------------| <-- Current stack end * (adjusted : : * downwards as the . . * stack grows) : : * |-------------------| * | Some Mapping | The previous mapping may prevent * |-------------------| stack growth * : : * : : * v Lower addresses v */ f = fopen("/proc/self/maps", "r"); if (!f) { return false; } while (fgets(buffer, sizeof(buffer), f) && sscanf(buffer, "%" SCNxPTR "-%" SCNxPTR, &start, &end) == 2) { if (start <= addr_on_stack && end >= addr_on_stack) { found = true; break; } prev_end = end; } fclose(f); if (!found) { return false; } error = getrlimit(RLIMIT_STACK, &rlim); if (error || rlim.rlim_cur == RLIM_INFINITY) { return false; } max_size = rlim.rlim_cur; /* Previous mapping may prevent the stack from growing */ if (end - max_size < prev_end) { max_size = prev_end - end; } stack->base = (void*)end; stack->max_size = max_size; return true; } static bool zend_call_stack_get_linux(zend_call_stack *stack) { if (zend_call_stack_is_main_thread()) { return zend_call_stack_get_linux_proc_maps(stack); } return zend_call_stack_get_linux_pthread(stack); } #else /* __linux__ */ static bool zend_call_stack_get_linux(zend_call_stack *stack) { return false; } #endif /* __linux__ */ #ifdef __FreeBSD__ static bool zend_call_stack_is_main_thread(void) { int is_main = pthread_main_np(); return is_main == -1 || is_main == 1; } # if defined(HAVE_PTHREAD_ATTR_GET_NP) && defined(HAVE_PTHREAD_ATTR_GET_STACK) static bool zend_call_stack_get_freebsd_pthread(zend_call_stack *stack) { pthread_attr_t attr; int error; void *addr; size_t max_size; size_t guard_size; /* pthread will return bogus values for the main thread */ ZEND_ASSERT(!zend_call_stack_is_main_thread()); pthread_attr_init(&attr); error = pthread_attr_get_np(pthread_self(), &attr); if (error) { goto fail; } error = pthread_attr_getstack(&attr, &addr, &max_size); if (error) { goto fail; } stack->base = (int8_t*)addr + max_size; stack->max_size = max_size; pthread_attr_destroy(&attr); return true; fail: pthread_attr_destroy(&attr); return false; } # else /* defined(HAVE_PTHREAD_ATTR_GET_NP) && defined(HAVE_PTHREAD_ATTR_GET_STACK) */ static bool zend_call_stack_get_freebsd_pthread(zend_call_stack *stack) { return false; } # endif /* defined(HAVE_PTHREAD_ATTR_GET_NP) && defined(HAVE_PTHREAD_ATTR_GET_STACK) */ static bool zend_call_stack_get_freebsd_sysctl(zend_call_stack *stack) { void *stack_base; int mib[2] = {CTL_KERN, KERN_USRSTACK}; size_t len = sizeof(stack_base); struct rlimit rlim; /* This method is relevant only for the main thread */ ZEND_ASSERT(zend_call_stack_is_main_thread()); if (sysctl(mib, sizeof(mib)/sizeof(*mib), &stack_base, &len, NULL, 0) != 0) { return false; } if (getrlimit(RLIMIT_STACK, &rlim) != 0) { return false; } if (rlim.rlim_cur == RLIM_INFINITY) { return false; } size_t guard_size = getpagesize(); stack->base = stack_base; stack->max_size = rlim.rlim_cur - guard_size; return true; } static bool zend_call_stack_get_freebsd(zend_call_stack *stack) { if (zend_call_stack_is_main_thread()) { return zend_call_stack_get_freebsd_sysctl(stack); } return zend_call_stack_get_freebsd_pthread(stack); } #else static bool zend_call_stack_get_freebsd(zend_call_stack *stack) { return false; } #endif /* __FreeBSD__ */ #ifdef ZEND_WIN32 static bool zend_call_stack_get_win32(zend_call_stack *stack) { ULONG_PTR low_limit, high_limit; ULONG size; MEMORY_BASIC_INFORMATION guard_region = {0}, uncommitted_region = {0}; size_t result_size, page_size; /* The stack consists of three regions: committed, guard, and uncommitted. * Memory is committed when the guard region is accessed. If only one page * is left in the uncommitted region, a stack overflow error is raised * instead. * * The total useable stack size is the size of the committed and uncommitted * regions less one page. * * http://blogs.msdn.com/b/satyem/archive/2012/08/13/thread-s-stack-memory-management.aspx * https://learn.microsoft.com/en-us/windows/win32/procthread/thread-stack-size * * ^ Higher addresses ^ * : : * : : * high_limit --> |--------------------| * ^ | | * | | Committed region | * | | | * | |------------------- | <-- guard_region.BaseAddress * reserved | | | + guard_region.RegionSize * size | | Guard region | * | | | * | |--------------------| <-- guard_region.BaseAddress, * | | | uncommitted_region.BaseAddress * | | Uncommitted region | + uncommitted_region.RegionSize * v | | * low_limit --> |------------------- | <-- uncommitted_region.BaseAddress * : : * : : * v Lower addresses v */ GetCurrentThreadStackLimits(&low_limit, &high_limit); result_size = VirtualQuery((void*)low_limit, &uncommitted_region, sizeof(uncommitted_region)); ZEND_ASSERT(result_size >= sizeof(uncommitted_region)); result_size = VirtualQuery((int8_t*)uncommitted_region.BaseAddress + uncommitted_region.RegionSize, &guard_region, sizeof(guard_region)); ZEND_ASSERT(result_size >= sizeof(uncommitted_region)); stack->base = (void*)high_limit; stack->max_size = (uintptr_t)high_limit - (uintptr_t)low_limit; ZEND_ASSERT(stack->max_size > guard_region.RegionSize); stack->max_size -= guard_region.RegionSize; /* The uncommitted region does not shrink below 1 page */ page_size = zend_get_page_size(); ZEND_ASSERT(stack->max_size > page_size); stack->max_size -= page_size; return true; } #else /* ZEND_WIN32 */ static bool zend_call_stack_get_win32(zend_call_stack *stack) { return false; } #endif /* ZEND_WIN32 */ #if defined(__APPLE__) && defined(HAVE_PTHREAD_GET_STACKADDR_NP) static bool zend_call_stack_get_macos(zend_call_stack *stack) { void *base = pthread_get_stackaddr_np(pthread_self()); size_t max_size; if (pthread_main_np()) { /* pthread_get_stacksize_np() returns a too low value for the main * thread in OSX 10.9, 10.10: * https://mail.openjdk.org/pipermail/hotspot-dev/2013-October/011353.html * https://github.com/rust-lang/rust/issues/43347 */ /* Stack size is 8MiB by default for main threads * https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html */ max_size = 8 * 1024 * 1024; } else { max_size = pthread_get_stacksize_np(pthread_self()); } stack->base = base; stack->max_size = max_size; return true; } #else /* defined(__APPLE__) && defined(HAVE_PTHREAD_GET_STACKADDR_NP) */ static bool zend_call_stack_get_macos(zend_call_stack *stack) { return false; } #endif /* defined(__APPLE__) && defined(HAVE_PTHREAD_GET_STACKADDR_NP) */ #if defined(__OpenBSD__) #if defined(HAVE_PTHREAD_STACKSEG_NP) static bool zend_call_stack_get_openbsd_pthread(zend_call_stack *stack) { stack_t ss; if (pthread_stackseg_np(pthread_self(), &ss) != 0) { return false; } stack->base = (char *)ss.ss_sp - ss.ss_size; stack->max_size = ss.ss_size - sysconf(_SC_PAGE_SIZE); return true; } #else static bool zend_call_stack_get_openbsd_pthread(zend_call_stack *stack) { return false; } #endif /* defined(HAVE_PTHREAD_STACKSEG_NP) */ static bool zend_call_stack_get_openbsd_vm(zend_call_stack *stack) { struct _ps_strings ps; struct rlimit rlim; int mib[2] = {CTL_VM, VM_PSSTRINGS }; size_t len = sizeof(ps), pagesize; if (sysctl(mib, 2, &ps, &len, NULL, 0) != 0) { return false; } if (getrlimit(RLIMIT_STACK, &rlim) != 0) { return false; } if (rlim.rlim_cur == RLIM_INFINITY) { return false; } pagesize = sysconf(_SC_PAGE_SIZE); stack->base = (void *)((uintptr_t)ps.val + (pagesize - 1) & ~(pagesize - 1)); stack->max_size = rlim.rlim_cur - pagesize; return true; } static bool zend_call_stack_get_openbsd(zend_call_stack *stack) { // TIB_THREAD_INITIAL_STACK is private and here we avoid using pthread's api (ie pthread_main_np) if (!TIB_GET()->tib_thread || (TIB_GET()->tib_thread_flags & 0x002) != 0) { return zend_call_stack_get_openbsd_vm(stack); } return zend_call_stack_get_openbsd_pthread(stack); } #else static bool zend_call_stack_get_openbsd(zend_call_stack *stack) { return false; } #endif /* defined(__OpenBSD__) */ /** Get the stack information for the calling thread */ ZEND_API bool zend_call_stack_get(zend_call_stack *stack) { if (zend_call_stack_get_linux(stack)) { return true; } if (zend_call_stack_get_freebsd(stack)) { return true; } if (zend_call_stack_get_win32(stack)) { return true; } if (zend_call_stack_get_macos(stack)) { return true; } if (zend_call_stack_get_openbsd(stack)) { return true; } return false; } #endif /* ZEND_CHECK_STACK_LIMIT */
14,837
26.734579
134
c
php-src
php-src-master/Zend/zend_call_stack.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Arnaud Le Blanc <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_CALL_STACK_H #define ZEND_CALL_STACK_H #include "zend.h" #include "zend_portability.h" #ifdef __APPLE__ # include <pthread.h> #endif #ifdef ZEND_CHECK_STACK_LIMIT typedef struct _zend_call_stack { void *base; size_t max_size; } zend_call_stack; ZEND_API void zend_call_stack_init(void); ZEND_API bool zend_call_stack_get(zend_call_stack *stack); /** Returns an approximation of the current stack position */ static zend_always_inline void *zend_call_stack_position(void) { #ifdef ZEND_WIN32 return _AddressOfReturnAddress(); #elif PHP_HAVE_BUILTIN_FRAME_ADDRESS return __builtin_frame_address(0); #else void *a; void *pos = (void*)&a; return pos; #endif } static zend_always_inline bool zend_call_stack_overflowed(void *stack_limit) { return (uintptr_t) zend_call_stack_position() <= (uintptr_t) stack_limit; } static inline void* zend_call_stack_limit(void *base, size_t size, size_t reserved_size) { if (UNEXPECTED(size > (uintptr_t)base)) { return (void*)0; } base = (int8_t*)base - size; if (UNEXPECTED(UINTPTR_MAX - (uintptr_t)base < reserved_size)) { return (void*)UINTPTR_MAX; } return (int8_t*)base + reserved_size; } static inline size_t zend_call_stack_default_size(void) { #ifdef __linux__ return 8 * 1024 * 1024; #endif #ifdef __FreeBSD__ return 8 * 1024 * 1024; #endif #ifdef __APPLE__ // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html if (pthread_main_np()) { return 8 * 1024 * 1024; } return 512 * 1024; #endif return 2 * 1024 * 1024; } #endif /* ZEND_CHECK_STACK_LIMIT */ #endif /* ZEND_CALL_STACK_H */
2,800
29.445652
130
h
php-src
php-src-master/Zend/zend_closures_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: e3b480674671a698814db282c5ea34d438fe519d */ ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Closure___construct, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_Closure_bind, 0, 2, Closure, 1) ZEND_ARG_OBJ_INFO(0, closure, Closure, 0) ZEND_ARG_TYPE_INFO(0, newThis, IS_OBJECT, 1) ZEND_ARG_TYPE_MASK(0, newScope, MAY_BE_OBJECT|MAY_BE_STRING|MAY_BE_NULL, "\"static\"") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_Closure_bindTo, 0, 1, Closure, 1) ZEND_ARG_TYPE_INFO(0, newThis, IS_OBJECT, 1) ZEND_ARG_TYPE_MASK(0, newScope, MAY_BE_OBJECT|MAY_BE_STRING|MAY_BE_NULL, "\"static\"") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Closure_call, 0, 1, IS_MIXED, 0) ZEND_ARG_TYPE_INFO(0, newThis, IS_OBJECT, 0) ZEND_ARG_VARIADIC_TYPE_INFO(0, args, IS_MIXED, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_Closure_fromCallable, 0, 1, Closure, 0) ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0) ZEND_END_ARG_INFO() ZEND_METHOD(Closure, __construct); ZEND_METHOD(Closure, bind); ZEND_METHOD(Closure, bindTo); ZEND_METHOD(Closure, call); ZEND_METHOD(Closure, fromCallable); static const zend_function_entry class_Closure_methods[] = { ZEND_ME(Closure, __construct, arginfo_class_Closure___construct, ZEND_ACC_PRIVATE) ZEND_ME(Closure, bind, arginfo_class_Closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_ME(Closure, bindTo, arginfo_class_Closure_bindTo, ZEND_ACC_PUBLIC) ZEND_ME(Closure, call, arginfo_class_Closure_call, ZEND_ACC_PUBLIC) ZEND_ME(Closure, fromCallable, arginfo_class_Closure_fromCallable, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_FE_END }; static zend_class_entry *register_class_Closure(void) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "Closure", class_Closure_methods); class_entry = zend_register_internal_class_ex(&ce, NULL); class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NO_DYNAMIC_PROPERTIES|ZEND_ACC_NOT_SERIALIZABLE; return class_entry; }
2,084
37.611111
100
h
php-src
php-src-master/Zend/zend_config.w32.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_CONFIG_W32_H #define ZEND_CONFIG_W32_H #include <../main/config.w32.h> #define _CRTDBG_MAP_ALLOC #include <malloc.h> #include <stdlib.h> #include <crtdbg.h> #include <string.h> #ifndef ZEND_INCLUDE_FULL_WINDOWS_HEADERS #define WIN32_LEAN_AND_MEAN #endif #include <winsock2.h> #include <windows.h> #include <float.h> #define HAVE_STDIOSTR_H 1 #define HAVE_CLASS_ISTDIOSTREAM #define istdiostream stdiostream #if _MSC_VER < 1900 #define snprintf _snprintf #endif #define strcasecmp(s1, s2) _stricmp(s1, s2) #define strncasecmp(s1, s2, n) _strnicmp(s1, s2, n) #ifdef LIBZEND_EXPORTS # define ZEND_API __declspec(dllexport) #else # define ZEND_API __declspec(dllimport) #endif #define ZEND_DLEXPORT __declspec(dllexport) #define ZEND_DLIMPORT __declspec(dllimport) #endif /* ZEND_CONFIG_W32_H */
2,041
32.47541
75
h
php-src
php-src-master/Zend/zend_constants_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: df76f4e5a735baba96c4ac3538e9e3e48d934f0f */ static void register_zend_constants_symbols(int module_number) { REGISTER_LONG_CONSTANT("E_ERROR", E_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_WARNING", E_WARNING, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_PARSE", E_PARSE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_NOTICE", E_NOTICE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_CORE_ERROR", E_CORE_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_CORE_WARNING", E_CORE_WARNING, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_COMPILE_ERROR", E_COMPILE_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_COMPILE_WARNING", E_COMPILE_WARNING, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_USER_ERROR", E_USER_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_USER_WARNING", E_USER_WARNING, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_USER_NOTICE", E_USER_NOTICE, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_STRICT", E_STRICT, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_RECOVERABLE_ERROR", E_RECOVERABLE_ERROR, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_DEPRECATED", E_DEPRECATED, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_USER_DEPRECATED", E_USER_DEPRECATED, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("E_ALL", E_ALL, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DEBUG_BACKTRACE_PROVIDE_OBJECT", DEBUG_BACKTRACE_PROVIDE_OBJECT, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("DEBUG_BACKTRACE_IGNORE_ARGS", DEBUG_BACKTRACE_IGNORE_ARGS, CONST_PERSISTENT); REGISTER_BOOL_CONSTANT("ZEND_THREAD_SAFE", ZTS_V, CONST_PERSISTENT); REGISTER_BOOL_CONSTANT("ZEND_DEBUG_BUILD", ZEND_DEBUG, CONST_PERSISTENT); REGISTER_BOOL_CONSTANT("TRUE", true, CONST_PERSISTENT); REGISTER_BOOL_CONSTANT("FALSE", false, CONST_PERSISTENT); REGISTER_NULL_CONSTANT("NULL", CONST_PERSISTENT); }
1,876
57.65625
108
h
php-src
php-src-master/Zend/zend_cpuinfo.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend_cpuinfo.h" typedef struct _zend_cpu_info { uint32_t eax; uint32_t ebx; uint32_t ecx; uint32_t edx; uint32_t initialized; } zend_cpu_info; static zend_cpu_info cpuinfo = {0}; #if (defined(__GNUC__) || defined(__clang__)) && (defined(__i386__) || defined(__x86_64__)) # if defined(HAVE_CPUID_H) && defined(HAVE_CPUID_COUNT) /* use cpuid.h functions */ # include <cpuid.h> static void __zend_cpuid(uint32_t func, uint32_t subfunc, zend_cpu_info *cpuinfo) { __cpuid_count(func, subfunc, cpuinfo->eax, cpuinfo->ebx, cpuinfo->ecx, cpuinfo->edx); } # else /* use inline asm */ static void __zend_cpuid(uint32_t func, uint32_t subfunc, zend_cpu_info *cpuinfo) { # if defined(__i386__) && (defined(__pic__) || defined(__PIC__)) /* PIC on i386 uses %ebx, so preserve it. */ __asm__ __volatile__ ( "pushl %%ebx\n" "cpuid\n" "mov %%ebx,%1\n" "popl %%ebx" : "=a"(cpuinfo->eax), "=r"(cpuinfo->ebx), "=c"(cpuinfo->ecx), "=d"(cpuinfo->edx) : "a"(func), "c"(subfunc) ); # else __asm__ __volatile__ ( "cpuid" : "=a"(cpuinfo->eax), "=b"(cpuinfo->ebx), "=c"(cpuinfo->ecx), "=d"(cpuinfo->edx) : "a"(func), "c"(subfunc) ); # endif } # endif #elif defined(_MSC_VER) && !defined(__clang__) && (defined(_M_X64) || defined(_M_IX86)) /* use MSVC __cpuidex intrin */ # include <intrin.h> static void __zend_cpuid(uint32_t func, uint32_t subfunc, zend_cpu_info *cpuinfo) { int regs[4]; __cpuidex(regs, func, subfunc); cpuinfo->eax = regs[0]; cpuinfo->ebx = regs[1]; cpuinfo->ecx = regs[2]; cpuinfo->edx = regs[3]; } #else /* fall back to zero */ static void __zend_cpuid(uint32_t func, uint32_t subfunc, zend_cpu_info *cpuinfo) { cpuinfo->eax = 0; } #endif #if defined(__i386__) || defined(__x86_64__) /* Function based on compiler-rt implementation. */ static unsigned get_xcr0_eax(void) { # if defined(__GNUC__) || defined(__clang__) // Check xgetbv; this uses a .byte sequence instead of the instruction // directly because older assemblers do not include support for xgetbv and // there is no easy way to conditionally compile based on the assembler used. unsigned eax, edx; __asm__(".byte 0x0f, 0x01, 0xd0" : "=a"(eax), "=d"(edx) : "c"(0)); return eax; # elif defined(ZEND_WIN32) && defined(_XCR_XFEATURE_ENABLED_MASK) return _xgetbv(_XCR_XFEATURE_ENABLED_MASK); # else return 0; # endif } static bool is_avx_supported(void) { if (!(cpuinfo.ecx & ZEND_CPU_FEATURE_AVX)) { /* No support for AVX */ return 0; } if (!(cpuinfo.ecx & ZEND_CPU_FEATURE_OSXSAVE)) { /* The operating system does not support XSAVE. */ return 0; } if ((get_xcr0_eax() & 0x6) != 0x6) { /* XCR0 SSE and AVX bits must be set. */ return 0; } return 1; } #else static bool is_avx_supported(void) { return 0; } #endif void zend_cpu_startup(void) { if (!cpuinfo.initialized) { zend_cpu_info ebx; int max_feature; cpuinfo.initialized = 1; __zend_cpuid(0, 0, &cpuinfo); max_feature = cpuinfo.eax; if (max_feature == 0) { return; } __zend_cpuid(1, 0, &cpuinfo); /* for avx2 */ if (max_feature >= 7) { __zend_cpuid(7, 0, &ebx); cpuinfo.ebx = ebx.ebx; } else { cpuinfo.ebx = 0; } if (!is_avx_supported()) { cpuinfo.edx &= ~ZEND_CPU_FEATURE_AVX; cpuinfo.ebx &= ~(ZEND_CPU_FEATURE_AVX2 & ~ZEND_CPU_EBX_MASK); } } } ZEND_API int zend_cpu_supports(zend_cpu_feature feature) { ZEND_ASSERT(cpuinfo.initialized); if (feature & ZEND_CPU_EDX_MASK) { return (cpuinfo.edx & (feature & ~ZEND_CPU_EDX_MASK)); } else if (feature & ZEND_CPU_EBX_MASK) { return (cpuinfo.ebx & (feature & ~ZEND_CPU_EBX_MASK)); } else { return (cpuinfo.ecx & feature); } }
4,783
30.064935
119
c
php-src
php-src-master/Zend/zend_cpuinfo.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_CPU_INFO_H #define ZEND_CPU_INFO_H #include "zend.h" #define ZEND_CPU_EBX_MASK (1<<30) #define ZEND_CPU_EDX_MASK (1U<<31) typedef enum _zend_cpu_feature { /* ECX */ ZEND_CPU_FEATURE_SSE3 = (1<<0), ZEND_CPU_FEATURE_PCLMULQDQ = (1<<1), ZEND_CPU_FEATURE_DTES64 = (1<<2), ZEND_CPU_FEATURE_MONITOR = (1<<3), ZEND_CPU_FEATURE_DSCPL = (1<<4), ZEND_CPU_FEATURE_VMX = (1<<5), ZEND_CPU_FEATURE_SMX = (1<<6), ZEND_CPU_FEATURE_EST = (1<<7), ZEND_CPU_FEATURE_TM2 = (1<<8), ZEND_CPU_FEATURE_SSSE3 = (1<<9), ZEND_CPU_FEATURE_CID = (1<<10), ZEND_CPU_FEATURE_SDBG = (1<<11), ZEND_CPU_FEATURE_FMA = (1<<12), ZEND_CPU_FEATURE_CX16 = (1<<13), ZEND_CPU_FEATURE_XTPR = (1<<14), ZEND_CPU_FEATURE_PDCM = (1<<15), /* reserved = (1<<16),*/ ZEND_CPU_FEATURE_PCID = (1<<17), ZEND_CPU_FEATURE_DCA = (1<<18), ZEND_CPU_FEATURE_SSE41 = (1<<19), ZEND_CPU_FEATURE_SSE42 = (1<<20), ZEND_CPU_FEATURE_X2APIC = (1<<21), ZEND_CPU_FEATURE_MOVBE = (1<<22), ZEND_CPU_FEATURE_POPCNT = (1<<23), ZEND_CPU_FEATURE_TSC_DEADLINE = (1<<24), ZEND_CPU_FEATURE_AES = (1<<25), ZEND_CPU_FEATURE_XSAVE = (1<<26), ZEND_CPU_FEATURE_OSXSAVE = (1<<27) , ZEND_CPU_FEATURE_AVX = (1<<28), ZEND_CPU_FEATURE_F16C = (1<<29), /* intentionally don't support = (1<<30) */ /* intentionally don't support = (1<<31) */ /* EBX */ ZEND_CPU_FEATURE_AVX2 = (1<<5 | ZEND_CPU_EBX_MASK), ZEND_CPU_FEATURE_AVX512F = (1<<16 | ZEND_CPU_EBX_MASK), ZEND_CPU_FEATURE_AVX512DQ = (1<<17 | ZEND_CPU_EBX_MASK), ZEND_CPU_FEATURE_AVX512CD = (1<<28 | ZEND_CPU_EBX_MASK), /* intentionally don't support = (1<<30 | ZEND_CPU_EBX_MASK) */ /* intentionally don't support = (1<<31 | ZEND_CPU_EBX_MASK) */ /* EDX */ ZEND_CPU_FEATURE_FPU = (1<<0 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_VME = (1<<1 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_DE = (1<<2 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PSE = (1<<3 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_TSC = (1<<4 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_MSR = (1<<5 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PAE = (1<<6 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_MCE = (1<<7 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_CX8 = (1<<8 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_APIC = (1<<9 | ZEND_CPU_EDX_MASK), /* reserved = (1<<10 | ZEND_CPU_EDX_MASK),*/ ZEND_CPU_FEATURE_SEP = (1<<11 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_MTRR = (1<<12 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PGE = (1<<13 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_MCA = (1<<14 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_CMOV = (1<<15 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PAT = (1<<16 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PSE36 = (1<<17 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_PN = (1<<18 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_CLFLUSH = (1<<19 | ZEND_CPU_EDX_MASK), /* reserved = (1<<20 | ZEND_CPU_EDX_MASK),*/ ZEND_CPU_FEATURE_DS = (1<<21 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_ACPI = (1<<22 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_MMX = (1<<23 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_FXSR = (1<<24 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_SSE = (1<<25 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_SSE2 = (1<<26 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_SS = (1<<27 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_HT = (1<<28 | ZEND_CPU_EDX_MASK), ZEND_CPU_FEATURE_TM = (1<<29 | ZEND_CPU_EDX_MASK) /*intentionally don't support = (1<<30 | ZEND_CPU_EDX_MASK)*/ /*intentionally don't support = (1<<31 | ZEND_CPU_EDX_MASK)*/ } zend_cpu_feature; void zend_cpu_startup(void); ZEND_API int zend_cpu_supports(zend_cpu_feature feature); #ifndef __has_attribute # define __has_attribute(x) 0 #endif /* Address sanitizer is incompatible with ifunc resolvers, so exclude the * CPU support helpers from asan. * See also https://github.com/google/sanitizers/issues/342. */ #if __has_attribute(no_sanitize_address) # define ZEND_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address)) #else # define ZEND_NO_SANITIZE_ADDRESS #endif #if PHP_HAVE_BUILTIN_CPU_SUPPORTS /* NOTE: you should use following inline function in * resolver functions (ifunc), as it could be called * before all PLT symbols are resolved. in other words, * resolver functions should not depend on any external * functions */ ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_sse2(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("sse2"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_sse3(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("sse3"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_ssse3(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("ssse3"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_sse41(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("sse4.1"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_sse42(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("sse4.2"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_avx(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("avx"); } ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_avx2(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("avx2"); } #if PHP_HAVE_AVX512_SUPPORTS ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_avx512(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512dq") && __builtin_cpu_supports("avx512cd") && __builtin_cpu_supports("avx512bw") && __builtin_cpu_supports("avx512vl"); } #endif #if PHP_HAVE_AVX512_VBMI_SUPPORTS ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_avx512_vbmi(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return zend_cpu_supports_avx512() && __builtin_cpu_supports("avx512vbmi"); } #endif #else static inline int zend_cpu_supports_sse2(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_SSE2); } static inline int zend_cpu_supports_sse3(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_SSE3); } static inline int zend_cpu_supports_ssse3(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_SSSE3); } static inline int zend_cpu_supports_sse41(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_SSE41); } static inline int zend_cpu_supports_sse42(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_SSE42); } static inline int zend_cpu_supports_avx(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_AVX); } static inline int zend_cpu_supports_avx2(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_AVX2); } static inline int zend_cpu_supports_avx512(void) { /* TODO: avx512_bw/avx512_vl use bit 30/31 which are reserved for mask */ return 0; } static zend_always_inline int zend_cpu_supports_avx512_vbmi(void) { /* TODO: avx512_vbmi use ECX of cpuid 7 */ return 0; } #endif /* __builtin_cpu_supports has pclmul from gcc9 */ #if PHP_HAVE_BUILTIN_CPU_SUPPORTS && (!defined(__GNUC__) || (ZEND_GCC_VERSION >= 9000)) ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_pclmul(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("pclmul"); } #else static inline int zend_cpu_supports_pclmul(void) { return zend_cpu_supports(ZEND_CPU_FEATURE_PCLMULQDQ); } #endif /* __builtin_cpu_supports has cldemote from gcc11 */ #if PHP_HAVE_BUILTIN_CPU_SUPPORTS && defined(__GNUC__) && (ZEND_GCC_VERSION >= 11000) ZEND_NO_SANITIZE_ADDRESS static inline int zend_cpu_supports_cldemote(void) { #if PHP_HAVE_BUILTIN_CPU_INIT __builtin_cpu_init(); #endif return __builtin_cpu_supports("cldemote"); } #endif #endif
9,097
32.326007
87
h
php-src
php-src-master/Zend/zend_default_classes.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Sterling Hughes <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_API.h" #include "zend_attributes.h" #include "zend_builtin_functions.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "zend_closures.h" #include "zend_generators.h" #include "zend_weakrefs.h" #include "zend_enum.h" #include "zend_fibers.h" ZEND_API void zend_register_default_classes(void) { zend_register_interfaces(); zend_register_default_exception(); zend_register_iterator_wrapper(); zend_register_closure_ce(); zend_register_generator_ce(); zend_register_weakref_ce(); zend_register_attribute_ce(); zend_register_enum_ce(); zend_register_fiber_ce(); }
1,845
40.954545
75
c
php-src
php-src-master/Zend/zend_dtrace.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: David Soria Parra <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_API.h" #include "zend_dtrace.h" #ifdef HAVE_DTRACE ZEND_API zend_op_array *(*zend_dtrace_compile_file)(zend_file_handle *file_handle, int type); ZEND_API void (*zend_dtrace_execute)(zend_op_array *op_array); ZEND_API void (*zend_dtrace_execute_internal)(zend_execute_data *execute_data, zval *return_value); /* PHP DTrace probes {{{ */ static inline const char *dtrace_get_executed_filename(void) { zend_execute_data *ex = EG(current_execute_data); while (ex && (!ex->func || !ZEND_USER_CODE(ex->func->type))) { ex = ex->prev_execute_data; } if (ex) { return ZSTR_VAL(ex->func->op_array.filename); } else { return zend_get_executed_filename(); } } ZEND_API zend_op_array *dtrace_compile_file(zend_file_handle *file_handle, int type) { zend_op_array *res; DTRACE_COMPILE_FILE_ENTRY(ZSTR_VAL(file_handle->opened_path), ZSTR_VAL(file_handle->filename)); res = compile_file(file_handle, type); DTRACE_COMPILE_FILE_RETURN(ZSTR_VAL(file_handle->opened_path), ZSTR_VAL(file_handle->filename)); return res; } /* We wrap the execute function to have fire the execute-entry/return and function-entry/return probes */ ZEND_API void dtrace_execute_ex(zend_execute_data *execute_data) { int lineno; const char *scope, *filename, *funcname, *classname; scope = filename = funcname = classname = NULL; /* we need filename and lineno for both execute and function probes */ if (DTRACE_EXECUTE_ENTRY_ENABLED() || DTRACE_EXECUTE_RETURN_ENABLED() || DTRACE_FUNCTION_ENTRY_ENABLED() || DTRACE_FUNCTION_RETURN_ENABLED()) { filename = dtrace_get_executed_filename(); lineno = zend_get_executed_lineno(); } if (DTRACE_FUNCTION_ENTRY_ENABLED() || DTRACE_FUNCTION_RETURN_ENABLED()) { classname = get_active_class_name(&scope); funcname = get_active_function_name(); } if (DTRACE_EXECUTE_ENTRY_ENABLED()) { DTRACE_EXECUTE_ENTRY((char *)filename, lineno); } if (DTRACE_FUNCTION_ENTRY_ENABLED() && funcname != NULL) { DTRACE_FUNCTION_ENTRY((char *)funcname, (char *)filename, lineno, (char *)classname, (char *)scope); } execute_ex(execute_data); if (DTRACE_FUNCTION_RETURN_ENABLED() && funcname != NULL) { DTRACE_FUNCTION_RETURN((char *)funcname, (char *)filename, lineno, (char *)classname, (char *)scope); } if (DTRACE_EXECUTE_RETURN_ENABLED()) { DTRACE_EXECUTE_RETURN((char *)filename, lineno); } } ZEND_API void dtrace_execute_internal(zend_execute_data *execute_data, zval *return_value) { int lineno; const char *filename; if (DTRACE_EXECUTE_ENTRY_ENABLED() || DTRACE_EXECUTE_RETURN_ENABLED()) { filename = dtrace_get_executed_filename(); lineno = zend_get_executed_lineno(); } if (DTRACE_EXECUTE_ENTRY_ENABLED()) { DTRACE_EXECUTE_ENTRY((char *)filename, lineno); } execute_internal(execute_data, return_value); if (DTRACE_EXECUTE_RETURN_ENABLED()) { DTRACE_EXECUTE_RETURN((char *)filename, lineno); } } void dtrace_error_notify_cb(int type, zend_string *error_filename, uint32_t error_lineno, zend_string *message) { if (DTRACE_ERROR_ENABLED()) { DTRACE_ERROR(ZSTR_VAL(message), ZSTR_VAL(error_filename), error_lineno); } } /* }}} */ #endif /* HAVE_DTRACE */
4,313
34.360656
111
c
php-src
php-src-master/Zend/zend_dtrace.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: David Soria Parra <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef _ZEND_DTRACE_H #define _ZEND_DTRACE_H #ifndef ZEND_WIN32 # include <unistd.h> #endif #ifdef __cplusplus extern "C" { #endif #ifdef HAVE_DTRACE ZEND_API extern zend_op_array *(*zend_dtrace_compile_file)(zend_file_handle *file_handle, int type); ZEND_API extern void (*zend_dtrace_execute)(zend_op_array *op_array); ZEND_API extern void (*zend_dtrace_execute_internal)(zend_execute_data *execute_data, zval *return_value); ZEND_API zend_op_array *dtrace_compile_file(zend_file_handle *file_handle, int type); ZEND_API void dtrace_execute_ex(zend_execute_data *execute_data); ZEND_API void dtrace_execute_internal(zend_execute_data *execute_data, zval *return_value); #include <zend_dtrace_gen.h> void dtrace_error_notify_cb(int type, zend_string *error_filename, uint32_t error_lineno, zend_string *message); #endif /* HAVE_DTRACE */ #ifdef __cplusplus } #endif #endif /* _ZEND_DTRACE_H */
2,051
40.877551
112
h
php-src
php-src-master/Zend/zend_enum_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: 7092f1d4ba651f077cff37050899f090f00abf22 */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_UnitEnum_cases, 0, 0, IS_ARRAY, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_BackedEnum_from, 0, 1, IS_STATIC, 0) ZEND_ARG_TYPE_MASK(0, value, MAY_BE_LONG|MAY_BE_STRING, NULL) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_BackedEnum_tryFrom, 0, 1, IS_STATIC, 1) ZEND_ARG_TYPE_MASK(0, value, MAY_BE_LONG|MAY_BE_STRING, NULL) ZEND_END_ARG_INFO() static const zend_function_entry class_UnitEnum_methods[] = { ZEND_ABSTRACT_ME_WITH_FLAGS(UnitEnum, cases, arginfo_class_UnitEnum_cases, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_ABSTRACT) ZEND_FE_END }; static const zend_function_entry class_BackedEnum_methods[] = { ZEND_ABSTRACT_ME_WITH_FLAGS(BackedEnum, from, arginfo_class_BackedEnum_from, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_ABSTRACT) ZEND_ABSTRACT_ME_WITH_FLAGS(BackedEnum, tryFrom, arginfo_class_BackedEnum_tryFrom, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_ABSTRACT) ZEND_FE_END }; static zend_class_entry *register_class_UnitEnum(void) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "UnitEnum", class_UnitEnum_methods); class_entry = zend_register_internal_interface(&ce); return class_entry; } static zend_class_entry *register_class_BackedEnum(zend_class_entry *class_entry_UnitEnum) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "BackedEnum", class_BackedEnum_methods); class_entry = zend_register_internal_interface(&ce); zend_class_implements(class_entry, 1, class_entry_UnitEnum); return class_entry; }
1,704
33.1
134
h
php-src
php-src-master/Zend/zend_fibers_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: e82bbc8e81fe98873a9a5697a4b38e63a24379da */ ZEND_BEGIN_ARG_INFO_EX(arginfo_class_Fiber___construct, 0, 0, 1) ZEND_ARG_TYPE_INFO(0, callback, IS_CALLABLE, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Fiber_start, 0, 0, IS_MIXED, 0) ZEND_ARG_VARIADIC_TYPE_INFO(0, args, IS_MIXED, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Fiber_resume, 0, 0, IS_MIXED, 0) ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, value, IS_MIXED, 0, "null") ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Fiber_throw, 0, 1, IS_MIXED, 0) ZEND_ARG_OBJ_INFO(0, exception, Throwable, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Fiber_isStarted, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() #define arginfo_class_Fiber_isSuspended arginfo_class_Fiber_isStarted #define arginfo_class_Fiber_isRunning arginfo_class_Fiber_isStarted #define arginfo_class_Fiber_isTerminated arginfo_class_Fiber_isStarted ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Fiber_getReturn, 0, 0, IS_MIXED, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_Fiber_getCurrent, 0, 0, Fiber, 1) ZEND_END_ARG_INFO() #define arginfo_class_Fiber_suspend arginfo_class_Fiber_resume ZEND_BEGIN_ARG_INFO_EX(arginfo_class_FiberError___construct, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_METHOD(Fiber, __construct); ZEND_METHOD(Fiber, start); ZEND_METHOD(Fiber, resume); ZEND_METHOD(Fiber, throw); ZEND_METHOD(Fiber, isStarted); ZEND_METHOD(Fiber, isSuspended); ZEND_METHOD(Fiber, isRunning); ZEND_METHOD(Fiber, isTerminated); ZEND_METHOD(Fiber, getReturn); ZEND_METHOD(Fiber, getCurrent); ZEND_METHOD(Fiber, suspend); ZEND_METHOD(FiberError, __construct); static const zend_function_entry class_Fiber_methods[] = { ZEND_ME(Fiber, __construct, arginfo_class_Fiber___construct, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, start, arginfo_class_Fiber_start, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, resume, arginfo_class_Fiber_resume, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, throw, arginfo_class_Fiber_throw, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, isStarted, arginfo_class_Fiber_isStarted, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, isSuspended, arginfo_class_Fiber_isSuspended, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, isRunning, arginfo_class_Fiber_isRunning, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, isTerminated, arginfo_class_Fiber_isTerminated, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, getReturn, arginfo_class_Fiber_getReturn, ZEND_ACC_PUBLIC) ZEND_ME(Fiber, getCurrent, arginfo_class_Fiber_getCurrent, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_ME(Fiber, suspend, arginfo_class_Fiber_suspend, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC) ZEND_FE_END }; static const zend_function_entry class_FiberError_methods[] = { ZEND_ME(FiberError, __construct, arginfo_class_FiberError___construct, ZEND_ACC_PUBLIC) ZEND_FE_END }; static zend_class_entry *register_class_Fiber(void) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "Fiber", class_Fiber_methods); class_entry = zend_register_internal_class_ex(&ce, NULL); class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NO_DYNAMIC_PROPERTIES|ZEND_ACC_NOT_SERIALIZABLE; return class_entry; } static zend_class_entry *register_class_FiberError(zend_class_entry *class_entry_Error) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "FiberError", class_FiberError_methods); class_entry = zend_register_internal_class_ex(&ce, class_entry_Error); class_entry->ce_flags |= ZEND_ACC_FINAL; return class_entry; }
3,569
35.804124
98
h
php-src
php-src-master/Zend/zend_float.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Seiler <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_compile.h" #include "zend_float.h" ZEND_API void zend_init_fpu(void) /* {{{ */ { #if XPFPA_HAVE_CW XPFPA_DECLARE if (!EG(saved_fpu_cw_ptr)) { EG(saved_fpu_cw_ptr) = (void*)&EG(saved_fpu_cw); } XPFPA_STORE_CW(EG(saved_fpu_cw_ptr)); XPFPA_SWITCH_DOUBLE(); #else EG(saved_fpu_cw_ptr) = NULL; #endif } /* }}} */ ZEND_API void zend_shutdown_fpu(void) /* {{{ */ { #if XPFPA_HAVE_CW if (EG(saved_fpu_cw_ptr)) { XPFPA_RESTORE_CW(EG(saved_fpu_cw_ptr)); } #endif EG(saved_fpu_cw_ptr) = NULL; } /* }}} */ ZEND_API void zend_ensure_fpu_mode(void) /* {{{ */ { XPFPA_DECLARE XPFPA_SWITCH_DOUBLE(); } /* }}} */
1,796
30.526316
75
c
php-src
php-src-master/Zend/zend_float.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Christian Seiler <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_FLOAT_H #define ZEND_FLOAT_H BEGIN_EXTERN_C() /* Define functions for FP initialization and de-initialization. */ extern ZEND_API void zend_init_fpu(void); extern ZEND_API void zend_shutdown_fpu(void); extern ZEND_API void zend_ensure_fpu_mode(void); END_EXTERN_C() /* Copy of the contents of xpfpa.h (which is under public domain) See http://wiki.php.net/rfc/rounding for details. Cross Platform Floating Point Arithmetics This header file defines several platform-dependent macros that ensure equal and deterministic floating point behaviour across several platforms, compilers and architectures. The current macros are currently only used on x86 and x86_64 architectures, on every other architecture, these macros expand to NOPs. This assumes that other architectures do not have an internal precision and the operhand types define the computational precision of floating point operations. This assumption may be false, in that case, the author is interested in further details on the other platform. For further details, please visit: http://www.christian-seiler.de/projekte/fpmath/ Version: 20090317 */ /* Implementation notes: x86_64: - Since all x86_64 compilers use SSE by default, we do not define these macros there. We ignore the compiler option -mfpmath=i387, because there is no reason to use it on x86_64. General: - It would be nice if one could detect whether SSE if used for math via some funky compiler defines and if so, make the macros go to NOPs. Any ideas on how to do that? MS Visual C: - Since MSVC users typically don't use autoconf or CMake, we will detect MSVC via compile time define. */ /* MSVC detection (MSVC people usually don't use autoconf) */ #if defined(_MSC_VER) && !defined(_WIN64) # define HAVE__CONTROLFP_S #endif /* _MSC_VER */ #if defined(HAVE__CONTROLFP_S) && !defined(__x86_64__) /* float.h defines _controlfp_s */ # include <float.h> # define XPFPA_HAVE_CW 1 # define XPFPA_CW_DATATYPE \ unsigned int # define XPFPA_STORE_CW(vptr) do { \ _controlfp_s((unsigned int *)(vptr), 0, 0); \ } while (0) # define XPFPA_RESTORE_CW(vptr) do { \ unsigned int _xpfpa_fpu_cw; \ _controlfp_s(&_xpfpa_fpu_cw, *((unsigned int *)(vptr)), _MCW_PC); \ } while (0) # define XPFPA_DECLARE \ unsigned int _xpfpa_fpu_oldcw, _xpfpa_fpu_cw; # define XPFPA_SWITCH_DOUBLE() do { \ _controlfp_s(&_xpfpa_fpu_cw, 0, 0); \ _xpfpa_fpu_oldcw = _xpfpa_fpu_cw; \ _controlfp_s(&_xpfpa_fpu_cw, _PC_53, _MCW_PC); \ } while (0) # define XPFPA_SWITCH_SINGLE() do { \ _controlfp_s(&_xpfpa_fpu_cw, 0, 0); \ _xpfpa_fpu_oldcw = _xpfpa_fpu_cw; \ _controlfp_s(&_xpfpa_fpu_cw, _PC_24, _MCW_PC); \ } while (0) /* NOTE: This only sets internal precision. MSVC does NOT support double- extended precision! */ # define XPFPA_SWITCH_DOUBLE_EXTENDED() do { \ _controlfp_s(&_xpfpa_fpu_cw, 0, 0); \ _xpfpa_fpu_oldcw = _xpfpa_fpu_cw; \ _controlfp_s(&_xpfpa_fpu_cw, _PC_64, _MCW_PC); \ } while (0) # define XPFPA_RESTORE() \ _controlfp_s(&_xpfpa_fpu_cw, _xpfpa_fpu_oldcw, _MCW_PC) /* We do NOT use the volatile return trick since _controlfp_s is a function call and thus FP registers are saved in memory anyway. However, we do use a variable to ensure that the expression passed into val will be evaluated *before* switching back contexts. */ # define XPFPA_RETURN_DOUBLE(val) \ do { \ double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_SINGLE(val) \ do { \ float _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) /* This won't work, but we add a macro for it anyway. */ # define XPFPA_RETURN_DOUBLE_EXTENDED(val) \ do { \ long double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) #elif defined(HAVE__CONTROLFP) && !defined(__x86_64__) /* float.h defines _controlfp */ # include <float.h> # define XPFPA_DECLARE \ unsigned int _xpfpa_fpu_oldcw; # define XPFPA_HAVE_CW 1 # define XPFPA_CW_DATATYPE \ unsigned int # define XPFPA_STORE_CW(vptr) do { \ *((unsigned int *)(vptr)) = _controlfp(0, 0); \ } while (0) # define XPFPA_RESTORE_CW(vptr) do { \ _controlfp(*((unsigned int *)(vptr)), _MCW_PC); \ } while (0) # define XPFPA_SWITCH_DOUBLE() do { \ _xpfpa_fpu_oldcw = _controlfp(0, 0); \ _controlfp(_PC_53, _MCW_PC); \ } while (0) # define XPFPA_SWITCH_SINGLE() do { \ _xpfpa_fpu_oldcw = _controlfp(0, 0); \ _controlfp(_PC_24, _MCW_PC); \ } while (0) /* NOTE: This will only work as expected on MinGW. */ # define XPFPA_SWITCH_DOUBLE_EXTENDED() do { \ _xpfpa_fpu_oldcw = _controlfp(0, 0); \ _controlfp(_PC_64, _MCW_PC); \ } while (0) # define XPFPA_RESTORE() \ _controlfp(_xpfpa_fpu_oldcw, _MCW_PC) /* We do NOT use the volatile return trick since _controlfp is a function call and thus FP registers are saved in memory anyway. However, we do use a variable to ensure that the expression passed into val will be evaluated *before* switching back contexts. */ # define XPFPA_RETURN_DOUBLE(val) \ do { \ double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_SINGLE(val) \ do { \ float _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) /* This will only work on MinGW */ # define XPFPA_RETURN_DOUBLE_EXTENDED(val) \ do { \ long double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) #elif defined(HAVE__FPU_SETCW) && !defined(__x86_64__) /* glibc systems */ /* fpu_control.h defines _FPU_[GS]ETCW */ # include <fpu_control.h> # define XPFPA_DECLARE \ fpu_control_t _xpfpa_fpu_oldcw, _xpfpa_fpu_cw; # define XPFPA_HAVE_CW 1 # define XPFPA_CW_DATATYPE \ fpu_control_t # define XPFPA_STORE_CW(vptr) do { \ _FPU_GETCW((*((fpu_control_t *)(vptr)))); \ } while (0) # define XPFPA_RESTORE_CW(vptr) do { \ _FPU_SETCW((*((fpu_control_t *)(vptr)))); \ } while (0) # define XPFPA_SWITCH_DOUBLE() do { \ _FPU_GETCW(_xpfpa_fpu_oldcw); \ _xpfpa_fpu_cw = (_xpfpa_fpu_oldcw & ~_FPU_EXTENDED & ~_FPU_SINGLE) | _FPU_DOUBLE; \ _FPU_SETCW(_xpfpa_fpu_cw); \ } while (0) # define XPFPA_SWITCH_SINGLE() do { \ _FPU_GETCW(_xpfpa_fpu_oldcw); \ _xpfpa_fpu_cw = (_xpfpa_fpu_oldcw & ~_FPU_EXTENDED & ~_FPU_DOUBLE) | _FPU_SINGLE; \ _FPU_SETCW(_xpfpa_fpu_cw); \ } while (0) # define XPFPA_SWITCH_DOUBLE_EXTENDED() do { \ _FPU_GETCW(_xpfpa_fpu_oldcw); \ _xpfpa_fpu_cw = (_xpfpa_fpu_oldcw & ~_FPU_SINGLE & ~_FPU_DOUBLE) | _FPU_EXTENDED; \ _FPU_SETCW(_xpfpa_fpu_cw); \ } while (0) # define XPFPA_RESTORE() \ _FPU_SETCW(_xpfpa_fpu_oldcw) /* We use a temporary volatile variable (in a new block) in order to ensure that the optimizer does not mis-optimize the instructions. Also, a volatile variable ensures truncation to correct precision. */ # define XPFPA_RETURN_DOUBLE(val) \ do { \ volatile double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_SINGLE(val) \ do { \ volatile float _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_DOUBLE_EXTENDED(val) \ do { \ volatile long double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) #elif defined(HAVE_FPSETPREC) && !defined(__x86_64__) /* FreeBSD */ /* fpu_control.h defines _FPU_[GS]ETCW */ # include <machine/ieeefp.h> # define XPFPA_DECLARE \ fp_prec_t _xpfpa_fpu_oldprec; # define XPFPA_HAVE_CW 1 # define XPFPA_CW_DATATYPE \ fp_prec_t # define XPFPA_STORE_CW(vptr) do { \ *((fp_prec_t *)(vptr)) = fpgetprec(); \ } while (0) # define XPFPA_RESTORE_CW(vptr) do { \ fpsetprec(*((fp_prec_t *)(vptr))); \ } while (0) # define XPFPA_SWITCH_DOUBLE() do { \ _xpfpa_fpu_oldprec = fpgetprec(); \ fpsetprec(FP_PD); \ } while (0) # define XPFPA_SWITCH_SINGLE() do { \ _xpfpa_fpu_oldprec = fpgetprec(); \ fpsetprec(FP_PS); \ } while (0) # define XPFPA_SWITCH_DOUBLE_EXTENDED() do { \ _xpfpa_fpu_oldprec = fpgetprec(); \ fpsetprec(FP_PE); \ } while (0) # define XPFPA_RESTORE() \ fpsetprec(_xpfpa_fpu_oldprec) /* We use a temporary volatile variable (in a new block) in order to ensure that the optimizer does not mis-optimize the instructions. Also, a volatile variable ensures truncation to correct precision. */ # define XPFPA_RETURN_DOUBLE(val) \ do { \ volatile double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_SINGLE(val) \ do { \ volatile float _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_DOUBLE_EXTENDED(val) \ do { \ volatile long double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) #elif defined(HAVE_FPU_INLINE_ASM_X86) && !defined(__x86_64__) /* Custom x86 inline assembler implementation. This implementation does not use predefined wrappers of the OS / compiler but rather uses x86/x87 inline assembler directly. Basic instructions: fnstcw - Store the FPU control word in a variable fldcw - Load the FPU control word from a variable Bits (only bits 8 and 9 are relevant, bits 0 to 7 are for other things): 0x0yy: Single precision 0x1yy: Reserved 0x2yy: Double precision 0x3yy: Double-extended precision We use an unsigned int for the datatype. glibc sources add __mode__ (__HI__) attribute to it (HI stands for half-integer according to docs). It is unclear what the does exactly and how portable it is. The assembly syntax works with GNU CC, Intel CC and Sun CC. */ # define XPFPA_DECLARE \ unsigned int _xpfpa_fpu_oldcw, _xpfpa_fpu_cw; # define XPFPA_HAVE_CW 1 # define XPFPA_CW_DATATYPE \ unsigned int # define XPFPA_STORE_CW(vptr) do { \ __asm__ __volatile__ ("fnstcw %0" : "=m" (*((unsigned int *)(vptr)))); \ } while (0) # define XPFPA_RESTORE_CW(vptr) do { \ __asm__ __volatile__ ("fldcw %0" : : "m" (*((unsigned int *)(vptr)))); \ } while (0) # define XPFPA_SWITCH_DOUBLE() do { \ __asm__ __volatile__ ("fnstcw %0" : "=m" (*&_xpfpa_fpu_oldcw)); \ _xpfpa_fpu_cw = (_xpfpa_fpu_oldcw & ~0x100) | 0x200; \ __asm__ __volatile__ ("fldcw %0" : : "m" (*&_xpfpa_fpu_cw)); \ } while (0) # define XPFPA_SWITCH_SINGLE() do { \ __asm__ __volatile__ ("fnstcw %0" : "=m" (*&_xpfpa_fpu_oldcw)); \ _xpfpa_fpu_cw = (_xpfpa_fpu_oldcw & ~0x300); \ __asm__ __volatile__ ("fldcw %0" : : "m" (*&_xpfpa_fpu_cw)); \ } while (0) # define XPFPA_SWITCH_DOUBLE_EXTENDED() do { \ __asm__ __volatile__ ("fnstcw %0" : "=m" (*&_xpfpa_fpu_oldcw)); \ _xpfpa_fpu_cw = _xpfpa_fpu_oldcw | 0x300; \ __asm__ __volatile__ ("fldcw %0" : : "m" (*&_xpfpa_fpu_cw)); \ } while (0) # define XPFPA_RESTORE() \ __asm__ __volatile__ ("fldcw %0" : : "m" (*&_xpfpa_fpu_oldcw)) /* We use a temporary volatile variable (in a new block) in order to ensure that the optimizer does not mis-optimize the instructions. Also, a volatile variable ensures truncation to correct precision. */ # define XPFPA_RETURN_DOUBLE(val) \ do { \ volatile double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_SINGLE(val) \ do { \ volatile float _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) # define XPFPA_RETURN_DOUBLE_EXTENDED(val) \ do { \ volatile long double _xpfpa_result = (val); \ XPFPA_RESTORE(); \ return _xpfpa_result; \ } while (0) #else /* FPU CONTROL */ /* This is either not an x87 FPU or the inline assembly syntax was not recognized. In any case, default to NOPs for the macros and hope the generated code will behave as planned. */ # define XPFPA_DECLARE /* NOP */ # define XPFPA_HAVE_CW 0 # define XPFPA_CW_DATATYPE unsigned int # define XPFPA_STORE_CW(variable) /* NOP */ # define XPFPA_RESTORE_CW(variable) /* NOP */ # define XPFPA_SWITCH_DOUBLE() /* NOP */ # define XPFPA_SWITCH_SINGLE() /* NOP */ # define XPFPA_SWITCH_DOUBLE_EXTENDED() /* NOP */ # define XPFPA_RESTORE() /* NOP */ # define XPFPA_RETURN_DOUBLE(val) return (val) # define XPFPA_RETURN_SINGLE(val) return (val) # define XPFPA_RETURN_DOUBLE_EXTENDED(val) return (val) #endif /* FPU CONTROL */ #endif
15,438
36.112981
95
h
php-src
php-src-master/Zend/zend_gc.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: David Wang <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_GC_H #define ZEND_GC_H #include "zend_hrtime.h" #ifndef GC_BENCH # define GC_BENCH 0 #endif BEGIN_EXTERN_C() typedef struct _zend_gc_status { bool active; bool gc_protected; bool full; uint32_t runs; uint32_t collected; uint32_t threshold; uint32_t buf_size; uint32_t num_roots; zend_hrtime_t application_time; zend_hrtime_t collector_time; zend_hrtime_t dtor_time; zend_hrtime_t free_time; } zend_gc_status; ZEND_API extern int (*gc_collect_cycles)(void); ZEND_API void ZEND_FASTCALL gc_possible_root(zend_refcounted *ref); ZEND_API void ZEND_FASTCALL gc_remove_from_buffer(zend_refcounted *ref); /* enable/disable automatic start of GC collection */ ZEND_API bool gc_enable(bool enable); ZEND_API bool gc_enabled(void); /* enable/disable possible root additions */ ZEND_API bool gc_protect(bool protect); ZEND_API bool gc_protected(void); #if GC_BENCH void gc_bench_print(void); #endif /* The default implementation of the gc_collect_cycles callback. */ ZEND_API int zend_gc_collect_cycles(void); ZEND_API void zend_gc_get_status(zend_gc_status *status); void gc_globals_ctor(void); void gc_globals_dtor(void); void gc_reset(void); #ifdef ZTS size_t zend_gc_globals_size(void); #endif #define GC_REMOVE_FROM_BUFFER(p) do { \ zend_refcounted *_p = (zend_refcounted*)(p); \ if (GC_TYPE_INFO(_p) & GC_INFO_MASK) { \ gc_remove_from_buffer(_p); \ } \ } while (0) #define GC_MAY_LEAK(ref) \ ((GC_TYPE_INFO(ref) & \ (GC_INFO_MASK | (GC_NOT_COLLECTABLE << GC_FLAGS_SHIFT))) == 0) static zend_always_inline void gc_check_possible_root(zend_refcounted *ref) { if (EXPECTED(GC_TYPE_INFO(ref) == GC_REFERENCE)) { zval *zv = &((zend_reference*)ref)->val; if (!Z_COLLECTABLE_P(zv)) { return; } ref = Z_COUNTED_P(zv); } if (UNEXPECTED(GC_MAY_LEAK(ref))) { gc_possible_root(ref); } } static zend_always_inline void gc_check_possible_root_no_ref(zend_refcounted *ref) { ZEND_ASSERT(GC_TYPE_INFO(ref) != GC_REFERENCE); if (UNEXPECTED(GC_MAY_LEAK(ref))) { gc_possible_root(ref); } } /* These APIs can be used to simplify object get_gc implementations * over heterogeneous structures. See zend_generator_get_gc() for * a usage example. */ typedef struct { zval *cur; zval *end; zval *start; } zend_get_gc_buffer; ZEND_API zend_get_gc_buffer *zend_get_gc_buffer_create(void); ZEND_API void zend_get_gc_buffer_grow(zend_get_gc_buffer *gc_buffer); static zend_always_inline void zend_get_gc_buffer_add_zval( zend_get_gc_buffer *gc_buffer, zval *zv) { if (Z_REFCOUNTED_P(zv)) { if (UNEXPECTED(gc_buffer->cur == gc_buffer->end)) { zend_get_gc_buffer_grow(gc_buffer); } ZVAL_COPY_VALUE(gc_buffer->cur, zv); gc_buffer->cur++; } } static zend_always_inline void zend_get_gc_buffer_add_obj( zend_get_gc_buffer *gc_buffer, zend_object *obj) { if (UNEXPECTED(gc_buffer->cur == gc_buffer->end)) { zend_get_gc_buffer_grow(gc_buffer); } ZVAL_OBJ(gc_buffer->cur, obj); gc_buffer->cur++; } static zend_always_inline void zend_get_gc_buffer_add_ptr( zend_get_gc_buffer *gc_buffer, void *ptr) { if (UNEXPECTED(gc_buffer->cur == gc_buffer->end)) { zend_get_gc_buffer_grow(gc_buffer); } ZVAL_PTR(gc_buffer->cur, ptr); gc_buffer->cur++; } static zend_always_inline void zend_get_gc_buffer_use( zend_get_gc_buffer *gc_buffer, zval **table, int *n) { *table = gc_buffer->start; *n = gc_buffer->cur - gc_buffer->start; } END_EXTERN_C() #endif /* ZEND_GC_H */
4,668
28
82
h
php-src
php-src-master/Zend/zend_gdb.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_gdb.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #if defined(__FreeBSD__) && __FreeBSD_version >= 1100000 # include <sys/user.h> # include <libutil.h> #endif enum { ZEND_GDBJIT_NOACTION, ZEND_GDBJIT_REGISTER, ZEND_GDBJIT_UNREGISTER }; typedef struct _zend_gdbjit_code_entry { struct _zend_gdbjit_code_entry *next_entry; struct _zend_gdbjit_code_entry *prev_entry; const char *symfile_addr; uint64_t symfile_size; } zend_gdbjit_code_entry; typedef struct _zend_gdbjit_descriptor { uint32_t version; uint32_t action_flag; struct _zend_gdbjit_code_entry *relevant_entry; struct _zend_gdbjit_code_entry *first_entry; } zend_gdbjit_descriptor; ZEND_API zend_gdbjit_descriptor __jit_debug_descriptor = { 1, ZEND_GDBJIT_NOACTION, NULL, NULL }; ZEND_API zend_never_inline void __jit_debug_register_code(void) { __asm__ __volatile__(""); } ZEND_API bool zend_gdb_register_code(const void *object, size_t size) { zend_gdbjit_code_entry *entry; entry = malloc(sizeof(zend_gdbjit_code_entry) + size); if (entry == NULL) { return 0; } entry->symfile_addr = ((char*)entry) + sizeof(zend_gdbjit_code_entry); entry->symfile_size = size; memcpy((char *)entry->symfile_addr, object, size); entry->prev_entry = NULL; entry->next_entry = __jit_debug_descriptor.first_entry; if (entry->next_entry) { entry->next_entry->prev_entry = entry; } __jit_debug_descriptor.first_entry = entry; /* Notify GDB */ __jit_debug_descriptor.relevant_entry = entry; __jit_debug_descriptor.action_flag = ZEND_GDBJIT_REGISTER; __jit_debug_register_code(); return 1; } ZEND_API void zend_gdb_unregister_all(void) { zend_gdbjit_code_entry *entry; __jit_debug_descriptor.action_flag = ZEND_GDBJIT_UNREGISTER; while ((entry = __jit_debug_descriptor.first_entry)) { __jit_debug_descriptor.first_entry = entry->next_entry; if (entry->next_entry) { entry->next_entry->prev_entry = NULL; } /* Notify GDB */ __jit_debug_descriptor.relevant_entry = entry; __jit_debug_register_code(); free(entry); } } ZEND_API bool zend_gdb_present(void) { bool ret = 0; #if defined(__linux__) /* netbsd while having this procfs part, does not hold the tracer pid */ int fd = open("/proc/self/status", O_RDONLY); if (fd >= 0) { char buf[1024]; ssize_t n = read(fd, buf, sizeof(buf) - 1); char *s; pid_t pid; if (n > 0) { buf[n] = 0; s = strstr(buf, "TracerPid:"); if (s) { s += sizeof("TracerPid:") - 1; while (*s == ' ' || *s == '\t') { s++; } pid = atoi(s); if (pid) { char out[1024]; sprintf(buf, "/proc/%d/exe", (int)pid); if (readlink(buf, out, sizeof(out) - 1) > 0) { if (strstr(out, "gdb")) { ret = 1; } } } } } close(fd); } #elif defined(__FreeBSD__) && __FreeBSD_version >= 1100000 struct kinfo_proc *proc = kinfo_getproc(getpid()); if (proc) { if ((proc->ki_flag & P_TRACED) != 0) { struct kinfo_proc *dbg = kinfo_getproc(proc->ki_tracer); ret = (dbg && strstr(dbg->ki_comm, "gdb")); } } #endif return ret; }
4,473
27.138365
95
c
php-src
php-src-master/Zend/zend_gdb.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_GDB #define ZEND_GDB ZEND_API bool zend_gdb_register_code(const void *object, size_t size); ZEND_API void zend_gdb_unregister_all(void); ZEND_API bool zend_gdb_present(void); #endif
1,420
49.75
75
h
php-src
php-src-master/Zend/zend_generators_arginfo.h
/* This is a generated file, edit the .stub.php file instead. * Stub hash: 0af5e8985dd4645bf23490b8cec312f8fd1fee2e */ ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Generator_rewind, 0, 0, IS_VOID, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Generator_valid, 0, 0, _IS_BOOL, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Generator_current, 0, 0, IS_MIXED, 0) ZEND_END_ARG_INFO() #define arginfo_class_Generator_key arginfo_class_Generator_current #define arginfo_class_Generator_next arginfo_class_Generator_rewind ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Generator_send, 0, 1, IS_MIXED, 0) ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_Generator_throw, 0, 1, IS_MIXED, 0) ZEND_ARG_OBJ_INFO(0, exception, Throwable, 0) ZEND_END_ARG_INFO() #define arginfo_class_Generator_getReturn arginfo_class_Generator_current ZEND_METHOD(Generator, rewind); ZEND_METHOD(Generator, valid); ZEND_METHOD(Generator, current); ZEND_METHOD(Generator, key); ZEND_METHOD(Generator, next); ZEND_METHOD(Generator, send); ZEND_METHOD(Generator, throw); ZEND_METHOD(Generator, getReturn); static const zend_function_entry class_Generator_methods[] = { ZEND_ME(Generator, rewind, arginfo_class_Generator_rewind, ZEND_ACC_PUBLIC) ZEND_ME(Generator, valid, arginfo_class_Generator_valid, ZEND_ACC_PUBLIC) ZEND_ME(Generator, current, arginfo_class_Generator_current, ZEND_ACC_PUBLIC) ZEND_ME(Generator, key, arginfo_class_Generator_key, ZEND_ACC_PUBLIC) ZEND_ME(Generator, next, arginfo_class_Generator_next, ZEND_ACC_PUBLIC) ZEND_ME(Generator, send, arginfo_class_Generator_send, ZEND_ACC_PUBLIC) ZEND_ME(Generator, throw, arginfo_class_Generator_throw, ZEND_ACC_PUBLIC) ZEND_ME(Generator, getReturn, arginfo_class_Generator_getReturn, ZEND_ACC_PUBLIC) ZEND_FE_END }; static const zend_function_entry class_ClosedGeneratorException_methods[] = { ZEND_FE_END }; static zend_class_entry *register_class_Generator(zend_class_entry *class_entry_Iterator) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "Generator", class_Generator_methods); class_entry = zend_register_internal_class_ex(&ce, NULL); class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NO_DYNAMIC_PROPERTIES|ZEND_ACC_NOT_SERIALIZABLE; zend_class_implements(class_entry, 1, class_entry_Iterator); return class_entry; } static zend_class_entry *register_class_ClosedGeneratorException(zend_class_entry *class_entry_Exception) { zend_class_entry ce, *class_entry; INIT_CLASS_ENTRY(ce, "ClosedGeneratorException", class_ClosedGeneratorException_methods); class_entry = zend_register_internal_class_ex(&ce, class_entry_Exception); return class_entry; }
2,787
35.684211
105
h
php-src
php-src-master/Zend/zend_globals.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_GLOBALS_H #define ZEND_GLOBALS_H #include <setjmp.h> #include <stdint.h> #include <sys/types.h> #include "zend_globals_macros.h" #include "zend_atomic.h" #include "zend_stack.h" #include "zend_ptr_stack.h" #include "zend_hash.h" #include "zend_llist.h" #include "zend_objects.h" #include "zend_objects_API.h" #include "zend_modules.h" #include "zend_float.h" #include "zend_multibyte.h" #include "zend_multiply.h" #include "zend_arena.h" #include "zend_call_stack.h" #include "zend_max_execution_timer.h" /* Define ZTS if you want a thread-safe Zend */ /*#undef ZTS*/ #ifdef ZTS BEGIN_EXTERN_C() ZEND_API extern int compiler_globals_id; ZEND_API extern int executor_globals_id; ZEND_API extern size_t compiler_globals_offset; ZEND_API extern size_t executor_globals_offset; END_EXTERN_C() #endif #define SYMTABLE_CACHE_SIZE 32 #ifdef ZEND_CHECK_STACK_LIMIT # define ZEND_MAX_ALLOWED_STACK_SIZE_UNCHECKED -1 # define ZEND_MAX_ALLOWED_STACK_SIZE_DETECT 0 #endif #include "zend_compile.h" /* excpt.h on Digital Unix 4.0 defines function_table */ #undef function_table typedef struct _zend_vm_stack *zend_vm_stack; typedef struct _zend_ini_entry zend_ini_entry; typedef struct _zend_fiber_context zend_fiber_context; typedef struct _zend_fiber zend_fiber; typedef enum { ZEND_MEMOIZE_NONE, ZEND_MEMOIZE_COMPILE, ZEND_MEMOIZE_FETCH, } zend_memoize_mode; struct _zend_compiler_globals { zend_stack loop_var_stack; zend_class_entry *active_class_entry; zend_string *compiled_filename; int zend_lineno; zend_op_array *active_op_array; HashTable *function_table; /* function symbol table */ HashTable *class_table; /* class table */ HashTable *auto_globals; /* Refer to zend_yytnamerr() in zend_language_parser.y for meaning of values */ uint8_t parse_error; bool in_compilation; bool short_tags; bool unclean_shutdown; bool ini_parser_unbuffered_errors; zend_llist open_files; struct _zend_ini_parser_param *ini_parser_param; bool skip_shebang; bool increment_lineno; bool variable_width_locale; /* UTF-8, Shift-JIS, Big5, ISO 2022, EUC, etc */ bool ascii_compatible_locale; /* locale uses ASCII characters as singletons */ /* and don't use them as lead/trail units */ zend_string *doc_comment; uint32_t extra_fn_flags; uint32_t compiler_options; /* set of ZEND_COMPILE_* constants */ zend_oparray_context context; zend_file_context file_context; zend_arena *arena; HashTable interned_strings; const zend_encoding **script_encoding_list; size_t script_encoding_list_size; bool multibyte; bool detect_unicode; bool encoding_declared; zend_ast *ast; zend_arena *ast_arena; zend_stack delayed_oplines_stack; HashTable *memoized_exprs; zend_memoize_mode memoize_mode; void *map_ptr_real_base; void *map_ptr_base; size_t map_ptr_size; size_t map_ptr_last; HashTable *delayed_variance_obligations; HashTable *delayed_autoloads; HashTable *unlinked_uses; zend_class_entry *current_linking_class; uint32_t rtd_key_counter; zend_stack short_circuiting_opnums; #ifdef ZTS uint32_t copied_functions_count; #endif }; struct _zend_executor_globals { zval uninitialized_zval; zval error_zval; /* symbol table cache */ zend_array *symtable_cache[SYMTABLE_CACHE_SIZE]; /* Pointer to one past the end of the symtable_cache */ zend_array **symtable_cache_limit; /* Pointer to first unused symtable_cache slot */ zend_array **symtable_cache_ptr; zend_array symbol_table; /* main symbol table */ HashTable included_files; /* files already included */ JMP_BUF *bailout; int error_reporting; int exit_status; HashTable *function_table; /* function symbol table */ HashTable *class_table; /* class table */ HashTable *zend_constants; /* constants table */ zval *vm_stack_top; zval *vm_stack_end; zend_vm_stack vm_stack; size_t vm_stack_page_size; struct _zend_execute_data *current_execute_data; zend_class_entry *fake_scope; /* used to avoid checks accessing properties */ uint32_t jit_trace_num; /* Used by tracing JIT to reference the currently running trace */ int ticks_count; zend_long precision; uint32_t persistent_constants_count; uint32_t persistent_functions_count; uint32_t persistent_classes_count; /* for extended information support */ bool no_extensions; bool full_tables_cleanup; zend_atomic_bool vm_interrupt; zend_atomic_bool timed_out; HashTable *in_autoload; zend_long hard_timeout; void *stack_base; void *stack_limit; #ifdef ZEND_WIN32 OSVERSIONINFOEX windows_version_info; #endif HashTable regular_list; HashTable persistent_list; int user_error_handler_error_reporting; bool exception_ignore_args; zval user_error_handler; zval user_exception_handler; zend_stack user_error_handlers_error_reporting; zend_stack user_error_handlers; zend_stack user_exception_handlers; zend_class_entry *exception_class; zend_error_handling_t error_handling; int capture_warnings_during_sccp; /* timeout support */ zend_long timeout_seconds; HashTable *ini_directives; HashTable *modified_ini_directives; zend_ini_entry *error_reporting_ini_entry; zend_objects_store objects_store; zend_object *exception, *prev_exception; const zend_op *opline_before_exception; zend_op exception_op[3]; struct _zend_module_entry *current_module; bool active; uint8_t flags; zend_long assertions; uint32_t ht_iterators_count; /* number of allocated slots */ uint32_t ht_iterators_used; /* number of used slots */ HashTableIterator *ht_iterators; HashTableIterator ht_iterators_slots[16]; void *saved_fpu_cw_ptr; #if XPFPA_HAVE_CW XPFPA_CW_DATATYPE saved_fpu_cw; #endif zend_function trampoline; zend_op call_trampoline_op; HashTable weakrefs; zend_long exception_string_param_max_len; zend_get_gc_buffer get_gc_buffer; zend_fiber_context *main_fiber_context; zend_fiber_context *current_fiber_context; /* Active instance of Fiber. */ zend_fiber *active_fiber; /* Default fiber C stack size. */ size_t fiber_stack_size; /* If record_errors is enabled, all emitted diagnostics will be recorded, * in addition to being processed as usual. */ bool record_errors; uint32_t num_errors; zend_error_info **errors; /* Override filename or line number of thrown errors and exceptions */ zend_string *filename_override; zend_long lineno_override; #ifdef ZEND_CHECK_STACK_LIMIT zend_call_stack call_stack; zend_long max_allowed_stack_size; zend_ulong reserved_stack_size; #endif #ifdef ZEND_MAX_EXECUTION_TIMERS timer_t max_execution_timer_timer; pid_t pid; struct sigaction oldact; #endif void *reserved[ZEND_MAX_RESERVED_RESOURCES]; }; #define EG_FLAGS_INITIAL (0) #define EG_FLAGS_IN_SHUTDOWN (1<<0) #define EG_FLAGS_OBJECT_STORE_NO_REUSE (1<<1) #define EG_FLAGS_IN_RESOURCE_SHUTDOWN (1<<2) struct _zend_ini_scanner_globals { zend_file_handle *yy_in; zend_file_handle *yy_out; unsigned int yy_leng; const unsigned char *yy_start; const unsigned char *yy_text; const unsigned char *yy_cursor; const unsigned char *yy_marker; const unsigned char *yy_limit; int yy_state; zend_stack state_stack; zend_string *filename; int lineno; /* Modes are: ZEND_INI_SCANNER_NORMAL, ZEND_INI_SCANNER_RAW, ZEND_INI_SCANNER_TYPED */ int scanner_mode; }; typedef enum { ON_TOKEN, ON_FEEDBACK, ON_STOP } zend_php_scanner_event; struct _zend_php_scanner_globals { zend_file_handle *yy_in; zend_file_handle *yy_out; unsigned int yy_leng; unsigned char *yy_start; unsigned char *yy_text; unsigned char *yy_cursor; unsigned char *yy_marker; unsigned char *yy_limit; int yy_state; zend_stack state_stack; zend_ptr_stack heredoc_label_stack; zend_stack nest_location_stack; /* for syntax error reporting */ bool heredoc_scan_ahead; int heredoc_indentation; bool heredoc_indentation_uses_spaces; /* original (unfiltered) script */ unsigned char *script_org; size_t script_org_size; /* filtered script */ unsigned char *script_filtered; size_t script_filtered_size; /* input/output filters */ zend_encoding_filter input_filter; zend_encoding_filter output_filter; const zend_encoding *script_encoding; /* initial string length after scanning to first variable */ int scanned_string_len; /* hooks */ void (*on_event)( zend_php_scanner_event event, int token, int line, const char *text, size_t length, void *context); void *on_event_context; }; #endif /* ZEND_GLOBALS_H */
9,751
24.462141
91
h
php-src
php-src-master/Zend/zend_globals_macros.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_GLOBALS_MACROS_H #define ZEND_GLOBALS_MACROS_H typedef struct _zend_compiler_globals zend_compiler_globals; typedef struct _zend_executor_globals zend_executor_globals; typedef struct _zend_php_scanner_globals zend_php_scanner_globals; typedef struct _zend_ini_scanner_globals zend_ini_scanner_globals; BEGIN_EXTERN_C() /* Compiler */ #ifdef ZTS # define CG(v) ZEND_TSRMG_FAST(compiler_globals_offset, zend_compiler_globals *, v) #else # define CG(v) (compiler_globals.v) extern ZEND_API struct _zend_compiler_globals compiler_globals; #endif ZEND_API int zendparse(void); /* Executor */ #ifdef ZTS # define EG(v) ZEND_TSRMG_FAST(executor_globals_offset, zend_executor_globals *, v) #else # define EG(v) (executor_globals.v) extern ZEND_API zend_executor_globals executor_globals; #endif /* Language Scanner */ #ifdef ZTS # define LANG_SCNG(v) ZEND_TSRMG_FAST(language_scanner_globals_offset, zend_php_scanner_globals *, v) extern ZEND_API ts_rsrc_id language_scanner_globals_id; extern ZEND_API size_t language_scanner_globals_offset; #else # define LANG_SCNG(v) (language_scanner_globals.v) extern ZEND_API zend_php_scanner_globals language_scanner_globals; #endif /* INI Scanner */ #ifdef ZTS # define INI_SCNG(v) ZEND_TSRMG_FAST(ini_scanner_globals_offset, zend_ini_scanner_globals *, v) extern ZEND_API ts_rsrc_id ini_scanner_globals_id; extern ZEND_API size_t ini_scanner_globals_offset; #else # define INI_SCNG(v) (ini_scanner_globals.v) extern ZEND_API zend_ini_scanner_globals ini_scanner_globals; #endif END_EXTERN_C() #endif /* ZEND_GLOBALS_MACROS_H */
2,810
38.041667
101
h
php-src
php-src-master/Zend/zend_highlight.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include <zend_language_parser.h> #include "zend_compile.h" #include "zend_highlight.h" #include "zend_ptr_stack.h" #include "zend_globals.h" #include "zend_exceptions.h" ZEND_API void zend_html_putc(char c) { switch (c) { case '\n': ZEND_PUTS("<br />"); break; case '<': ZEND_PUTS("&lt;"); break; case '>': ZEND_PUTS("&gt;"); break; case '&': ZEND_PUTS("&amp;"); break; case ' ': ZEND_PUTS("&nbsp;"); break; case '\t': ZEND_PUTS("&nbsp;&nbsp;&nbsp;&nbsp;"); break; default: ZEND_PUTC(c); break; } } ZEND_API void zend_html_puts(const char *s, size_t len) { const unsigned char *ptr = (const unsigned char*)s, *end = ptr + len; unsigned char *filtered = NULL; size_t filtered_len; if (LANG_SCNG(output_filter)) { LANG_SCNG(output_filter)(&filtered, &filtered_len, ptr, len); ptr = filtered; end = filtered + filtered_len; } while (ptr<end) { if (*ptr==' ') { do { zend_html_putc(*ptr); } while ((++ptr < end) && (*ptr==' ')); } else { zend_html_putc(*ptr++); } } if (LANG_SCNG(output_filter)) { efree(filtered); } } ZEND_API void zend_highlight(zend_syntax_highlighter_ini *syntax_highlighter_ini) { zval token; int token_type; char *last_color = syntax_highlighter_ini->highlight_html; char *next_color; zend_printf("<code>"); zend_printf("<span style=\"color: %s\">\n", last_color); /* highlight stuff coming back from zendlex() */ while ((token_type=lex_scan(&token, NULL))) { switch (token_type) { case T_INLINE_HTML: next_color = syntax_highlighter_ini->highlight_html; break; case T_COMMENT: case T_DOC_COMMENT: next_color = syntax_highlighter_ini->highlight_comment; break; case T_OPEN_TAG: case T_OPEN_TAG_WITH_ECHO: case T_CLOSE_TAG: case T_LINE: case T_FILE: case T_DIR: case T_TRAIT_C: case T_METHOD_C: case T_FUNC_C: case T_NS_C: case T_CLASS_C: next_color = syntax_highlighter_ini->highlight_default; break; case '"': case T_ENCAPSED_AND_WHITESPACE: case T_CONSTANT_ENCAPSED_STRING: next_color = syntax_highlighter_ini->highlight_string; break; case T_WHITESPACE: zend_html_puts((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); /* no color needed */ ZVAL_UNDEF(&token); continue; break; default: if (Z_TYPE(token) == IS_UNDEF) { next_color = syntax_highlighter_ini->highlight_keyword; } else { next_color = syntax_highlighter_ini->highlight_default; } break; } if (last_color != next_color) { if (last_color != syntax_highlighter_ini->highlight_html) { zend_printf("</span>"); } last_color = next_color; if (last_color != syntax_highlighter_ini->highlight_html) { zend_printf("<span style=\"color: %s\">", last_color); } } zend_html_puts((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); if (Z_TYPE(token) == IS_STRING) { switch (token_type) { case T_OPEN_TAG: case T_OPEN_TAG_WITH_ECHO: case T_CLOSE_TAG: case T_WHITESPACE: case T_COMMENT: case T_DOC_COMMENT: break; default: zval_ptr_dtor_str(&token); break; } } ZVAL_UNDEF(&token); } if (last_color != syntax_highlighter_ini->highlight_html) { zend_printf("</span>\n"); } zend_printf("</span>\n"); zend_printf("</code>"); /* Discard parse errors thrown during tokenization */ zend_clear_exception(); } ZEND_API void zend_strip(void) { zval token; int token_type; int prev_space = 0; while ((token_type=lex_scan(&token, NULL))) { switch (token_type) { case T_WHITESPACE: if (!prev_space) { zend_write(" ", sizeof(" ") - 1); prev_space = 1; } ZEND_FALLTHROUGH; case T_COMMENT: case T_DOC_COMMENT: ZVAL_UNDEF(&token); continue; case T_END_HEREDOC: zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); /* read the following character, either newline or ; */ if (lex_scan(&token, NULL) != T_WHITESPACE) { zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); } zend_write("\n", sizeof("\n") - 1); prev_space = 1; ZVAL_UNDEF(&token); continue; default: zend_write((char*)LANG_SCNG(yy_text), LANG_SCNG(yy_leng)); break; } if (Z_TYPE(token) == IS_STRING) { switch (token_type) { case T_OPEN_TAG: case T_OPEN_TAG_WITH_ECHO: case T_CLOSE_TAG: case T_WHITESPACE: case T_COMMENT: case T_DOC_COMMENT: break; default: zval_ptr_dtor_str(&token); break; } } prev_space = 0; ZVAL_UNDEF(&token); } /* Discard parse errors thrown during tokenization */ zend_clear_exception(); }
5,885
24.480519
89
c
php-src
php-src-master/Zend/zend_highlight.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_HIGHLIGHT_H #define ZEND_HIGHLIGHT_H #define HL_COMMENT_COLOR "#FF8000" /* orange */ #define HL_DEFAULT_COLOR "#0000BB" /* blue */ #define HL_HTML_COLOR "#000000" /* black */ #define HL_STRING_COLOR "#DD0000" /* red */ #define HL_KEYWORD_COLOR "#007700" /* green */ typedef struct _zend_syntax_highlighter_ini { char *highlight_html; char *highlight_comment; char *highlight_default; char *highlight_string; char *highlight_keyword; } zend_syntax_highlighter_ini; BEGIN_EXTERN_C() ZEND_API void zend_highlight(zend_syntax_highlighter_ini *syntax_highlighter_ini); ZEND_API void zend_strip(void); ZEND_API zend_result highlight_file(const char *filename, zend_syntax_highlighter_ini *syntax_highlighter_ini); ZEND_API void highlight_string(zend_string *str, zend_syntax_highlighter_ini *syntax_highlighter_ini, const char *str_name); ZEND_API void zend_html_putc(char c); ZEND_API void zend_html_puts(const char *s, size_t len); END_EXTERN_C() extern zend_syntax_highlighter_ini syntax_highlighter_ini; #endif
2,296
44.039216
124
h
php-src
php-src-master/Zend/zend_hrtime.c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Niklas Keller <[email protected]> | | Author: Anatol Belski <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_hrtime.h" /* This file reuses code parts from the cross-platform timer library Public Domain - 2011 Mattias Jansson / Rampant Pixels */ #if ZEND_HRTIME_PLATFORM_POSIX # include <unistd.h> # include <time.h> # include <string.h> #elif ZEND_HRTIME_PLATFORM_WINDOWS # define WIN32_LEAN_AND_MEAN double zend_hrtime_timer_scale = .0; #elif ZEND_HRTIME_PLATFORM_APPLE # include <mach/mach_time.h> # include <string.h> mach_timebase_info_data_t zend_hrtime_timerlib_info = { .numer = 0, .denom = 1, }; #elif ZEND_HRTIME_PLATFORM_HPUX # include <sys/time.h> #elif ZEND_HRTIME_PLATFORM_AIX # include <sys/time.h> # include <sys/systemcfg.h> #endif void zend_startup_hrtime(void) { #if ZEND_HRTIME_PLATFORM_WINDOWS LARGE_INTEGER tf = {0}; if (QueryPerformanceFrequency(&tf) || 0 != tf.QuadPart) { zend_hrtime_timer_scale = (double)ZEND_NANO_IN_SEC / (zend_hrtime_t)tf.QuadPart; } #elif ZEND_HRTIME_PLATFORM_APPLE mach_timebase_info(&zend_hrtime_timerlib_info); #endif }
2,092
28.478873
82
c
php-src
php-src-master/Zend/zend_ini_scanner.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef _ZEND_INI_SCANNER_H #define _ZEND_INI_SCANNER_H /* Scanner modes */ #define ZEND_INI_SCANNER_NORMAL 0 /* Normal mode. [DEFAULT] */ #define ZEND_INI_SCANNER_RAW 1 /* Raw mode. Option values are not parsed */ #define ZEND_INI_SCANNER_TYPED 2 /* Typed mode. */ BEGIN_EXTERN_C() ZEND_COLD int zend_ini_scanner_get_lineno(void); ZEND_COLD const char *zend_ini_scanner_get_filename(void); zend_result zend_ini_open_file_for_scanning(zend_file_handle *fh, int scanner_mode); zend_result zend_ini_prepare_string_for_scanning(const char *str, int scanner_mode); int ini_lex(zval *ini_lval); void shutdown_ini_scanner(void); END_EXTERN_C() #endif /* _ZEND_INI_SCANNER_H */
1,901
49.052632
84
h
php-src
php-src-master/Zend/zend_istdiostream.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef _ZEND_STDIOSTREAM #define _ZEND_STDIOSTREAM #if defined(ZTS) && !defined(HAVE_CLASS_ISTDIOSTREAM) class istdiostream : public istream { private: stdiobuf _file; public: istdiostream (FILE* __f) : istream(), _file(__f) { init(&_file); } stdiobuf* rdbuf()/* const */ { return &_file; } }; #endif #endif
1,537
42.942857
75
h
php-src
php-src-master/Zend/zend_iterators.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Wez Furlong <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_API.h" static zend_class_entry zend_iterator_class_entry; static void iter_wrapper_free(zend_object *object); static void iter_wrapper_dtor(zend_object *object); static HashTable *iter_wrapper_get_gc(zend_object *object, zval **table, int *n); static const zend_object_handlers iterator_object_handlers = { 0, iter_wrapper_free, iter_wrapper_dtor, NULL, /* clone_obj */ NULL, /* prop read */ NULL, /* prop write */ NULL, /* read dim */ NULL, /* write dim */ NULL, /* get_property_ptr_ptr */ NULL, /* has prop */ NULL, /* unset prop */ NULL, /* has dim */ NULL, /* unset dim */ NULL, /* props get */ NULL, /* method get */ NULL, /* get ctor */ NULL, /* get class name */ NULL, /* cast */ NULL, /* count */ NULL, /* get_debug_info */ NULL, /* get_closure */ iter_wrapper_get_gc, NULL, /* do_operation */ NULL, /* compare */ NULL /* get_properties_for */ }; ZEND_API void zend_register_iterator_wrapper(void) { INIT_CLASS_ENTRY(zend_iterator_class_entry, "__iterator_wrapper", NULL); zend_iterator_class_entry.default_object_handlers = &iterator_object_handlers; } static void iter_wrapper_free(zend_object *object) { zend_object_iterator *iter = (zend_object_iterator*)object; iter->funcs->dtor(iter); } static void iter_wrapper_dtor(zend_object *object) { } static HashTable *iter_wrapper_get_gc(zend_object *object, zval **table, int *n) { zend_object_iterator *iter = (zend_object_iterator*)object; if (iter->funcs->get_gc) { return iter->funcs->get_gc(iter, table, n); } *table = NULL; *n = 0; return NULL; } ZEND_API void zend_iterator_init(zend_object_iterator *iter) { zend_object_std_init(&iter->std, &zend_iterator_class_entry); } ZEND_API void zend_iterator_dtor(zend_object_iterator *iter) { if (GC_DELREF(&iter->std) > 0) { return; } zend_objects_store_del(&iter->std); } ZEND_API zend_object_iterator* zend_iterator_unwrap(zval *array_ptr) { ZEND_ASSERT(Z_TYPE_P(array_ptr) == IS_OBJECT); if (Z_OBJ_HT_P(array_ptr) == &iterator_object_handlers) { return (zend_object_iterator *)Z_OBJ_P(array_ptr); } return NULL; }
3,344
30.556604
82
c
php-src
php-src-master/Zend/zend_iterators.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Wez Furlong <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ /* These iterators were designed to operate within the foreach() * structures provided by the engine, but could be extended for use * with other iterative engine opcodes. * These methods have similar semantics to the zend_hash API functions * with similar names. * */ typedef struct _zend_object_iterator zend_object_iterator; typedef struct _zend_object_iterator_funcs { /* release all resources associated with this iterator instance */ void (*dtor)(zend_object_iterator *iter); /* check for end of iteration (FAILURE or SUCCESS if data is valid) */ int (*valid)(zend_object_iterator *iter); /* fetch the item data for the current element */ zval *(*get_current_data)(zend_object_iterator *iter); /* fetch the key for the current element (optional, may be NULL). The key * should be written into the provided zval* using the ZVAL_* macros. If * this handler is not provided auto-incrementing integer keys will be * used. */ void (*get_current_key)(zend_object_iterator *iter, zval *key); /* step forwards to next element */ void (*move_forward)(zend_object_iterator *iter); /* rewind to start of data (optional, may be NULL) */ void (*rewind)(zend_object_iterator *iter); /* invalidate current value/key (optional, may be NULL) */ void (*invalidate_current)(zend_object_iterator *iter); /* Expose owned values to GC. * This has the same semantics as the corresponding object handler. */ HashTable *(*get_gc)(zend_object_iterator *iter, zval **table, int *n); } zend_object_iterator_funcs; struct _zend_object_iterator { zend_object std; zval data; const zend_object_iterator_funcs *funcs; zend_ulong index; /* private to fe_reset/fe_fetch opcodes */ }; typedef struct _zend_class_iterator_funcs { zend_function *zf_new_iterator; zend_function *zf_valid; zend_function *zf_current; zend_function *zf_key; zend_function *zf_next; zend_function *zf_rewind; } zend_class_iterator_funcs; typedef struct _zend_class_arrayaccess_funcs { zend_function *zf_offsetget; zend_function *zf_offsetexists; zend_function *zf_offsetset; zend_function *zf_offsetunset; } zend_class_arrayaccess_funcs; BEGIN_EXTERN_C() /* given a zval, returns stuff that can be used to iterate it. */ ZEND_API zend_object_iterator* zend_iterator_unwrap(zval *array_ptr); /* given an iterator, wrap it up as a zval for use by the engine opcodes */ ZEND_API void zend_iterator_init(zend_object_iterator *iter); ZEND_API void zend_iterator_dtor(zend_object_iterator *iter); ZEND_API void zend_register_iterator_wrapper(void); END_EXTERN_C()
3,786
40.163043
75
h
php-src
php-src-master/Zend/zend_language_scanner.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_SCANNER_H #define ZEND_SCANNER_H typedef struct _zend_lex_state { unsigned int yy_leng; unsigned char *yy_start; unsigned char *yy_text; unsigned char *yy_cursor; unsigned char *yy_marker; unsigned char *yy_limit; int yy_state; zend_stack state_stack; zend_ptr_stack heredoc_label_stack; zend_stack nest_location_stack; /* for syntax error reporting */ zend_file_handle *in; uint32_t lineno; zend_string *filename; /* original (unfiltered) script */ unsigned char *script_org; size_t script_org_size; /* filtered script */ unsigned char *script_filtered; size_t script_filtered_size; /* input/output filters */ zend_encoding_filter input_filter; zend_encoding_filter output_filter; const zend_encoding *script_encoding; /* hooks */ void (*on_event)( zend_php_scanner_event event, int token, int line, const char *text, size_t length, void *context); void *on_event_context; zend_ast *ast; zend_arena *ast_arena; } zend_lex_state; typedef struct _zend_heredoc_label { char *label; int length; int indentation; bool indentation_uses_spaces; } zend_heredoc_label; /* Track locations of unclosed {, [, (, etc. for better syntax error reporting */ typedef struct _zend_nest_location { char text; int lineno; } zend_nest_location; BEGIN_EXTERN_C() ZEND_API void zend_save_lexical_state(zend_lex_state *lex_state); ZEND_API void zend_restore_lexical_state(zend_lex_state *lex_state); ZEND_API void zend_prepare_string_for_scanning(zval *str, zend_string *filename); ZEND_API void zend_multibyte_yyinput_again(zend_encoding_filter old_input_filter, const zend_encoding *old_encoding); ZEND_API zend_result zend_multibyte_set_filter(const zend_encoding *onetime_encoding); ZEND_API zend_result zend_lex_tstring(zval *zv, unsigned char *ident); END_EXTERN_C() #endif
3,044
34.406977
117
h
php-src
php-src-master/Zend/zend_list.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_LIST_H #define ZEND_LIST_H #include "zend_hash.h" #include "zend_globals.h" BEGIN_EXTERN_C() typedef void (*rsrc_dtor_func_t)(zend_resource *res); #define ZEND_RSRC_DTOR_FUNC(name) void name(zend_resource *res) typedef struct _zend_rsrc_list_dtors_entry { rsrc_dtor_func_t list_dtor_ex; rsrc_dtor_func_t plist_dtor_ex; const char *type_name; int module_number; int resource_id; } zend_rsrc_list_dtors_entry; ZEND_API int zend_register_list_destructors_ex(rsrc_dtor_func_t ld, rsrc_dtor_func_t pld, const char *type_name, int module_number); void list_entry_destructor(zval *ptr); void plist_entry_destructor(zval *ptr); void zend_clean_module_rsrc_dtors(int module_number); ZEND_API void zend_init_rsrc_list(void); /* Exported for phar hack */ void zend_init_rsrc_plist(void); void zend_close_rsrc_list(HashTable *ht); void zend_destroy_rsrc_list(HashTable *ht); void zend_init_rsrc_list_dtors(void); void zend_destroy_rsrc_list_dtors(void); ZEND_API zval* ZEND_FASTCALL zend_list_insert(void *ptr, int type); ZEND_API void ZEND_FASTCALL zend_list_free(zend_resource *res); ZEND_API zend_result ZEND_FASTCALL zend_list_delete(zend_resource *res); ZEND_API void ZEND_FASTCALL zend_list_close(zend_resource *res); ZEND_API zend_resource *zend_register_resource(void *rsrc_pointer, int rsrc_type); ZEND_API void *zend_fetch_resource(zend_resource *res, const char *resource_type_name, int resource_type); ZEND_API void *zend_fetch_resource2(zend_resource *res, const char *resource_type_name, int resource_type, int resource_type2); ZEND_API void *zend_fetch_resource_ex(zval *res, const char *resource_type_name, int resource_type); ZEND_API void *zend_fetch_resource2_ex(zval *res, const char *resource_type_name, int resource_type, int resource_type2); ZEND_API const char *zend_rsrc_list_get_rsrc_type(zend_resource *res); ZEND_API int zend_fetch_list_dtor_id(const char *type_name); ZEND_API zend_resource* zend_register_persistent_resource(const char *key, size_t key_len, void *rsrc_pointer, int rsrc_type); ZEND_API zend_resource* zend_register_persistent_resource_ex(zend_string *key, void *rsrc_pointer, int rsrc_type); extern ZEND_API int le_index_ptr; /* list entry type for index pointers */ END_EXTERN_C() #endif
3,483
44.246753
132
h
php-src
php-src-master/Zend/zend_llist.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_llist.h" #include "zend_sort.h" ZEND_API void zend_llist_init(zend_llist *l, size_t size, llist_dtor_func_t dtor, unsigned char persistent) { l->head = NULL; l->tail = NULL; l->count = 0; l->size = size; l->dtor = dtor; l->persistent = persistent; } ZEND_API void zend_llist_add_element(zend_llist *l, const void *element) { zend_llist_element *tmp = pemalloc(sizeof(zend_llist_element)+l->size-1, l->persistent); tmp->prev = l->tail; tmp->next = NULL; if (l->tail) { l->tail->next = tmp; } else { l->head = tmp; } l->tail = tmp; memcpy(tmp->data, element, l->size); ++l->count; } ZEND_API void zend_llist_prepend_element(zend_llist *l, const void *element) { zend_llist_element *tmp = pemalloc(sizeof(zend_llist_element)+l->size-1, l->persistent); tmp->next = l->head; tmp->prev = NULL; if (l->head) { l->head->prev = tmp; } else { l->tail = tmp; } l->head = tmp; memcpy(tmp->data, element, l->size); ++l->count; } #define DEL_LLIST_ELEMENT(current, l) \ if ((current)->prev) {\ (current)->prev->next = (current)->next;\ } else {\ (l)->head = (current)->next;\ }\ if ((current)->next) {\ (current)->next->prev = (current)->prev;\ } else {\ (l)->tail = (current)->prev;\ }\ if ((l)->dtor) {\ (l)->dtor((current)->data);\ }\ pefree((current), (l)->persistent);\ --l->count; ZEND_API void zend_llist_del_element(zend_llist *l, void *element, int (*compare)(void *element1, void *element2)) { zend_llist_element *current=l->head; while (current) { if (compare(current->data, element)) { DEL_LLIST_ELEMENT(current, l); break; } current = current->next; } } ZEND_API void zend_llist_destroy(zend_llist *l) { zend_llist_element *current=l->head, *next; while (current) { next = current->next; if (l->dtor) { l->dtor(current->data); } pefree(current, l->persistent); current = next; } l->head = NULL; l->tail = NULL; l->count = 0; } ZEND_API void zend_llist_clean(zend_llist *l) { zend_llist_destroy(l); l->head = l->tail = NULL; } ZEND_API void zend_llist_remove_tail(zend_llist *l) { zend_llist_element *old_tail = l->tail; if (!old_tail) { return; } if (old_tail->prev) { old_tail->prev->next = NULL; } else { l->head = NULL; } l->tail = old_tail->prev; --l->count; if (l->dtor) { l->dtor(old_tail->data); } pefree(old_tail, l->persistent); } ZEND_API void zend_llist_copy(zend_llist *dst, zend_llist *src) { zend_llist_element *ptr; zend_llist_init(dst, src->size, src->dtor, src->persistent); ptr = src->head; while (ptr) { zend_llist_add_element(dst, ptr->data); ptr = ptr->next; } } ZEND_API void zend_llist_apply_with_del(zend_llist *l, int (*func)(void *data)) { zend_llist_element *element, *next; element=l->head; while (element) { next = element->next; if (func(element->data)) { DEL_LLIST_ELEMENT(element, l); } element = next; } } ZEND_API void zend_llist_apply(zend_llist *l, llist_apply_func_t func) { zend_llist_element *element; for (element=l->head; element; element=element->next) { func(element->data); } } static void zend_llist_swap(zend_llist_element **p, zend_llist_element **q) { zend_llist_element *t; t = *p; *p = *q; *q = t; } ZEND_API void zend_llist_sort(zend_llist *l, llist_compare_func_t comp_func) { size_t i; zend_llist_element **elements; zend_llist_element *element, **ptr; if (l->count == 0) { return; } elements = (zend_llist_element **) emalloc(l->count * sizeof(zend_llist_element *)); ptr = &elements[0]; for (element=l->head; element; element=element->next) { *ptr++ = element; } zend_sort(elements, l->count, sizeof(zend_llist_element *), (compare_func_t) comp_func, (swap_func_t) zend_llist_swap); l->head = elements[0]; elements[0]->prev = NULL; for (i = 1; i < l->count; i++) { elements[i]->prev = elements[i-1]; elements[i-1]->next = elements[i]; } elements[i-1]->next = NULL; l->tail = elements[i-1]; efree(elements); } ZEND_API void zend_llist_apply_with_argument(zend_llist *l, llist_apply_with_arg_func_t func, void *arg) { zend_llist_element *element; for (element=l->head; element; element=element->next) { func(element->data, arg); } } ZEND_API void zend_llist_apply_with_arguments(zend_llist *l, llist_apply_with_args_func_t func, int num_args, ...) { zend_llist_element *element; va_list args; va_start(args, num_args); for (element=l->head; element; element=element->next) { func(element->data, num_args, args); } va_end(args); } ZEND_API size_t zend_llist_count(zend_llist *l) { return l->count; } ZEND_API void *zend_llist_get_first_ex(zend_llist *l, zend_llist_position *pos) { zend_llist_position *current = pos ? pos : &l->traverse_ptr; *current = l->head; if (*current) { return (*current)->data; } else { return NULL; } } ZEND_API void *zend_llist_get_last_ex(zend_llist *l, zend_llist_position *pos) { zend_llist_position *current = pos ? pos : &l->traverse_ptr; *current = l->tail; if (*current) { return (*current)->data; } else { return NULL; } } ZEND_API void *zend_llist_get_next_ex(zend_llist *l, zend_llist_position *pos) { zend_llist_position *current = pos ? pos : &l->traverse_ptr; if (*current) { *current = (*current)->next; if (*current) { return (*current)->data; } } return NULL; } ZEND_API void *zend_llist_get_prev_ex(zend_llist *l, zend_llist_position *pos) { zend_llist_position *current = pos ? pos : &l->traverse_ptr; if (*current) { *current = (*current)->prev; if (*current) { return (*current)->data; } } return NULL; }
6,885
21.070513
114
c
php-src
php-src-master/Zend/zend_llist.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_LLIST_H #define ZEND_LLIST_H typedef struct _zend_llist_element { struct _zend_llist_element *next; struct _zend_llist_element *prev; char data[1]; /* Needs to always be last in the struct */ } zend_llist_element; typedef void (*llist_dtor_func_t)(void *); typedef int (*llist_compare_func_t)(const zend_llist_element **, const zend_llist_element **); typedef void (*llist_apply_with_args_func_t)(void *data, int num_args, va_list args); typedef void (*llist_apply_with_arg_func_t)(void *data, void *arg); typedef void (*llist_apply_func_t)(void *); typedef struct _zend_llist { zend_llist_element *head; zend_llist_element *tail; size_t count; size_t size; llist_dtor_func_t dtor; unsigned char persistent; zend_llist_element *traverse_ptr; } zend_llist; typedef zend_llist_element* zend_llist_position; BEGIN_EXTERN_C() ZEND_API void zend_llist_init(zend_llist *l, size_t size, llist_dtor_func_t dtor, unsigned char persistent); ZEND_API void zend_llist_add_element(zend_llist *l, const void *element); ZEND_API void zend_llist_prepend_element(zend_llist *l, const void *element); ZEND_API void zend_llist_del_element(zend_llist *l, void *element, int (*compare)(void *element1, void *element2)); ZEND_API void zend_llist_destroy(zend_llist *l); ZEND_API void zend_llist_clean(zend_llist *l); ZEND_API void zend_llist_remove_tail(zend_llist *l); ZEND_API void zend_llist_copy(zend_llist *dst, zend_llist *src); ZEND_API void zend_llist_apply(zend_llist *l, llist_apply_func_t func); ZEND_API void zend_llist_apply_with_del(zend_llist *l, int (*func)(void *data)); ZEND_API void zend_llist_apply_with_argument(zend_llist *l, llist_apply_with_arg_func_t func, void *arg); ZEND_API void zend_llist_apply_with_arguments(zend_llist *l, llist_apply_with_args_func_t func, int num_args, ...); ZEND_API size_t zend_llist_count(zend_llist *l); ZEND_API void zend_llist_sort(zend_llist *l, llist_compare_func_t comp_func); /* traversal */ ZEND_API void *zend_llist_get_first_ex(zend_llist *l, zend_llist_position *pos); ZEND_API void *zend_llist_get_last_ex(zend_llist *l, zend_llist_position *pos); ZEND_API void *zend_llist_get_next_ex(zend_llist *l, zend_llist_position *pos); ZEND_API void *zend_llist_get_prev_ex(zend_llist *l, zend_llist_position *pos); static zend_always_inline void *zend_llist_get_first(zend_llist *l) { return zend_llist_get_first_ex(l, NULL); } static zend_always_inline void *zend_llist_get_last(zend_llist *l) { return zend_llist_get_last_ex(l, NULL); } static zend_always_inline void *zend_llist_get_next(zend_llist *l) { return zend_llist_get_next_ex(l, NULL); } static zend_always_inline void *zend_llist_get_prev(zend_llist *l) { return zend_llist_get_prev_ex(l, NULL); } END_EXTERN_C() #endif /* ZEND_LLIST_H */
4,001
42.5
115
h
php-src
php-src-master/Zend/zend_long.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Anatol Belski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_LONG_H #define ZEND_LONG_H #include <inttypes.h> #include <stdint.h> /* This is the heart of the whole int64 enablement in zval. */ #if defined(__x86_64__) || defined(__LP64__) || defined(_LP64) || defined(_WIN64) # define ZEND_ENABLE_ZVAL_LONG64 1 #endif /* Integer types. */ #ifdef ZEND_ENABLE_ZVAL_LONG64 typedef int64_t zend_long; typedef uint64_t zend_ulong; typedef int64_t zend_off_t; # define ZEND_LONG_MAX INT64_MAX # define ZEND_LONG_MIN INT64_MIN # define ZEND_ULONG_MAX UINT64_MAX # define Z_L(i) INT64_C(i) # define Z_UL(i) UINT64_C(i) # define SIZEOF_ZEND_LONG 8 #else typedef int32_t zend_long; typedef uint32_t zend_ulong; typedef int32_t zend_off_t; # define ZEND_LONG_MAX INT32_MAX # define ZEND_LONG_MIN INT32_MIN # define ZEND_ULONG_MAX UINT32_MAX # define Z_L(i) INT32_C(i) # define Z_UL(i) UINT32_C(i) # define SIZEOF_ZEND_LONG 4 #endif /* Conversion macros. */ #define ZEND_LTOA_BUF_LEN 65 #ifdef ZEND_ENABLE_ZVAL_LONG64 # define ZEND_LONG_FMT "%" PRId64 # define ZEND_ULONG_FMT "%" PRIu64 # define ZEND_XLONG_FMT "%" PRIx64 # define ZEND_LONG_FMT_SPEC PRId64 # define ZEND_ULONG_FMT_SPEC PRIu64 # ifdef ZEND_WIN32 # define ZEND_LTOA(i, s, len) _i64toa_s((i), (s), (len), 10) # define ZEND_ATOL(s) _atoi64((s)) # define ZEND_STRTOL(s0, s1, base) _strtoi64((s0), (s1), (base)) # define ZEND_STRTOUL(s0, s1, base) _strtoui64((s0), (s1), (base)) # define ZEND_STRTOL_PTR _strtoi64 # define ZEND_STRTOUL_PTR _strtoui64 # define ZEND_ABS _abs64 # else # define ZEND_LTOA(i, s, len) \ do { \ int st = snprintf((s), (len), ZEND_LONG_FMT, (i)); \ (s)[st] = '\0'; \ } while (0) # define ZEND_ATOL(s) atoll((s)) # define ZEND_STRTOL(s0, s1, base) strtoll((s0), (s1), (base)) # define ZEND_STRTOUL(s0, s1, base) strtoull((s0), (s1), (base)) # define ZEND_STRTOL_PTR strtoll # define ZEND_STRTOUL_PTR strtoull # define ZEND_ABS imaxabs # endif #else # define ZEND_STRTOL(s0, s1, base) strtol((s0), (s1), (base)) # define ZEND_STRTOUL(s0, s1, base) strtoul((s0), (s1), (base)) # define ZEND_LONG_FMT "%" PRId32 # define ZEND_ULONG_FMT "%" PRIu32 # define ZEND_XLONG_FMT "%" PRIx32 # define ZEND_LONG_FMT_SPEC PRId32 # define ZEND_ULONG_FMT_SPEC PRIu32 # ifdef ZEND_WIN32 # define ZEND_LTOA(i, s, len) _ltoa_s((i), (s), (len), 10) # define ZEND_ATOL(s) atol((s)) # else # define ZEND_LTOA(i, s, len) \ do { \ int st = snprintf((s), (len), ZEND_LONG_FMT, (i)); \ (s)[st] = '\0'; \ } while (0) # define ZEND_ATOL(s) atol((s)) # endif # define ZEND_STRTOL_PTR strtol # define ZEND_STRTOUL_PTR strtoul # define ZEND_ABS abs #endif #if SIZEOF_ZEND_LONG == 4 # define MAX_LENGTH_OF_LONG 11 # define LONG_MIN_DIGITS "2147483648" #elif SIZEOF_ZEND_LONG == 8 # define MAX_LENGTH_OF_LONG 20 # define LONG_MIN_DIGITS "9223372036854775808" #else # error "Unknown SIZEOF_ZEND_LONG" #endif static const char long_min_digits[] = LONG_MIN_DIGITS; #if SIZEOF_SIZE_T == 4 # define ZEND_ADDR_FMT "0x%08zx" #elif SIZEOF_SIZE_T == 8 # define ZEND_ADDR_FMT "0x%016zx" #else # error "Unknown SIZEOF_SIZE_T" #endif #endif /* ZEND_LONG_H */
4,227
31.775194
81
h
php-src
php-src-master/Zend/zend_map_ptr.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_MAP_PTR_H #define ZEND_MAP_PTR_H #include "zend_portability.h" #define ZEND_MAP_PTR_KIND_PTR 0 #define ZEND_MAP_PTR_KIND_PTR_OR_OFFSET 1 #define ZEND_MAP_PTR_KIND ZEND_MAP_PTR_KIND_PTR_OR_OFFSET #define ZEND_MAP_PTR(ptr) \ ptr ## __ptr #define ZEND_MAP_PTR_DEF(type, name) \ type ZEND_MAP_PTR(name) #define ZEND_MAP_PTR_OFFSET2PTR(offset) \ ((void**)((char*)CG(map_ptr_base) + offset)) #define ZEND_MAP_PTR_PTR2OFFSET(ptr) \ ((void*)(((char*)(ptr)) - ((char*)CG(map_ptr_base)))) #define ZEND_MAP_PTR_INIT(ptr, val) do { \ ZEND_MAP_PTR(ptr) = (val); \ } while (0) #define ZEND_MAP_PTR_NEW(ptr) do { \ ZEND_MAP_PTR(ptr) = zend_map_ptr_new(); \ } while (0) #if ZEND_MAP_PTR_KIND == ZEND_MAP_PTR_KIND_PTR_OR_OFFSET # define ZEND_MAP_PTR_NEW_OFFSET() \ ((uint32_t)(uintptr_t)zend_map_ptr_new()) # define ZEND_MAP_PTR_IS_OFFSET(ptr) \ (((uintptr_t)ZEND_MAP_PTR(ptr)) & 1L) # define ZEND_MAP_PTR_GET(ptr) \ ((ZEND_MAP_PTR_IS_OFFSET(ptr) ? \ ZEND_MAP_PTR_GET_IMM(ptr) : \ ((void*)(ZEND_MAP_PTR(ptr))))) # define ZEND_MAP_PTR_GET_IMM(ptr) \ (*ZEND_MAP_PTR_OFFSET2PTR((uintptr_t)ZEND_MAP_PTR(ptr))) # define ZEND_MAP_PTR_SET(ptr, val) do { \ if (ZEND_MAP_PTR_IS_OFFSET(ptr)) { \ ZEND_MAP_PTR_SET_IMM(ptr, val); \ } else { \ ZEND_MAP_PTR_INIT(ptr, val); \ } \ } while (0) # define ZEND_MAP_PTR_SET_IMM(ptr, val) do { \ void **__p = ZEND_MAP_PTR_OFFSET2PTR((uintptr_t)ZEND_MAP_PTR(ptr)); \ *__p = (val); \ } while (0) # define ZEND_MAP_PTR_BIASED_BASE(real_base) \ ((void*)(((uintptr_t)(real_base)) - 1)) #else # error "Unknown ZEND_MAP_PTR_KIND" #endif BEGIN_EXTERN_C() ZEND_API void zend_map_ptr_reset(void); ZEND_API void *zend_map_ptr_new(void); ZEND_API void zend_map_ptr_extend(size_t last); ZEND_API void zend_alloc_ce_cache(zend_string *type_name); END_EXTERN_C() #endif /* ZEND_MAP_PTR_H */
3,006
35.670732
75
h
php-src
php-src-master/Zend/zend_max_execution_timer.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Kévin Dunglas <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_MAX_EXECUTION_TIMER_H #define ZEND_MAX_EXECUTION_TIMER_H # ifdef ZEND_MAX_EXECUTION_TIMERS #include "zend_long.h" /* Must be called after calls to fork() */ ZEND_API void zend_max_execution_timer_init(void); void zend_max_execution_timer_settime(zend_long seconds); void zend_max_execution_timer_shutdown(void); # else #define zend_max_execution_timer_init() #define zend_max_execution_timer_settime(seconds) #define zend_max_execution_timer_shutdown() # endif #endif
1,483
39.108108
75
h
php-src
php-src-master/Zend/zend_mmap.h
/* +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Max Kellermann <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_MMAP_H #define ZEND_MMAP_H #include "zend_portability.h" #ifdef HAVE_PRCTL # include <sys/prctl.h> /* fallback definitions if our libc is older than the kernel */ # ifndef PR_SET_VMA # define PR_SET_VMA 0x53564d41 # endif # ifndef PR_SET_VMA_ANON_NAME # define PR_SET_VMA_ANON_NAME 0 # endif #endif // HAVE_PRCTL /** * Set a name for the specified memory area. * * This feature requires Linux 5.17. */ static zend_always_inline void zend_mmap_set_name(const void *start, size_t len, const char *name) { #ifdef HAVE_PRCTL prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, (unsigned long)start, len, (unsigned long)name); #endif } #endif /* ZEND_MMAP_H */
1,512
32.622222
98
h
php-src
php-src-master/Zend/zend_modules.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef MODULES_H #define MODULES_H #include "zend.h" #include "zend_compile.h" #include "zend_build.h" #define INIT_FUNC_ARGS int type, int module_number #define INIT_FUNC_ARGS_PASSTHRU type, module_number #define SHUTDOWN_FUNC_ARGS int type, int module_number #define SHUTDOWN_FUNC_ARGS_PASSTHRU type, module_number #define ZEND_MODULE_INFO_FUNC_ARGS zend_module_entry *zend_module #define ZEND_MODULE_INFO_FUNC_ARGS_PASSTHRU zend_module #define ZEND_MODULE_API_NO 20220830 #ifdef ZTS #define USING_ZTS 1 #else #define USING_ZTS 0 #endif #define STANDARD_MODULE_HEADER_EX sizeof(zend_module_entry), ZEND_MODULE_API_NO, ZEND_DEBUG, USING_ZTS #define STANDARD_MODULE_HEADER \ STANDARD_MODULE_HEADER_EX, NULL, NULL #define ZE2_STANDARD_MODULE_HEADER \ STANDARD_MODULE_HEADER_EX, ini_entries, NULL #define ZEND_MODULE_BUILD_ID "API" ZEND_TOSTR(ZEND_MODULE_API_NO) ZEND_BUILD_TS ZEND_BUILD_DEBUG ZEND_BUILD_SYSTEM ZEND_BUILD_EXTRA #define STANDARD_MODULE_PROPERTIES_EX 0, 0, NULL, 0, ZEND_MODULE_BUILD_ID #define NO_MODULE_GLOBALS 0, NULL, NULL, NULL #ifdef ZTS # define ZEND_MODULE_GLOBALS(module_name) sizeof(zend_##module_name##_globals), &module_name##_globals_id #else # define ZEND_MODULE_GLOBALS(module_name) sizeof(zend_##module_name##_globals), &module_name##_globals #endif #define STANDARD_MODULE_PROPERTIES \ NO_MODULE_GLOBALS, NULL, STANDARD_MODULE_PROPERTIES_EX #define NO_VERSION_YET NULL #define MODULE_PERSISTENT 1 #define MODULE_TEMPORARY 2 struct _zend_ini_entry; typedef struct _zend_module_entry zend_module_entry; typedef struct _zend_module_dep zend_module_dep; struct _zend_module_entry { unsigned short size; unsigned int zend_api; unsigned char zend_debug; unsigned char zts; const struct _zend_ini_entry *ini_entry; const struct _zend_module_dep *deps; const char *name; const struct _zend_function_entry *functions; zend_result (*module_startup_func)(INIT_FUNC_ARGS); zend_result (*module_shutdown_func)(SHUTDOWN_FUNC_ARGS); zend_result (*request_startup_func)(INIT_FUNC_ARGS); zend_result (*request_shutdown_func)(SHUTDOWN_FUNC_ARGS); void (*info_func)(ZEND_MODULE_INFO_FUNC_ARGS); const char *version; size_t globals_size; #ifdef ZTS ts_rsrc_id* globals_id_ptr; #else void* globals_ptr; #endif void (*globals_ctor)(void *global); void (*globals_dtor)(void *global); zend_result (*post_deactivate_func)(void); int module_started; unsigned char type; void *handle; int module_number; const char *build_id; }; #define MODULE_DEP_REQUIRED 1 #define MODULE_DEP_CONFLICTS 2 #define MODULE_DEP_OPTIONAL 3 #define ZEND_MOD_REQUIRED_EX(name, rel, ver) { name, rel, ver, MODULE_DEP_REQUIRED }, #define ZEND_MOD_CONFLICTS_EX(name, rel, ver) { name, rel, ver, MODULE_DEP_CONFLICTS }, #define ZEND_MOD_OPTIONAL_EX(name, rel, ver) { name, rel, ver, MODULE_DEP_OPTIONAL }, #define ZEND_MOD_REQUIRED(name) ZEND_MOD_REQUIRED_EX(name, NULL, NULL) #define ZEND_MOD_CONFLICTS(name) ZEND_MOD_CONFLICTS_EX(name, NULL, NULL) #define ZEND_MOD_OPTIONAL(name) ZEND_MOD_OPTIONAL_EX(name, NULL, NULL) #define ZEND_MOD_END { NULL, NULL, NULL, 0 } struct _zend_module_dep { const char *name; /* module name */ const char *rel; /* version relationship: NULL (exists), lt|le|eq|ge|gt (to given version) */ const char *version; /* version */ unsigned char type; /* dependency type */ }; BEGIN_EXTERN_C() extern ZEND_API HashTable module_registry; void module_destructor(zend_module_entry *module); int module_registry_request_startup(zend_module_entry *module); int module_registry_unload_temp(const zend_module_entry *module); END_EXTERN_C() #endif
4,830
35.598485
131
h
php-src
php-src-master/Zend/zend_multiply.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Sascha Schumann <[email protected]> | | Ard Biesheuvel <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend_portability.h" #ifndef ZEND_MULTIPLY_H #define ZEND_MULTIPLY_H #if PHP_HAVE_BUILTIN_SMULL_OVERFLOW && SIZEOF_LONG == SIZEOF_ZEND_LONG #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ long __tmpvar; \ if (((usedval) = __builtin_smull_overflow((a), (b), &__tmpvar))) { \ (dval) = (double) (a) * (double) (b); \ } \ else (lval) = __tmpvar; \ } while (0) #elif PHP_HAVE_BUILTIN_SMULLL_OVERFLOW && SIZEOF_LONG_LONG == SIZEOF_ZEND_LONG #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ long long __tmpvar; \ if (((usedval) = __builtin_smulll_overflow((a), (b), &__tmpvar))) { \ (dval) = (double) (a) * (double) (b); \ } \ else (lval) = __tmpvar; \ } while (0) #elif (defined(__i386__) || defined(__x86_64__)) && defined(__GNUC__) #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ zend_long __tmpvar; \ __asm__ ("imul %3,%0\n" \ "adc $0,%1" \ : "=r"(__tmpvar),"=r"(usedval) \ : "0"(a), "r"(b), "1"(0)); \ if (usedval) (dval) = (double) (a) * (double) (b); \ else (lval) = __tmpvar; \ } while (0) #elif defined(__arm__) && defined(__GNUC__) #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ zend_long __tmpvar; \ __asm__("smull %0, %1, %2, %3\n" \ "sub %1, %1, %0, asr #31" \ : "=r"(__tmpvar), "=r"(usedval) \ : "r"(a), "r"(b)); \ if (usedval) (dval) = (double) (a) * (double) (b); \ else (lval) = __tmpvar; \ } while (0) #elif defined(__aarch64__) && defined(__GNUC__) #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ zend_long __tmpvar; \ __asm__("mul %0, %2, %3\n" \ "smulh %1, %2, %3\n" \ "sub %1, %1, %0, asr #63\n" \ : "=&r"(__tmpvar), "=&r"(usedval) \ : "r"(a), "r"(b)); \ if (usedval) (dval) = (double) (a) * (double) (b); \ else (lval) = __tmpvar; \ } while (0) #elif defined(ZEND_WIN32) # ifdef _M_X64 # pragma intrinsic(_mul128) # define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ __int64 __high; \ __int64 __low = _mul128((a), (b), &__high); \ if ((__low >> 63I64) == __high) { \ (usedval) = 0; \ (lval) = __low; \ } else { \ (usedval) = 1; \ (dval) = (double)(a) * (double)(b); \ } \ } while (0) # elif defined(_M_ARM64) # pragma intrinsic(__mulh) # define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ __int64 __high = __mulh((a), (b)); \ __int64 __low = (a) * (b); \ if ((__low >> 63I64) == __high) { \ (usedval) = 0; \ (lval) = __low; \ } else { \ (usedval) = 1; \ (dval) = (double)(a) * (double)(b); \ } \ } while (0) # else # define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ zend_long __lres = (a) * (b); \ long double __dres = (long double)(a) * (long double)(b); \ long double __delta = (long double) __lres - __dres; \ if ( ((usedval) = (( __dres + __delta ) != __dres))) { \ (dval) = __dres; \ } else { \ (lval) = __lres; \ } \ } while (0) # endif #elif defined(__powerpc64__) && defined(__GNUC__) #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ long __low, __high; \ __asm__("mulld %0,%2,%3\n\t" \ "mulhd %1,%2,%3\n" \ : "=&r"(__low), "=&r"(__high) \ : "r"(a), "r"(b)); \ if ((__low >> 63) != __high) { \ (dval) = (double) (a) * (double) (b); \ (usedval) = 1; \ } else { \ (lval) = __low; \ (usedval) = 0; \ } \ } while (0) #elif SIZEOF_ZEND_LONG == 4 #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ int64_t __result = (int64_t) (a) * (int64_t) (b); \ if (__result > ZEND_LONG_MAX || __result < ZEND_LONG_MIN) { \ (dval) = (double) __result; \ (usedval) = 1; \ } else { \ (lval) = (long) __result; \ (usedval) = 0; \ } \ } while (0) #else #define ZEND_SIGNED_MULTIPLY_LONG(a, b, lval, dval, usedval) do { \ long __lres = (a) * (b); \ long double __dres = (long double)(a) * (long double)(b); \ long double __delta = (long double) __lres - __dres; \ if ( ((usedval) = (( __dres + __delta ) != __dres))) { \ (dval) = __dres; \ } else { \ (lval) = __lres; \ } \ } while (0) #endif #if defined(__GNUC__) && (defined(__native_client__) || defined(i386)) static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res = nmemb; size_t m_overflow = 0; if (ZEND_CONST_COND(offset == 0, 0)) { __asm__ ("mull %3\n\tadcl $0,%1" : "=&a"(res), "=&d" (m_overflow) : "%0"(res), "rm"(size)); } else { __asm__ ("mull %3\n\taddl %4,%0\n\tadcl $0,%1" : "=&a"(res), "=&d" (m_overflow) : "%0"(res), "rm"(size), "rm"(offset)); } if (UNEXPECTED(m_overflow)) { *overflow = 1; return 0; } *overflow = 0; return res; } #elif defined(__GNUC__) && defined(__x86_64__) static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res = nmemb; zend_ulong m_overflow = 0; #ifdef __ILP32__ /* x32 */ # define LP_SUFF "l" #else /* amd64 */ # define LP_SUFF "q" #endif if (ZEND_CONST_COND(offset == 0, 0)) { __asm__ ("mul" LP_SUFF " %3\n\t" "adc $0,%1" : "=&a"(res), "=&d" (m_overflow) : "%0"(res), "rm"(size)); } else { __asm__ ("mul" LP_SUFF " %3\n\t" "add %4,%0\n\t" "adc $0,%1" : "=&a"(res), "=&d" (m_overflow) : "%0"(res), "rm"(size), "rm"(offset)); } #undef LP_SUFF if (UNEXPECTED(m_overflow)) { *overflow = 1; return 0; } *overflow = 0; return res; } #elif defined(__GNUC__) && defined(__arm__) static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res; zend_ulong m_overflow; __asm__ ("umlal %0,%1,%2,%3" : "=r"(res), "=r"(m_overflow) : "r"(nmemb), "r"(size), "0"(offset), "1"(0)); if (UNEXPECTED(m_overflow)) { *overflow = 1; return 0; } *overflow = 0; return res; } #elif defined(__GNUC__) && defined(__aarch64__) static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res; zend_ulong m_overflow; __asm__ ("mul %0,%2,%3\n\tumulh %1,%2,%3\n\tadds %0,%0,%4\n\tadc %1,%1,xzr" : "=&r"(res), "=&r"(m_overflow) : "r"(nmemb), "r"(size), "r"(offset)); if (UNEXPECTED(m_overflow)) { *overflow = 1; return 0; } *overflow = 0; return res; } #elif defined(__GNUC__) && defined(__powerpc64__) static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res; unsigned long m_overflow; __asm__ ("mulld %0,%2,%3\n\t" "mulhdu %1,%2,%3\n\t" "addc %0,%0,%4\n\t" "addze %1,%1\n" : "=&r"(res), "=&r"(m_overflow) : "r"(nmemb), "r"(size), "r"(offset)); if (UNEXPECTED(m_overflow)) { *overflow = 1; return 0; } *overflow = 0; return res; } #elif SIZEOF_SIZE_T == 4 static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { uint64_t res = (uint64_t) nmemb * (uint64_t) size + (uint64_t) offset; if (UNEXPECTED(res > UINT64_C(0xFFFFFFFF))) { *overflow = 1; return 0; } *overflow = 0; return (size_t) res; } #else static zend_always_inline size_t zend_safe_address(size_t nmemb, size_t size, size_t offset, bool *overflow) { size_t res = nmemb * size + offset; double _d = (double)nmemb * (double)size + (double)offset; double _delta = (double)res - _d; if (UNEXPECTED((_d + _delta ) != _d)) { *overflow = 1; return 0; } *overflow = 0; return res; } #endif static zend_always_inline size_t zend_safe_address_guarded(size_t nmemb, size_t size, size_t offset) { bool overflow; size_t ret = zend_safe_address(nmemb, size, offset, &overflow); if (UNEXPECTED(overflow)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", nmemb, size, offset); return 0; } return ret; } /* A bit more generic version of the same */ static zend_always_inline size_t zend_safe_addmult(size_t nmemb, size_t size, size_t offset, const char *message) { bool overflow; size_t ret = zend_safe_address(nmemb, size, offset, &overflow); if (UNEXPECTED(overflow)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in %s (%zu * %zu + %zu)", message, nmemb, size, offset); return 0; } return ret; } #endif /* ZEND_MULTIPLY_H */
10,208
27.596639
120
h
php-src
php-src-master/Zend/zend_objects.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_globals.h" #include "zend_variables.h" #include "zend_API.h" #include "zend_interfaces.h" #include "zend_exceptions.h" #include "zend_weakrefs.h" static zend_always_inline void _zend_object_std_init(zend_object *object, zend_class_entry *ce) { GC_SET_REFCOUNT(object, 1); GC_TYPE_INFO(object) = GC_OBJECT; object->ce = ce; object->handlers = ce->default_object_handlers; object->properties = NULL; zend_objects_store_put(object); if (UNEXPECTED(ce->ce_flags & ZEND_ACC_USE_GUARDS)) { ZVAL_UNDEF(object->properties_table + object->ce->default_properties_count); } } ZEND_API void ZEND_FASTCALL zend_object_std_init(zend_object *object, zend_class_entry *ce) { _zend_object_std_init(object, ce); } ZEND_API void zend_object_std_dtor(zend_object *object) { zval *p, *end; if (object->properties) { if (EXPECTED(!(GC_FLAGS(object->properties) & IS_ARRAY_IMMUTABLE))) { if (EXPECTED(GC_DELREF(object->properties) == 0) && EXPECTED(GC_TYPE(object->properties) != IS_NULL)) { zend_array_destroy(object->properties); } } } p = object->properties_table; if (EXPECTED(object->ce->default_properties_count)) { end = p + object->ce->default_properties_count; do { if (Z_REFCOUNTED_P(p)) { if (UNEXPECTED(Z_ISREF_P(p)) && (ZEND_DEBUG || ZEND_REF_HAS_TYPE_SOURCES(Z_REF_P(p)))) { zend_property_info *prop_info = zend_get_property_info_for_slot(object, p); if (ZEND_TYPE_IS_SET(prop_info->type)) { ZEND_REF_DEL_TYPE_SOURCE(Z_REF_P(p), prop_info); } } i_zval_ptr_dtor(p); } p++; } while (p != end); } if (UNEXPECTED(object->ce->ce_flags & ZEND_ACC_USE_GUARDS)) { if (EXPECTED(Z_TYPE_P(p) == IS_STRING)) { zval_ptr_dtor_str(p); } else if (Z_TYPE_P(p) == IS_ARRAY) { HashTable *guards; guards = Z_ARRVAL_P(p); ZEND_ASSERT(guards != NULL); zend_hash_destroy(guards); FREE_HASHTABLE(guards); } } if (UNEXPECTED(GC_FLAGS(object) & IS_OBJ_WEAKLY_REFERENCED)) { zend_weakrefs_notify(object); } } ZEND_API void zend_objects_destroy_object(zend_object *object) { zend_function *destructor = object->ce->destructor; if (destructor) { zend_object *old_exception; const zend_op *old_opline_before_exception; if (destructor->op_array.fn_flags & (ZEND_ACC_PRIVATE|ZEND_ACC_PROTECTED)) { if (destructor->op_array.fn_flags & ZEND_ACC_PRIVATE) { /* Ensure that if we're calling a private function, we're allowed to do so. */ if (EG(current_execute_data)) { zend_class_entry *scope = zend_get_executed_scope(); if (object->ce != scope) { zend_throw_error(NULL, "Call to private %s::__destruct() from %s%s", ZSTR_VAL(object->ce->name), scope ? "scope " : "global scope", scope ? ZSTR_VAL(scope->name) : "" ); return; } } else { zend_error(E_WARNING, "Call to private %s::__destruct() from global scope during shutdown ignored", ZSTR_VAL(object->ce->name)); return; } } else { /* Ensure that if we're calling a protected function, we're allowed to do so. */ if (EG(current_execute_data)) { zend_class_entry *scope = zend_get_executed_scope(); if (!zend_check_protected(zend_get_function_root_class(destructor), scope)) { zend_throw_error(NULL, "Call to protected %s::__destruct() from %s%s", ZSTR_VAL(object->ce->name), scope ? "scope " : "global scope", scope ? ZSTR_VAL(scope->name) : "" ); return; } } else { zend_error(E_WARNING, "Call to protected %s::__destruct() from global scope during shutdown ignored", ZSTR_VAL(object->ce->name)); return; } } } GC_ADDREF(object); /* Make sure that destructors are protected from previously thrown exceptions. * For example, if an exception was thrown in a function and when the function's * local variable destruction results in a destructor being called. */ old_exception = NULL; if (EG(exception)) { if (EG(exception) == object) { zend_error_noreturn(E_CORE_ERROR, "Attempt to destruct pending exception"); } else { if (EG(current_execute_data) && EG(current_execute_data)->func && ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) { zend_rethrow_exception(EG(current_execute_data)); } old_exception = EG(exception); old_opline_before_exception = EG(opline_before_exception); EG(exception) = NULL; } } zend_call_known_instance_method_with_0_params(destructor, object, NULL); if (old_exception) { EG(opline_before_exception) = old_opline_before_exception; if (EG(exception)) { zend_exception_set_previous(EG(exception), old_exception); } else { EG(exception) = old_exception; } } OBJ_RELEASE(object); } } ZEND_API zend_object* ZEND_FASTCALL zend_objects_new(zend_class_entry *ce) { zend_object *object = emalloc(sizeof(zend_object) + zend_object_properties_size(ce)); _zend_object_std_init(object, ce); return object; } ZEND_API void ZEND_FASTCALL zend_objects_clone_members(zend_object *new_object, zend_object *old_object) { bool has_clone_method = old_object->ce->clone != NULL; if (old_object->ce->default_properties_count) { zval *src = old_object->properties_table; zval *dst = new_object->properties_table; zval *end = src + old_object->ce->default_properties_count; do { i_zval_ptr_dtor(dst); ZVAL_COPY_VALUE_PROP(dst, src); zval_add_ref(dst); if (has_clone_method) { /* Unconditionally add the IS_PROP_REINITABLE flag to avoid a potential cache miss of property_info */ Z_PROP_FLAG_P(dst) |= IS_PROP_REINITABLE; } if (UNEXPECTED(Z_ISREF_P(dst)) && (ZEND_DEBUG || ZEND_REF_HAS_TYPE_SOURCES(Z_REF_P(dst)))) { zend_property_info *prop_info = zend_get_property_info_for_slot(new_object, dst); if (ZEND_TYPE_IS_SET(prop_info->type)) { ZEND_REF_ADD_TYPE_SOURCE(Z_REF_P(dst), prop_info); } } src++; dst++; } while (src != end); } else if (old_object->properties && !has_clone_method) { /* fast copy */ if (EXPECTED(old_object->handlers == &std_object_handlers)) { if (EXPECTED(!(GC_FLAGS(old_object->properties) & IS_ARRAY_IMMUTABLE))) { GC_ADDREF(old_object->properties); } new_object->properties = old_object->properties; return; } } if (old_object->properties && EXPECTED(zend_hash_num_elements(old_object->properties))) { zval *prop, new_prop; zend_ulong num_key; zend_string *key; if (!new_object->properties) { new_object->properties = zend_new_array(zend_hash_num_elements(old_object->properties)); zend_hash_real_init_mixed(new_object->properties); } else { zend_hash_extend(new_object->properties, new_object->properties->nNumUsed + zend_hash_num_elements(old_object->properties), 0); } HT_FLAGS(new_object->properties) |= HT_FLAGS(old_object->properties) & HASH_FLAG_HAS_EMPTY_IND; ZEND_HASH_MAP_FOREACH_KEY_VAL(old_object->properties, num_key, key, prop) { if (Z_TYPE_P(prop) == IS_INDIRECT) { ZVAL_INDIRECT(&new_prop, new_object->properties_table + (Z_INDIRECT_P(prop) - old_object->properties_table)); } else { ZVAL_COPY_VALUE(&new_prop, prop); zval_add_ref(&new_prop); } if (has_clone_method) { /* Unconditionally add the IS_PROP_REINITABLE flag to avoid a potential cache miss of property_info */ Z_PROP_FLAG_P(&new_prop) |= IS_PROP_REINITABLE; } if (EXPECTED(key)) { _zend_hash_append(new_object->properties, key, &new_prop); } else { zend_hash_index_add_new(new_object->properties, num_key, &new_prop); } } ZEND_HASH_FOREACH_END(); } if (has_clone_method) { GC_ADDREF(new_object); zend_call_known_instance_method_with_0_params(new_object->ce->clone, new_object, NULL); if (ZEND_CLASS_HAS_READONLY_PROPS(new_object->ce)) { for (uint32_t i = 0; i < new_object->ce->default_properties_count; i++) { zval* prop = OBJ_PROP_NUM(new_object, i); /* Unconditionally remove the IS_PROP_REINITABLE flag to avoid a potential cache miss of property_info */ Z_PROP_FLAG_P(prop) &= ~IS_PROP_REINITABLE; } } OBJ_RELEASE(new_object); } } ZEND_API zend_object *zend_objects_clone_obj(zend_object *old_object) { zend_object *new_object; /* assume that create isn't overwritten, so when clone depends on the * overwritten one then it must itself be overwritten */ new_object = zend_objects_new(old_object->ce); /* zend_objects_clone_members() expect the properties to be initialized. */ if (new_object->ce->default_properties_count) { zval *p = new_object->properties_table; zval *end = p + new_object->ce->default_properties_count; do { ZVAL_UNDEF(p); p++; } while (p != end); } zend_objects_clone_members(new_object, old_object); return new_object; }
10,122
32.190164
130
c
php-src
php-src-master/Zend/zend_objects.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_OBJECTS_H #define ZEND_OBJECTS_H #include "zend.h" BEGIN_EXTERN_C() ZEND_API void ZEND_FASTCALL zend_object_std_init(zend_object *object, zend_class_entry *ce); ZEND_API zend_object* ZEND_FASTCALL zend_objects_new(zend_class_entry *ce); ZEND_API void ZEND_FASTCALL zend_objects_clone_members(zend_object *new_object, zend_object *old_object); ZEND_API void zend_object_std_dtor(zend_object *object); ZEND_API void zend_objects_destroy_object(zend_object *object); ZEND_API zend_object *zend_objects_clone_obj(zend_object *object); END_EXTERN_C() #endif /* ZEND_OBJECTS_H */
1,814
49.416667
105
h
php-src
php-src-master/Zend/zend_objects_API.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_globals.h" #include "zend_variables.h" #include "zend_API.h" #include "zend_objects_API.h" #include "zend_fibers.h" ZEND_API void ZEND_FASTCALL zend_objects_store_init(zend_objects_store *objects, uint32_t init_size) { objects->object_buckets = (zend_object **) emalloc(init_size * sizeof(zend_object*)); objects->top = 1; /* Skip 0 so that handles are true */ objects->size = init_size; objects->free_list_head = -1; memset(&objects->object_buckets[0], 0, sizeof(zend_object*)); } ZEND_API void ZEND_FASTCALL zend_objects_store_destroy(zend_objects_store *objects) { efree(objects->object_buckets); objects->object_buckets = NULL; } ZEND_API void ZEND_FASTCALL zend_objects_store_call_destructors(zend_objects_store *objects) { EG(flags) |= EG_FLAGS_OBJECT_STORE_NO_REUSE; if (objects->top > 1) { zend_fiber_switch_block(); uint32_t i; for (i = 1; i < objects->top; i++) { zend_object *obj = objects->object_buckets[i]; if (IS_OBJ_VALID(obj)) { if (!(OBJ_FLAGS(obj) & IS_OBJ_DESTRUCTOR_CALLED)) { GC_ADD_FLAGS(obj, IS_OBJ_DESTRUCTOR_CALLED); if (obj->handlers->dtor_obj != zend_objects_destroy_object || obj->ce->destructor) { GC_ADDREF(obj); obj->handlers->dtor_obj(obj); GC_DELREF(obj); } } } } zend_fiber_switch_unblock(); } } ZEND_API void ZEND_FASTCALL zend_objects_store_mark_destructed(zend_objects_store *objects) { if (objects->object_buckets && objects->top > 1) { zend_object **obj_ptr = objects->object_buckets + 1; zend_object **end = objects->object_buckets + objects->top; do { zend_object *obj = *obj_ptr; if (IS_OBJ_VALID(obj)) { GC_ADD_FLAGS(obj, IS_OBJ_DESTRUCTOR_CALLED); } obj_ptr++; } while (obj_ptr != end); } } ZEND_API void ZEND_FASTCALL zend_objects_store_free_object_storage(zend_objects_store *objects, bool fast_shutdown) { zend_object **obj_ptr, **end, *obj; if (objects->top <= 1) { return; } /* Free object contents, but don't free objects themselves, so they show up as leaks. * Also add a ref to all objects, so the object can't be freed by something else later. */ end = objects->object_buckets + 1; obj_ptr = objects->object_buckets + objects->top; if (fast_shutdown) { do { obj_ptr--; obj = *obj_ptr; if (IS_OBJ_VALID(obj)) { if (!(OBJ_FLAGS(obj) & IS_OBJ_FREE_CALLED)) { GC_ADD_FLAGS(obj, IS_OBJ_FREE_CALLED); if (obj->handlers->free_obj != zend_object_std_dtor) { GC_ADDREF(obj); obj->handlers->free_obj(obj); } } } } while (obj_ptr != end); } else { do { obj_ptr--; obj = *obj_ptr; if (IS_OBJ_VALID(obj)) { if (!(OBJ_FLAGS(obj) & IS_OBJ_FREE_CALLED)) { GC_ADD_FLAGS(obj, IS_OBJ_FREE_CALLED); GC_ADDREF(obj); obj->handlers->free_obj(obj); } } } while (obj_ptr != end); } } /* Store objects API */ static ZEND_COLD zend_never_inline void ZEND_FASTCALL zend_objects_store_put_cold(zend_object *object) { int handle; uint32_t new_size = 2 * EG(objects_store).size; EG(objects_store).object_buckets = (zend_object **) erealloc(EG(objects_store).object_buckets, new_size * sizeof(zend_object*)); /* Assign size after realloc, in case it fails */ EG(objects_store).size = new_size; handle = EG(objects_store).top++; object->handle = handle; EG(objects_store).object_buckets[handle] = object; } ZEND_API void ZEND_FASTCALL zend_objects_store_put(zend_object *object) { int handle; /* When in shutdown sequence - do not reuse previously freed handles, to make sure * the dtors for newly created objects are called in zend_objects_store_call_destructors() loop */ if (EG(objects_store).free_list_head != -1 && EXPECTED(!(EG(flags) & EG_FLAGS_OBJECT_STORE_NO_REUSE))) { handle = EG(objects_store).free_list_head; EG(objects_store).free_list_head = GET_OBJ_BUCKET_NUMBER(EG(objects_store).object_buckets[handle]); } else if (UNEXPECTED(EG(objects_store).top == EG(objects_store).size)) { zend_objects_store_put_cold(object); return; } else { handle = EG(objects_store).top++; } object->handle = handle; EG(objects_store).object_buckets[handle] = object; } ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object) /* {{{ */ { ZEND_ASSERT(GC_REFCOUNT(object) == 0); /* GC might have released this object already. */ if (UNEXPECTED(GC_TYPE(object) == IS_NULL)) { return; } /* Make sure we hold a reference count during the destructor call otherwise, when the destructor ends the storage might be freed when the refcount reaches 0 a second time */ if (!(OBJ_FLAGS(object) & IS_OBJ_DESTRUCTOR_CALLED)) { GC_ADD_FLAGS(object, IS_OBJ_DESTRUCTOR_CALLED); if (object->handlers->dtor_obj != zend_objects_destroy_object || object->ce->destructor) { zend_fiber_switch_block(); GC_SET_REFCOUNT(object, 1); object->handlers->dtor_obj(object); GC_DELREF(object); zend_fiber_switch_unblock(); } } if (GC_REFCOUNT(object) == 0) { uint32_t handle = object->handle; void *ptr; ZEND_ASSERT(EG(objects_store).object_buckets != NULL); ZEND_ASSERT(IS_OBJ_VALID(EG(objects_store).object_buckets[handle])); EG(objects_store).object_buckets[handle] = SET_OBJ_INVALID(object); if (!(OBJ_FLAGS(object) & IS_OBJ_FREE_CALLED)) { GC_ADD_FLAGS(object, IS_OBJ_FREE_CALLED); GC_SET_REFCOUNT(object, 1); object->handlers->free_obj(object); } ptr = ((char*)object) - object->handlers->offset; GC_REMOVE_FROM_BUFFER(object); efree(ptr); ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(handle); } } /* }}} */
6,868
31.866029
129
c
php-src
php-src-master/Zend/zend_objects_API.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_OBJECTS_API_H #define ZEND_OBJECTS_API_H #include "zend.h" #include "zend_compile.h" #define OBJ_BUCKET_INVALID (1<<0) #define IS_OBJ_VALID(o) (!(((uintptr_t)(o)) & OBJ_BUCKET_INVALID)) #define SET_OBJ_INVALID(o) ((zend_object*)((((uintptr_t)(o)) | OBJ_BUCKET_INVALID))) #define GET_OBJ_BUCKET_NUMBER(o) (((intptr_t)(o)) >> 1) #define SET_OBJ_BUCKET_NUMBER(o, n) do { \ (o) = (zend_object*)((((uintptr_t)(n)) << 1) | OBJ_BUCKET_INVALID); \ } while (0) #define ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(h) do { \ SET_OBJ_BUCKET_NUMBER(EG(objects_store).object_buckets[(h)], EG(objects_store).free_list_head); \ EG(objects_store).free_list_head = (h); \ } while (0) #define OBJ_RELEASE(obj) zend_object_release(obj) typedef struct _zend_objects_store { zend_object **object_buckets; uint32_t top; uint32_t size; int free_list_head; } zend_objects_store; /* Global store handling functions */ BEGIN_EXTERN_C() ZEND_API void ZEND_FASTCALL zend_objects_store_init(zend_objects_store *objects, uint32_t init_size); ZEND_API void ZEND_FASTCALL zend_objects_store_call_destructors(zend_objects_store *objects); ZEND_API void ZEND_FASTCALL zend_objects_store_mark_destructed(zend_objects_store *objects); ZEND_API void ZEND_FASTCALL zend_objects_store_free_object_storage(zend_objects_store *objects, bool fast_shutdown); ZEND_API void ZEND_FASTCALL zend_objects_store_destroy(zend_objects_store *objects); /* Store API functions */ ZEND_API void ZEND_FASTCALL zend_objects_store_put(zend_object *object); ZEND_API void ZEND_FASTCALL zend_objects_store_del(zend_object *object); /* Called when the ctor was terminated by an exception */ static zend_always_inline void zend_object_store_ctor_failed(zend_object *obj) { GC_ADD_FLAGS(obj, IS_OBJ_DESTRUCTOR_CALLED); } END_EXTERN_C() static zend_always_inline void zend_object_release(zend_object *obj) { if (GC_DELREF(obj) == 0) { zend_objects_store_del(obj); } else if (UNEXPECTED(GC_MAY_LEAK((zend_refcounted*)obj))) { gc_possible_root((zend_refcounted*)obj); } } static zend_always_inline size_t zend_object_properties_size(zend_class_entry *ce) { return sizeof(zval) * (ce->default_properties_count - ((ce->ce_flags & ZEND_ACC_USE_GUARDS) ? 0 : 1)); } /* Allocates object type and zeros it, but not the standard zend_object and properties. * Standard object MUST be initialized using zend_object_std_init(). * Properties MUST be initialized using object_properties_init(). */ static zend_always_inline void *zend_object_alloc(size_t obj_size, zend_class_entry *ce) { void *obj = emalloc(obj_size + zend_object_properties_size(ce)); memset(obj, 0, obj_size - sizeof(zend_object)); return obj; } static inline zend_property_info *zend_get_property_info_for_slot(zend_object *obj, zval *slot) { zend_property_info **table = obj->ce->properties_info_table; intptr_t prop_num = slot - obj->properties_table; ZEND_ASSERT(prop_num >= 0 && prop_num < obj->ce->default_properties_count); return table[prop_num]; } /* Helper for cases where we're only interested in property info of typed properties. */ static inline zend_property_info *zend_get_typed_property_info_for_slot(zend_object *obj, zval *slot) { zend_property_info *prop_info = zend_get_property_info_for_slot(obj, slot); if (prop_info && ZEND_TYPE_IS_SET(prop_info->type)) { return prop_info; } return NULL; } #endif /* ZEND_OBJECTS_H */
4,631
38.589744
116
h
php-src
php-src-master/Zend/zend_ptr_stack.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_ptr_stack.h" #include <stdarg.h> ZEND_API void zend_ptr_stack_init_ex(zend_ptr_stack *stack, bool persistent) { stack->top_element = stack->elements = NULL; stack->top = stack->max = 0; stack->persistent = persistent; } ZEND_API void zend_ptr_stack_init(zend_ptr_stack *stack) { zend_ptr_stack_init_ex(stack, 0); } ZEND_API void zend_ptr_stack_n_push(zend_ptr_stack *stack, int count, ...) { va_list ptr; void *elem; ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, count) va_start(ptr, count); while (count>0) { elem = va_arg(ptr, void *); stack->top++; *(stack->top_element++) = elem; count--; } va_end(ptr); } ZEND_API void zend_ptr_stack_n_pop(zend_ptr_stack *stack, int count, ...) { va_list ptr; void **elem; va_start(ptr, count); while (count>0) { elem = va_arg(ptr, void **); *elem = *(--stack->top_element); stack->top--; count--; } va_end(ptr); } ZEND_API void zend_ptr_stack_destroy(zend_ptr_stack *stack) { if (stack->elements) { pefree(stack->elements, stack->persistent); } } ZEND_API void zend_ptr_stack_apply(zend_ptr_stack *stack, void (*func)(void *)) { int i = stack->top; while (--i >= 0) { func(stack->elements[i]); } } ZEND_API void zend_ptr_stack_reverse_apply(zend_ptr_stack *stack, void (*func)(void *)) { int i = 0; while (i < stack->top) { func(stack->elements[i++]); } } ZEND_API void zend_ptr_stack_clean(zend_ptr_stack *stack, void (*func)(void *), bool free_elements) { zend_ptr_stack_apply(stack, func); if (free_elements) { int i = stack->top; while (--i >= 0) { pefree(stack->elements[i], stack->persistent); } } stack->top = 0; stack->top_element = stack->elements; } ZEND_API int zend_ptr_stack_num_elements(zend_ptr_stack *stack) { return stack->top; }
3,020
24.601695
99
c
php-src
php-src-master/Zend/zend_ptr_stack.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_PTR_STACK_H #define ZEND_PTR_STACK_H typedef struct _zend_ptr_stack { int top, max; void **elements; void **top_element; bool persistent; } zend_ptr_stack; #define PTR_STACK_BLOCK_SIZE 64 BEGIN_EXTERN_C() ZEND_API void zend_ptr_stack_init(zend_ptr_stack *stack); ZEND_API void zend_ptr_stack_init_ex(zend_ptr_stack *stack, bool persistent); ZEND_API void zend_ptr_stack_n_push(zend_ptr_stack *stack, int count, ...); ZEND_API void zend_ptr_stack_n_pop(zend_ptr_stack *stack, int count, ...); ZEND_API void zend_ptr_stack_destroy(zend_ptr_stack *stack); ZEND_API void zend_ptr_stack_apply(zend_ptr_stack *stack, void (*func)(void *)); ZEND_API void zend_ptr_stack_reverse_apply(zend_ptr_stack *stack, void (*func)(void *)); ZEND_API void zend_ptr_stack_clean(zend_ptr_stack *stack, void (*func)(void *), bool free_elements); ZEND_API int zend_ptr_stack_num_elements(zend_ptr_stack *stack); END_EXTERN_C() #define ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, count) \ if (stack->top+count > stack->max) { \ /* we need to allocate more memory */ \ do { \ stack->max += PTR_STACK_BLOCK_SIZE; \ } while (stack->top+count > stack->max); \ stack->elements = (void **) safe_perealloc(stack->elements, sizeof(void *), (stack->max), 0, stack->persistent); \ stack->top_element = stack->elements+stack->top; \ } /* Not doing this with a macro because of the loop unrolling in the element assignment. Just using a macro for 3 in the body for readability sake. */ static zend_always_inline void zend_ptr_stack_3_push(zend_ptr_stack *stack, void *a, void *b, void *c) { #define ZEND_PTR_STACK_NUM_ARGS 3 ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, ZEND_PTR_STACK_NUM_ARGS) stack->top += ZEND_PTR_STACK_NUM_ARGS; *(stack->top_element++) = a; *(stack->top_element++) = b; *(stack->top_element++) = c; #undef ZEND_PTR_STACK_NUM_ARGS } static zend_always_inline void zend_ptr_stack_2_push(zend_ptr_stack *stack, void *a, void *b) { #define ZEND_PTR_STACK_NUM_ARGS 2 ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, ZEND_PTR_STACK_NUM_ARGS) stack->top += ZEND_PTR_STACK_NUM_ARGS; *(stack->top_element++) = a; *(stack->top_element++) = b; #undef ZEND_PTR_STACK_NUM_ARGS } static zend_always_inline void zend_ptr_stack_3_pop(zend_ptr_stack *stack, void **a, void **b, void **c) { *a = *(--stack->top_element); *b = *(--stack->top_element); *c = *(--stack->top_element); stack->top -= 3; } static zend_always_inline void zend_ptr_stack_2_pop(zend_ptr_stack *stack, void **a, void **b) { *a = *(--stack->top_element); *b = *(--stack->top_element); stack->top -= 2; } static zend_always_inline void zend_ptr_stack_push(zend_ptr_stack *stack, void *ptr) { ZEND_PTR_STACK_RESIZE_IF_NEEDED(stack, 1) stack->top++; *(stack->top_element++) = ptr; } static zend_always_inline void *zend_ptr_stack_pop(zend_ptr_stack *stack) { stack->top--; return *(--stack->top_element); } static zend_always_inline void *zend_ptr_stack_top(zend_ptr_stack *stack) { return stack->elements[stack->top - 1]; } #endif /* ZEND_PTR_STACK_H */
4,296
35.109244
116
h
php-src
php-src-master/Zend/zend_range_check.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Anatol Belski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_RANGE_CHECK_H #define ZEND_RANGE_CHECK_H #include "zend_long.h" /* Flag macros for basic range recognition. Notable is that always sizeof(signed) == sizeof(unsigned), so no need to overcomplicate things. */ #if SIZEOF_INT < SIZEOF_ZEND_LONG # define ZEND_LONG_CAN_OVFL_INT 1 # define ZEND_LONG_CAN_OVFL_UINT 1 #endif #if SIZEOF_INT < SIZEOF_SIZE_T /* size_t can always overflow signed int on the same platform. Furthermore, by the current design, size_t can always overflow zend_long. */ # define ZEND_SIZE_T_CAN_OVFL_UINT 1 #endif /* zend_long vs. (unsigned) int checks. */ #ifdef ZEND_LONG_CAN_OVFL_INT # define ZEND_LONG_INT_OVFL(zlong) UNEXPECTED((zlong) > (zend_long)INT_MAX) # define ZEND_LONG_INT_UDFL(zlong) UNEXPECTED((zlong) < (zend_long)INT_MIN) # define ZEND_LONG_EXCEEDS_INT(zlong) UNEXPECTED(ZEND_LONG_INT_OVFL(zlong) || ZEND_LONG_INT_UDFL(zlong)) # define ZEND_LONG_UINT_OVFL(zlong) UNEXPECTED((zlong) < 0 || (zlong) > (zend_long)UINT_MAX) #else # define ZEND_LONG_INT_OVFL(zl) (0) # define ZEND_LONG_INT_UDFL(zl) (0) # define ZEND_LONG_EXCEEDS_INT(zlong) (0) # define ZEND_LONG_UINT_OVFL(zl) (0) #endif /* size_t vs (unsigned) int checks. */ #define ZEND_SIZE_T_INT_OVFL(size) UNEXPECTED((size) > (size_t)INT_MAX) #ifdef ZEND_SIZE_T_CAN_OVFL_UINT # define ZEND_SIZE_T_UINT_OVFL(size) UNEXPECTED((size) > (size_t)UINT_MAX) #else # define ZEND_SIZE_T_UINT_OVFL(size) (0) #endif /* Comparison zend_long vs size_t */ #define ZEND_SIZE_T_GT_ZEND_LONG(size, zlong) ((zlong) < 0 || (size) > (size_t)(zlong)) #define ZEND_SIZE_T_GTE_ZEND_LONG(size, zlong) ((zlong) < 0 || (size) >= (size_t)(zlong)) #define ZEND_SIZE_T_LT_ZEND_LONG(size, zlong) ((zlong) >= 0 && (size) < (size_t)(zlong)) #define ZEND_SIZE_T_LTE_ZEND_LONG(size, zlong) ((zlong) >= 0 && (size) <= (size_t)(zlong)) #endif /* ZEND_RANGE_CHECK_H */
3,000
43.132353
104
h
php-src
php-src-master/Zend/zend_smart_str.c
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include <zend.h> #include "zend_smart_str.h" #include "zend_smart_string.h" #define SMART_STR_OVERHEAD (ZEND_MM_OVERHEAD + _ZSTR_HEADER_SIZE + 1) #define SMART_STR_START_SIZE 256 #define SMART_STR_START_LEN (SMART_STR_START_SIZE - SMART_STR_OVERHEAD) #define SMART_STR_PAGE 4096 #define SMART_STR_NEW_LEN(len) \ (ZEND_MM_ALIGNED_SIZE_EX(len + SMART_STR_OVERHEAD, SMART_STR_PAGE) - SMART_STR_OVERHEAD) ZEND_API void ZEND_FASTCALL smart_str_erealloc(smart_str *str, size_t len) { if (UNEXPECTED(!str->s)) { str->a = len <= SMART_STR_START_LEN ? SMART_STR_START_LEN : SMART_STR_NEW_LEN(len); str->s = zend_string_alloc(str->a, 0); ZSTR_LEN(str->s) = 0; } else { str->a = SMART_STR_NEW_LEN(len); str->s = (zend_string *) erealloc2(str->s, str->a + _ZSTR_HEADER_SIZE + 1, _ZSTR_HEADER_SIZE + ZSTR_LEN(str->s)); } } ZEND_API void ZEND_FASTCALL smart_str_realloc(smart_str *str, size_t len) { if (UNEXPECTED(!str->s)) { str->a = len <= SMART_STR_START_LEN ? SMART_STR_START_LEN : SMART_STR_NEW_LEN(len); str->s = zend_string_alloc(str->a, 1); ZSTR_LEN(str->s) = 0; } else { str->a = SMART_STR_NEW_LEN(len); str->s = (zend_string *) perealloc(str->s, str->a + _ZSTR_HEADER_SIZE + 1, 1); } } /* Windows uses VK_ESCAPE instead of \e */ #ifndef VK_ESCAPE #define VK_ESCAPE '\e' #endif static size_t zend_compute_escaped_string_len(const char *s, size_t l) { size_t i, len = l; for (i = 0; i < l; ++i) { char c = s[i]; if (c == '\n' || c == '\r' || c == '\t' || c == '\f' || c == '\v' || c == '\\' || c == VK_ESCAPE) { len += 1; } else if (c < 32 || c > 126) { len += 3; } } return len; } ZEND_API void ZEND_FASTCALL smart_str_append_escaped(smart_str *str, const char *s, size_t l) { char *res; size_t i, len = zend_compute_escaped_string_len(s, l); smart_str_alloc(str, len, 0); res = &ZSTR_VAL(str->s)[ZSTR_LEN(str->s)]; ZSTR_LEN(str->s) += len; for (i = 0; i < l; ++i) { unsigned char c = s[i]; if (c < 32 || c == '\\' || c > 126) { *res++ = '\\'; switch (c) { case '\n': *res++ = 'n'; break; case '\r': *res++ = 'r'; break; case '\t': *res++ = 't'; break; case '\f': *res++ = 'f'; break; case '\v': *res++ = 'v'; break; case '\\': *res++ = '\\'; break; case VK_ESCAPE: *res++ = 'e'; break; default: *res++ = 'x'; if ((c >> 4) < 10) { *res++ = (c >> 4) + '0'; } else { *res++ = (c >> 4) + 'A' - 10; } if ((c & 0xf) < 10) { *res++ = (c & 0xf) + '0'; } else { *res++ = (c & 0xf) + 'A' - 10; } } } else { *res++ = c; } } } ZEND_API void ZEND_FASTCALL smart_str_append_double( smart_str *str, double num, int precision, bool zero_fraction) { char buf[ZEND_DOUBLE_MAX_LENGTH]; /* Model snprintf precision behavior. */ zend_gcvt(num, precision ? precision : 1, '.', 'E', buf); smart_str_appends(str, buf); if (zero_fraction && zend_finite(num) && !strchr(buf, '.')) { smart_str_appendl(str, ".0", 2); } } ZEND_API void smart_str_append_printf(smart_str *dest, const char *format, ...) { va_list arg; va_start(arg, format); zend_printf_to_smart_str(dest, format, arg); va_end(arg); } #define SMART_STRING_OVERHEAD (ZEND_MM_OVERHEAD + 1) #define SMART_STRING_START_SIZE 256 #define SMART_STRING_START_LEN (SMART_STRING_START_SIZE - SMART_STRING_OVERHEAD) #define SMART_STRING_PAGE 4096 ZEND_API void ZEND_FASTCALL _smart_string_alloc_persistent(smart_string *str, size_t len) { if (!str->c) { str->len = 0; if (len <= SMART_STRING_START_LEN) { str->a = SMART_STRING_START_LEN; } else { str->a = ZEND_MM_ALIGNED_SIZE_EX(len + SMART_STRING_OVERHEAD, SMART_STRING_PAGE) - SMART_STRING_OVERHEAD; } str->c = pemalloc(str->a + 1, 1); } else { if (UNEXPECTED((size_t) len > SIZE_MAX - str->len)) { zend_error(E_ERROR, "String size overflow"); } len += str->len; str->a = ZEND_MM_ALIGNED_SIZE_EX(len + SMART_STRING_OVERHEAD, SMART_STRING_PAGE) - SMART_STRING_OVERHEAD; str->c = perealloc(str->c, str->a + 1, 1); } } ZEND_API void ZEND_FASTCALL _smart_string_alloc(smart_string *str, size_t len) { if (!str->c) { str->len = 0; if (len <= SMART_STRING_START_LEN) { str->a = SMART_STRING_START_LEN; str->c = emalloc(SMART_STRING_START_LEN + 1); } else { str->a = ZEND_MM_ALIGNED_SIZE_EX(len + SMART_STRING_OVERHEAD, SMART_STRING_PAGE) - SMART_STRING_OVERHEAD; if (EXPECTED(str->a < (ZEND_MM_CHUNK_SIZE - SMART_STRING_OVERHEAD))) { str->c = emalloc_large(str->a + 1); } else { /* allocate a huge chunk */ str->c = emalloc(str->a + 1); } } } else { if (UNEXPECTED((size_t) len > SIZE_MAX - str->len)) { zend_error(E_ERROR, "String size overflow"); } len += str->len; str->a = ZEND_MM_ALIGNED_SIZE_EX(len + SMART_STRING_OVERHEAD, SMART_STRING_PAGE) - SMART_STRING_OVERHEAD; str->c = erealloc2(str->c, str->a + 1, str->len); } } ZEND_API void ZEND_FASTCALL smart_str_append_escaped_truncated(smart_str *str, const zend_string *value, size_t length) { smart_str_append_escaped(str, ZSTR_VAL(value), MIN(length, ZSTR_LEN(value))); if (ZSTR_LEN(value) > length) { smart_str_appendl(str, "...", sizeof("...")-1); } } ZEND_API void ZEND_FASTCALL smart_str_append_scalar(smart_str *dest, const zval *value, size_t truncate) { ZEND_ASSERT(Z_TYPE_P(value) <= IS_STRING); switch (Z_TYPE_P(value)) { case IS_UNDEF: case IS_NULL: smart_str_appendl(dest, "NULL", sizeof("NULL")-1); break; case IS_TRUE: case IS_FALSE: smart_str_appends(dest, Z_TYPE_P(value) == IS_TRUE ? "true" : "false"); break; case IS_DOUBLE: smart_str_append_double(dest, Z_DVAL_P(value), (int) EG(precision), true); break; case IS_LONG: smart_str_append_long(dest, Z_LVAL_P(value)); break; case IS_STRING: smart_str_appendc(dest, '\''); smart_str_append_escaped_truncated(dest, Z_STR_P(value), truncate); smart_str_appendc(dest, '\''); break; EMPTY_SWITCH_DEFAULT_CASE(); } }
6,980
30.165179
119
c
php-src
php-src-master/Zend/zend_smart_str.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_SMART_STR_H #define ZEND_SMART_STR_H #include <zend.h> #include "zend_globals.h" #include "zend_smart_str_public.h" BEGIN_EXTERN_C() ZEND_API void ZEND_FASTCALL smart_str_erealloc(smart_str *str, size_t len); ZEND_API void ZEND_FASTCALL smart_str_realloc(smart_str *str, size_t len); ZEND_API void ZEND_FASTCALL smart_str_append_escaped(smart_str *str, const char *s, size_t l); /* If zero_fraction is true, then a ".0" will be added to numbers that would not otherwise * have a fractional part and look like integers. */ ZEND_API void ZEND_FASTCALL smart_str_append_double( smart_str *str, double num, int precision, bool zero_fraction); ZEND_API void smart_str_append_printf(smart_str *dest, const char *format, ...) ZEND_ATTRIBUTE_FORMAT(printf, 2, 3); ZEND_API void ZEND_FASTCALL smart_str_append_escaped_truncated(smart_str *str, const zend_string *value, size_t length); ZEND_API void ZEND_FASTCALL smart_str_append_scalar(smart_str *str, const zval *value, size_t truncate); END_EXTERN_C() static zend_always_inline size_t smart_str_alloc(smart_str *str, size_t len, bool persistent) { if (UNEXPECTED(!str->s)) { goto do_smart_str_realloc; } else { len += ZSTR_LEN(str->s); if (UNEXPECTED(len >= str->a)) { do_smart_str_realloc: if (persistent) { smart_str_realloc(str, len); } else { smart_str_erealloc(str, len); } } } return len; } static zend_always_inline char* smart_str_extend_ex(smart_str *dest, size_t len, bool persistent) { size_t new_len = smart_str_alloc(dest, len, persistent); char *ret = ZSTR_VAL(dest->s) + ZSTR_LEN(dest->s); ZSTR_LEN(dest->s) = new_len; return ret; } static zend_always_inline char* smart_str_extend(smart_str *dest, size_t length) { return smart_str_extend_ex(dest, length, false); } static zend_always_inline void smart_str_free_ex(smart_str *str, bool persistent) { if (str->s) { zend_string_release_ex(str->s, persistent); str->s = NULL; } str->a = 0; } static zend_always_inline void smart_str_free(smart_str *str) { smart_str_free_ex(str, false); } static zend_always_inline void smart_str_0(smart_str *str) { if (str->s) { ZSTR_VAL(str->s)[ZSTR_LEN(str->s)] = '\0'; } } static zend_always_inline size_t smart_str_get_len(smart_str *str) { return str->s ? ZSTR_LEN(str->s) : 0; } static zend_always_inline void smart_str_trim_to_size_ex(smart_str *str, bool persistent) { if (str->s && str->a > ZSTR_LEN(str->s)) { str->s = zend_string_realloc(str->s, ZSTR_LEN(str->s), persistent); str->a = ZSTR_LEN(str->s); } } static zend_always_inline void smart_str_trim_to_size(smart_str *dest) { smart_str_trim_to_size_ex(dest, false); } static zend_always_inline zend_string *smart_str_extract_ex(smart_str *str, bool persistent) { if (str->s) { zend_string *res; smart_str_0(str); smart_str_trim_to_size_ex(str, persistent); res = str->s; str->s = NULL; return res; } else { return ZSTR_EMPTY_ALLOC(); } } static zend_always_inline zend_string *smart_str_extract(smart_str *dest) { return smart_str_extract_ex(dest, false); } static zend_always_inline void smart_str_appendc_ex(smart_str *dest, char ch, bool persistent) { size_t new_len = smart_str_alloc(dest, 1, persistent); ZSTR_VAL(dest->s)[new_len - 1] = ch; ZSTR_LEN(dest->s) = new_len; } static zend_always_inline void smart_str_appendl_ex(smart_str *dest, const char *str, size_t len, bool persistent) { size_t new_len = smart_str_alloc(dest, len, persistent); memcpy(ZSTR_VAL(dest->s) + ZSTR_LEN(dest->s), str, len); ZSTR_LEN(dest->s) = new_len; } static zend_always_inline void smart_str_append_ex(smart_str *dest, const zend_string *src, bool persistent) { smart_str_appendl_ex(dest, ZSTR_VAL(src), ZSTR_LEN(src), persistent); } static zend_always_inline void smart_str_append_smart_str_ex(smart_str *dest, const smart_str *src, bool persistent) { if (src->s && ZSTR_LEN(src->s)) { smart_str_append_ex(dest, src->s, persistent); } } static zend_always_inline void smart_str_append_long_ex(smart_str *dest, zend_long num, bool persistent) { char buf[32]; char *result = zend_print_long_to_buf(buf + sizeof(buf) - 1, num); smart_str_appendl_ex(dest, result, buf + sizeof(buf) - 1 - result, persistent); } static zend_always_inline void smart_str_append_long(smart_str *dest, zend_long num) { smart_str_append_long_ex(dest, num, false); } static zend_always_inline void smart_str_append_unsigned_ex(smart_str *dest, zend_ulong num, bool persistent) { char buf[32]; char *result = zend_print_ulong_to_buf(buf + sizeof(buf) - 1, num); smart_str_appendl_ex(dest, result, buf + sizeof(buf) - 1 - result, persistent); } static zend_always_inline void smart_str_append_unsigned(smart_str *dest, zend_ulong num) { smart_str_append_unsigned_ex(dest, num, false); } static zend_always_inline void smart_str_appendl(smart_str *dest, const char *src, size_t length) { smart_str_appendl_ex(dest, src, length, false); } static zend_always_inline void smart_str_appends_ex(smart_str *dest, const char *src, bool persistent) { smart_str_appendl_ex(dest, src, strlen(src), persistent); } static zend_always_inline void smart_str_appends(smart_str *dest, const char *src) { smart_str_appendl_ex(dest, src, strlen(src), false); } static zend_always_inline void smart_str_append(smart_str *dest, const zend_string *src) { smart_str_append_ex(dest, src, false); } static zend_always_inline void smart_str_appendc(smart_str *dest, char ch) { smart_str_appendc_ex(dest, ch, false); } static zend_always_inline void smart_str_append_smart_str(smart_str *dest, const smart_str *src) { smart_str_append_smart_str_ex(dest, src, false); } static zend_always_inline void smart_str_setl(smart_str *dest, const char *src, size_t len) { smart_str_free(dest); smart_str_appendl(dest, src, len); } static zend_always_inline void smart_str_sets(smart_str *dest, const char *src) { smart_str_setl(dest, src, strlen(src)); } #endif
6,934
33.502488
120
h
php-src
php-src-master/Zend/zend_smart_str_public.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_SMART_STR_PUBLIC_H #define ZEND_SMART_STR_PUBLIC_H typedef struct { /** See smart_str_extract() */ zend_string *s; size_t a; } smart_str; #endif
1,159
41.962963
75
h
php-src
php-src-master/Zend/zend_smart_string.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_SMART_STRING_H #define PHP_SMART_STRING_H #include "zend_smart_string_public.h" #include <stdlib.h> #include <zend.h> /* wrapper */ #define smart_string_appends_ex(str, src, what) \ smart_string_appendl_ex((str), (src), strlen(src), (what)) #define smart_string_appends(str, src) \ smart_string_appendl((str), (src), strlen(src)) #define smart_string_append_ex(str, src, what) \ smart_string_appendl_ex((str), ((smart_string *)(src))->c, \ ((smart_string *)(src))->len, (what)); #define smart_string_sets(str, src) \ smart_string_setl((str), (src), strlen(src)); #define smart_string_appendc(str, c) \ smart_string_appendc_ex((str), (c), 0) #define smart_string_free(s) \ smart_string_free_ex((s), 0) #define smart_string_appendl(str, src, len) \ smart_string_appendl_ex((str), (src), (len), 0) #define smart_string_append(str, src) \ smart_string_append_ex((str), (src), 0) #define smart_string_append_long(str, val) \ smart_string_append_long_ex((str), (val), 0) #define smart_string_append_unsigned(str, val) \ smart_string_append_unsigned_ex((str), (val), 0) ZEND_API void ZEND_FASTCALL _smart_string_alloc_persistent(smart_string *str, size_t len); ZEND_API void ZEND_FASTCALL _smart_string_alloc(smart_string *str, size_t len); static zend_always_inline size_t smart_string_alloc(smart_string *str, size_t len, bool persistent) { if (UNEXPECTED(!str->c) || UNEXPECTED(len >= str->a - str->len)) { if (persistent) { _smart_string_alloc_persistent(str, len); } else { _smart_string_alloc(str, len); } } return str->len + len; } static zend_always_inline void smart_string_free_ex(smart_string *str, bool persistent) { if (str->c) { pefree(str->c, persistent); str->c = NULL; } str->a = str->len = 0; } static zend_always_inline void smart_string_0(smart_string *str) { if (str->c) { str->c[str->len] = '\0'; } } static zend_always_inline void smart_string_appendc_ex(smart_string *dest, char ch, bool persistent) { dest->len = smart_string_alloc(dest, 1, persistent); dest->c[dest->len - 1] = ch; } static zend_always_inline void smart_string_appendl_ex(smart_string *dest, const char *str, size_t len, bool persistent) { size_t new_len = smart_string_alloc(dest, len, persistent); memcpy(dest->c + dest->len, str, len); dest->len = new_len; } static zend_always_inline void smart_string_append_long_ex(smart_string *dest, zend_long num, bool persistent) { char buf[32]; char *result = zend_print_long_to_buf(buf + sizeof(buf) - 1, num); smart_string_appendl_ex(dest, result, buf + sizeof(buf) - 1 - result, persistent); } static zend_always_inline void smart_string_append_unsigned_ex(smart_string *dest, zend_ulong num, bool persistent) { char buf[32]; char *result = zend_print_ulong_to_buf(buf + sizeof(buf) - 1, num); smart_string_appendl_ex(dest, result, buf + sizeof(buf) - 1 - result, persistent); } static zend_always_inline void smart_string_setl(smart_string *dest, char *src, size_t len) { dest->len = len; dest->a = len + 1; dest->c = src; } static zend_always_inline void smart_string_reset(smart_string *str) { str->len = 0; } #endif
4,207
35.912281
122
h
php-src
php-src-master/Zend/zend_smart_string_public.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sascha Schumann <[email protected]> | | Xinchen Hui <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef PHP_SMART_STRING_PUBLIC_H #define PHP_SMART_STRING_PUBLIC_H #include <sys/types.h> typedef struct { char *c; size_t len; size_t a; } smart_string; #endif
1,240
40.366667
75
h
php-src
php-src-master/Zend/zend_sort.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Xinchen Hui <[email protected]> | | Sterling Hughes <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_sort.h" #include <limits.h> static inline void zend_sort_2(void *a, void *b, compare_func_t cmp, swap_func_t swp) /* {{{ */ { if (cmp(a, b) > 0) { swp(a, b); } } /* }}} */ static inline void zend_sort_3(void *a, void *b, void *c, compare_func_t cmp, swap_func_t swp) /* {{{ */ { if (!(cmp(a, b) > 0)) { if (!(cmp(b, c) > 0)) { return; } swp(b, c); if (cmp(a, b) > 0) { swp(a, b); } return; } if (!(cmp(c, b) > 0)) { swp(a, c); return; } swp(a, b); if (cmp(b, c) > 0) { swp(b, c); } } /* }}} */ static void zend_sort_4(void *a, void *b, void *c, void *d, compare_func_t cmp, swap_func_t swp) /* {{{ */ { zend_sort_3(a, b, c, cmp, swp); if (cmp(c, d) > 0) { swp(c, d); if (cmp(b, c) > 0) { swp(b, c); if (cmp(a, b) > 0) { swp(a, b); } } } } /* }}} */ static void zend_sort_5(void *a, void *b, void *c, void *d, void *e, compare_func_t cmp, swap_func_t swp) /* {{{ */ { zend_sort_4(a, b, c, d, cmp, swp); if (cmp(d, e) > 0) { swp(d, e); if (cmp(c, d) > 0) { swp(c, d); if (cmp(b, c) > 0) { swp(b, c); if (cmp(a, b) > 0) { swp(a, b); } } } } } /* }}} */ ZEND_API void zend_insert_sort(void *base, size_t nmemb, size_t siz, compare_func_t cmp, swap_func_t swp) /* {{{ */{ switch (nmemb) { case 0: case 1: break; case 2: zend_sort_2(base, (char *)base + siz, cmp, swp); break; case 3: zend_sort_3(base, (char *)base + siz, (char *)base + siz + siz, cmp, swp); break; case 4: { size_t siz2 = siz + siz; zend_sort_4(base, (char *)base + siz, (char *)base + siz2, (char *)base + siz + siz2, cmp, swp); } break; case 5: { size_t siz2 = siz + siz; zend_sort_5(base, (char *)base + siz, (char *)base + siz2, (char *)base + siz + siz2, (char *)base + siz2 + siz2, cmp, swp); } break; default: { char *i, *j, *k; char *start = (char *)base; char *end = start + (nmemb * siz); size_t siz2= siz + siz; char *sentry = start + (6 * siz); for (i = start + siz; i < sentry; i += siz) { j = i - siz; if (!(cmp(j, i) > 0)) { continue; } while (j != start) { j -= siz; if (!(cmp(j, i) > 0)) { j += siz; break; } } for (k = i; k > j; k -= siz) { swp(k, k - siz); } } for (i = sentry; i < end; i += siz) { j = i - siz; if (!(cmp(j, i) > 0)) { continue; } do { j -= siz2; if (!(cmp(j, i) > 0)) { j += siz; if (!(cmp(j, i) > 0)) { j += siz; } break; } if (j == start) { break; } if (j == start + siz) { j -= siz; if (cmp(i, j) > 0) { j += siz; } break; } } while (1); for (k = i; k > j; k -= siz) { swp(k, k - siz); } } } break; } } /* }}} */ /* {{{ ZEND_API void zend_sort(void *base, size_t nmemb, size_t siz, compare_func_t cmp, swap_func_t swp) * * Derived from LLVM's libc++ implementation of std::sort. * * =========================================================================== * libc++ License * =========================================================================== * * The libc++ library is dual licensed under both the University of Illinois * "BSD-Like" license and the MIT license. As a user of this code you may * choose to use it under either license. As a contributor, you agree to allow * your code to be used under both. * * Full text of the relevant licenses is included below. * * =========================================================================== * * University of Illinois/NCSA * Open Source License * * Copyright (c) 2009-2012 by the contributors listed at * http://llvm.org/svn/llvm-project/libcxx/trunk/CREDITS.TXT * * All rights reserved. * * Developed by: * * LLVM Team * * University of Illinois at Urbana-Champaign * * http://llvm.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal with the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimers. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimers in the * documentation and/or other materials provided with the distribution. * * * Neither the names of the LLVM Team, University of Illinois at * Urbana-Champaign, nor the names of its contributors may be used to * endorse or promote products derived from this Software without * specific prior written permission. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * WITH THE SOFTWARE. * * =========================================================================== * * Copyright (c) 2009-2012 by the contributors listed at * http://llvm.org/svn/llvm-project/libcxx/trunk/CREDITS.TXT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ ZEND_API void zend_sort(void *base, size_t nmemb, size_t siz, compare_func_t cmp, swap_func_t swp) { while (1) { if (nmemb <= 16) { zend_insert_sort(base, nmemb, siz, cmp, swp); return; } else { char *i, *j; char *start = (char *)base; char *end = start + (nmemb * siz); size_t offset = (nmemb >> Z_L(1)); char *pivot = start + (offset * siz); if ((nmemb >> Z_L(10))) { size_t delta = (offset >> Z_L(1)) * siz; zend_sort_5(start, start + delta, pivot, pivot + delta, end - siz, cmp, swp); } else { zend_sort_3(start, pivot, end - siz, cmp, swp); } swp(start + siz, pivot); pivot = start + siz; i = pivot + siz; j = end - siz; while (1) { while (cmp(pivot, i) > 0) { i += siz; if (UNEXPECTED(i == j)) { goto done; } } j -= siz; if (UNEXPECTED(j == i)) { goto done; } while (cmp(j, pivot) > 0) { j -= siz; if (UNEXPECTED(j == i)) { goto done; } } swp(i, j); i += siz; if (UNEXPECTED(i == j)) { goto done; } } done: swp(pivot, i - siz); if ((i - siz) - start < end - i) { zend_sort(start, (i - start)/siz - 1, siz, cmp, swp); base = i; nmemb = (end - i)/siz; } else { zend_sort(i, (end - i)/siz, siz, cmp, swp); nmemb = (i - start)/siz - 1; } } } } /* }}} */
9,439
29.649351
128
c
php-src
php-src-master/Zend/zend_sort.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Xinchen Hui <[email protected]> | | Sterling Hughes <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_SORT_H #define ZEND_SORT_H BEGIN_EXTERN_C() ZEND_API void zend_sort(void *base, size_t nmemb, size_t siz, compare_func_t cmp, swap_func_t swp); ZEND_API void zend_insert_sort(void *base, size_t nmemb, size_t siz, compare_func_t cmp, swap_func_t swp); END_EXTERN_C() #endif /* ZEND_SORT_H */
1,535
51.965517
106
h
php-src
php-src-master/Zend/zend_stream.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Scott MacVicar <[email protected]> | | Nuno Lopes <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ #include "zend.h" #include "zend_compile.h" #include "zend_stream.h" ZEND_DLIMPORT int isatty(int fd); static ssize_t zend_stream_stdio_reader(void *handle, char *buf, size_t len) /* {{{ */ { return fread(buf, 1, len, (FILE*)handle); } /* }}} */ static void zend_stream_stdio_closer(void *handle) /* {{{ */ { if (handle && (FILE*)handle != stdin) { fclose((FILE*)handle); } } /* }}} */ static size_t zend_stream_stdio_fsizer(void *handle) /* {{{ */ { zend_stat_t buf = {0}; if (handle && zend_fstat(fileno((FILE*)handle), &buf) == 0) { #ifdef S_ISREG if (!S_ISREG(buf.st_mode)) { return 0; } #endif return buf.st_size; } return -1; } /* }}} */ static size_t zend_stream_fsize(zend_file_handle *file_handle) /* {{{ */ { ZEND_ASSERT(file_handle->type == ZEND_HANDLE_STREAM); if (file_handle->handle.stream.isatty) { return 0; } return file_handle->handle.stream.fsizer(file_handle->handle.stream.handle); } /* }}} */ ZEND_API void zend_stream_init_fp(zend_file_handle *handle, FILE *fp, const char *filename) { memset(handle, 0, sizeof(zend_file_handle)); handle->type = ZEND_HANDLE_FP; handle->handle.fp = fp; handle->filename = filename ? zend_string_init(filename, strlen(filename), 0) : NULL; } ZEND_API void zend_stream_init_filename(zend_file_handle *handle, const char *filename) { memset(handle, 0, sizeof(zend_file_handle)); handle->type = ZEND_HANDLE_FILENAME; handle->filename = filename ? zend_string_init(filename, strlen(filename), 0) : NULL; } ZEND_API void zend_stream_init_filename_ex(zend_file_handle *handle, zend_string *filename) { memset(handle, 0, sizeof(zend_file_handle)); handle->type = ZEND_HANDLE_FILENAME; handle->filename = zend_string_copy(filename); } ZEND_API zend_result zend_stream_open(zend_file_handle *handle) /* {{{ */ { zend_string *opened_path; ZEND_ASSERT(handle->type == ZEND_HANDLE_FILENAME); if (zend_stream_open_function) { return zend_stream_open_function(handle); } handle->handle.fp = zend_fopen(handle->filename, &opened_path); if (!handle->handle.fp) { return FAILURE; } handle->type = ZEND_HANDLE_FP; return SUCCESS; } /* }}} */ static int zend_stream_getc(zend_file_handle *file_handle) /* {{{ */ { char buf; if (file_handle->handle.stream.reader(file_handle->handle.stream.handle, &buf, sizeof(buf))) { return (int)buf; } return EOF; } /* }}} */ static ssize_t zend_stream_read(zend_file_handle *file_handle, char *buf, size_t len) /* {{{ */ { if (file_handle->handle.stream.isatty) { int c = '*'; size_t n; for (n = 0; n < len && (c = zend_stream_getc(file_handle)) != EOF && c != '\n'; ++n) { buf[n] = (char)c; } if (c == '\n') { buf[n++] = (char)c; } return n; } return file_handle->handle.stream.reader(file_handle->handle.stream.handle, buf, len); } /* }}} */ ZEND_API zend_result zend_stream_fixup(zend_file_handle *file_handle, char **buf, size_t *len) /* {{{ */ { size_t file_size; if (file_handle->buf) { *buf = file_handle->buf; *len = file_handle->len; return SUCCESS; } if (file_handle->type == ZEND_HANDLE_FILENAME) { if (zend_stream_open(file_handle) == FAILURE) { return FAILURE; } } if (file_handle->type == ZEND_HANDLE_FP) { if (!file_handle->handle.fp) { return FAILURE; } file_handle->type = ZEND_HANDLE_STREAM; file_handle->handle.stream.handle = file_handle->handle.fp; file_handle->handle.stream.isatty = isatty(fileno((FILE *)file_handle->handle.stream.handle)); file_handle->handle.stream.reader = (zend_stream_reader_t)zend_stream_stdio_reader; file_handle->handle.stream.closer = (zend_stream_closer_t)zend_stream_stdio_closer; file_handle->handle.stream.fsizer = (zend_stream_fsizer_t)zend_stream_stdio_fsizer; } file_size = zend_stream_fsize(file_handle); if (file_size == (size_t)-1) { return FAILURE; } if (file_size) { ssize_t read; size_t size = 0; *buf = safe_emalloc(1, file_size, ZEND_MMAP_AHEAD); while ((read = zend_stream_read(file_handle, *buf + size, file_size - size)) > 0) { size += read; } if (read < 0) { efree(*buf); return FAILURE; } file_handle->buf = *buf; file_handle->len = size; } else { size_t size = 0, remain = 4*1024; ssize_t read; *buf = emalloc(remain); while ((read = zend_stream_read(file_handle, *buf + size, remain)) > 0) { size += read; remain -= read; if (remain == 0) { *buf = safe_erealloc(*buf, size, 2, 0); remain = size; } } if (read < 0) { efree(*buf); return FAILURE; } file_handle->len = size; if (size && remain < ZEND_MMAP_AHEAD) { *buf = safe_erealloc(*buf, size, 1, ZEND_MMAP_AHEAD); } file_handle->buf = *buf; } if (file_handle->len == 0) { *buf = erealloc(*buf, ZEND_MMAP_AHEAD); file_handle->buf = *buf; } memset(file_handle->buf + file_handle->len, 0, ZEND_MMAP_AHEAD); *buf = file_handle->buf; *len = file_handle->len; return SUCCESS; } /* }}} */ static void zend_file_handle_dtor(zend_file_handle *fh) /* {{{ */ { switch (fh->type) { case ZEND_HANDLE_FP: if (fh->handle.fp) { fclose(fh->handle.fp); fh->handle.fp = NULL; } break; case ZEND_HANDLE_STREAM: if (fh->handle.stream.closer && fh->handle.stream.handle) { fh->handle.stream.closer(fh->handle.stream.handle); } fh->handle.stream.handle = NULL; break; case ZEND_HANDLE_FILENAME: /* We're only supposed to get here when destructing the used_files hash, * which doesn't really contain open files, but references to their names/paths */ break; } if (fh->opened_path) { zend_string_release_ex(fh->opened_path, 0); fh->opened_path = NULL; } if (fh->buf) { efree(fh->buf); fh->buf = NULL; } if (fh->filename) { zend_string_release(fh->filename); fh->filename = NULL; } } /* }}} */ /* return int to be compatible with Zend linked list API */ static int zend_compare_file_handles(zend_file_handle *fh1, zend_file_handle *fh2) /* {{{ */ { if (fh1->type != fh2->type) { return 0; } switch (fh1->type) { case ZEND_HANDLE_FILENAME: return zend_string_equals(fh1->filename, fh2->filename); case ZEND_HANDLE_FP: return fh1->handle.fp == fh2->handle.fp; case ZEND_HANDLE_STREAM: return fh1->handle.stream.handle == fh2->handle.stream.handle; default: return 0; } return 0; } /* }}} */ ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle) /* {{{ */ { if (file_handle->in_list) { zend_llist_del_element(&CG(open_files), file_handle, (int (*)(void *, void *)) zend_compare_file_handles); /* zend_file_handle_dtor() operates on the copy, so we have to NULLify the original here */ file_handle->opened_path = NULL; file_handle->filename = NULL; } else { zend_file_handle_dtor(file_handle); } } /* }}} */ void zend_stream_init(void) /* {{{ */ { zend_llist_init(&CG(open_files), sizeof(zend_file_handle), (void (*)(void *)) zend_file_handle_dtor, 0); } /* }}} */ void zend_stream_shutdown(void) /* {{{ */ { zend_llist_destroy(&CG(open_files)); } /* }}} */
8,382
28.00692
108
c
php-src
php-src-master/Zend/zend_stream.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Wez Furlong <[email protected]> | | Scott MacVicar <[email protected]> | | Nuno Lopes <[email protected]> | | Marcus Boerger <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_STREAM_H #define ZEND_STREAM_H #include <sys/types.h> #include <sys/stat.h> /* Lightweight stream implementation for the ZE scanners. * These functions are private to the engine. * */ typedef size_t (*zend_stream_fsizer_t)(void* handle); typedef ssize_t (*zend_stream_reader_t)(void* handle, char *buf, size_t len); typedef void (*zend_stream_closer_t)(void* handle); #define ZEND_MMAP_AHEAD 32 typedef enum { ZEND_HANDLE_FILENAME, ZEND_HANDLE_FP, ZEND_HANDLE_STREAM } zend_stream_type; typedef struct _zend_stream { void *handle; int isatty; zend_stream_reader_t reader; zend_stream_fsizer_t fsizer; zend_stream_closer_t closer; } zend_stream; typedef struct _zend_file_handle { union { FILE *fp; zend_stream stream; } handle; zend_string *filename; zend_string *opened_path; uint8_t type; /* packed zend_stream_type */ bool primary_script; bool in_list; /* added into CG(open_file) */ char *buf; size_t len; } zend_file_handle; BEGIN_EXTERN_C() ZEND_API void zend_stream_init_fp(zend_file_handle *handle, FILE *fp, const char *filename); ZEND_API void zend_stream_init_filename(zend_file_handle *handle, const char *filename); ZEND_API void zend_stream_init_filename_ex(zend_file_handle *handle, zend_string *filename); ZEND_API zend_result zend_stream_open(zend_file_handle *handle); ZEND_API zend_result zend_stream_fixup(zend_file_handle *file_handle, char **buf, size_t *len); ZEND_API void zend_destroy_file_handle(zend_file_handle *file_handle); void zend_stream_init(void); void zend_stream_shutdown(void); END_EXTERN_C() #ifdef ZEND_WIN32 # include "win32/ioutil.h" typedef php_win32_ioutil_stat_t zend_stat_t; #ifdef _WIN64 # define zend_fseek _fseeki64 # define zend_ftell _ftelli64 # define zend_lseek _lseeki64 # else # define zend_fseek fseek # define zend_ftell ftell # define zend_lseek lseek # endif # define zend_fstat php_win32_ioutil_fstat # define zend_stat php_win32_ioutil_stat #else typedef struct stat zend_stat_t; # define zend_fseek fseek # define zend_ftell ftell # define zend_lseek lseek # define zend_fstat fstat # define zend_stat stat #endif #endif
3,616
34.811881
95
h
php-src
php-src-master/Zend/zend_string.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_STRING_H #define ZEND_STRING_H #include "zend.h" BEGIN_EXTERN_C() typedef void (*zend_string_copy_storage_func_t)(void); typedef zend_string *(ZEND_FASTCALL *zend_new_interned_string_func_t)(zend_string *str); typedef zend_string *(ZEND_FASTCALL *zend_string_init_interned_func_t)(const char *str, size_t size, bool permanent); typedef zend_string *(ZEND_FASTCALL *zend_string_init_existing_interned_func_t)(const char *str, size_t size, bool permanent); ZEND_API extern zend_new_interned_string_func_t zend_new_interned_string; ZEND_API extern zend_string_init_interned_func_t zend_string_init_interned; /* Init an interned string if it already exists, but do not create a new one if it does not. */ ZEND_API extern zend_string_init_existing_interned_func_t zend_string_init_existing_interned; ZEND_API zend_ulong ZEND_FASTCALL zend_string_hash_func(zend_string *str); ZEND_API zend_ulong ZEND_FASTCALL zend_hash_func(const char *str, size_t len); ZEND_API zend_string* ZEND_FASTCALL zend_interned_string_find_permanent(zend_string *str); ZEND_API zend_string *zend_string_concat2( const char *str1, size_t str1_len, const char *str2, size_t str2_len); ZEND_API zend_string *zend_string_concat3( const char *str1, size_t str1_len, const char *str2, size_t str2_len, const char *str3, size_t str3_len); ZEND_API void zend_interned_strings_init(void); ZEND_API void zend_interned_strings_dtor(void); ZEND_API void zend_interned_strings_activate(void); ZEND_API void zend_interned_strings_deactivate(void); ZEND_API void zend_interned_strings_set_request_storage_handlers( zend_new_interned_string_func_t handler, zend_string_init_interned_func_t init_handler, zend_string_init_existing_interned_func_t init_existing_handler); ZEND_API void zend_interned_strings_switch_storage(bool request); ZEND_API extern zend_string *zend_empty_string; ZEND_API extern zend_string *zend_one_char_string[256]; ZEND_API extern zend_string **zend_known_strings; END_EXTERN_C() /* Shortcuts */ #define ZSTR_VAL(zstr) (zstr)->val #define ZSTR_LEN(zstr) (zstr)->len #define ZSTR_H(zstr) (zstr)->h #define ZSTR_HASH(zstr) zend_string_hash_val(zstr) /* Compatibility macros */ #define IS_INTERNED(s) ZSTR_IS_INTERNED(s) #define STR_EMPTY_ALLOC() ZSTR_EMPTY_ALLOC() #define _STR_HEADER_SIZE _ZSTR_HEADER_SIZE #define STR_ALLOCA_ALLOC(str, _len, use_heap) ZSTR_ALLOCA_ALLOC(str, _len, use_heap) #define STR_ALLOCA_INIT(str, s, len, use_heap) ZSTR_ALLOCA_INIT(str, s, len, use_heap) #define STR_ALLOCA_FREE(str, use_heap) ZSTR_ALLOCA_FREE(str, use_heap) /*---*/ #define ZSTR_IS_INTERNED(s) (GC_FLAGS(s) & IS_STR_INTERNED) #define ZSTR_IS_VALID_UTF8(s) (GC_FLAGS(s) & IS_STR_VALID_UTF8) /* These are properties, encoded as flags, that will hold on the resulting string * after concatenating two strings that have these property. * Example: concatenating two UTF-8 strings yields another UTF-8 string. */ #define ZSTR_COPYABLE_CONCAT_PROPERTIES (IS_STR_VALID_UTF8) #define ZSTR_GET_COPYABLE_CONCAT_PROPERTIES(s) (GC_FLAGS(s) & ZSTR_COPYABLE_CONCAT_PROPERTIES) /* This macro returns the copyable concat properties which hold on both strings. */ #define ZSTR_GET_COPYABLE_CONCAT_PROPERTIES_BOTH(s1, s2) (GC_FLAGS(s1) & GC_FLAGS(s2) & ZSTR_COPYABLE_CONCAT_PROPERTIES) #define ZSTR_COPY_CONCAT_PROPERTIES(out, in) do { \ zend_string *_out = (out); \ uint32_t properties = ZSTR_GET_COPYABLE_CONCAT_PROPERTIES((in)); \ GC_ADD_FLAGS(_out, properties); \ } while (0) #define ZSTR_COPY_CONCAT_PROPERTIES_BOTH(out, in1, in2) do { \ zend_string *_out = (out); \ uint32_t properties = ZSTR_GET_COPYABLE_CONCAT_PROPERTIES_BOTH((in1), (in2)); \ GC_ADD_FLAGS(_out, properties); \ } while (0) #define ZSTR_EMPTY_ALLOC() zend_empty_string #define ZSTR_CHAR(c) zend_one_char_string[c] #define ZSTR_KNOWN(idx) zend_known_strings[idx] #define _ZSTR_HEADER_SIZE XtOffsetOf(zend_string, val) #define _ZSTR_STRUCT_SIZE(len) (_ZSTR_HEADER_SIZE + len + 1) #define ZSTR_MAX_OVERHEAD (ZEND_MM_ALIGNED_SIZE(_ZSTR_HEADER_SIZE + 1)) #define ZSTR_MAX_LEN (SIZE_MAX - ZSTR_MAX_OVERHEAD) #define ZSTR_ALLOCA_ALLOC(str, _len, use_heap) do { \ (str) = (zend_string *)do_alloca(ZEND_MM_ALIGNED_SIZE_EX(_ZSTR_STRUCT_SIZE(_len), 8), (use_heap)); \ GC_SET_REFCOUNT(str, 1); \ GC_TYPE_INFO(str) = GC_STRING; \ ZSTR_H(str) = 0; \ ZSTR_LEN(str) = _len; \ } while (0) #define ZSTR_ALLOCA_INIT(str, s, len, use_heap) do { \ ZSTR_ALLOCA_ALLOC(str, len, use_heap); \ memcpy(ZSTR_VAL(str), (s), (len)); \ ZSTR_VAL(str)[(len)] = '\0'; \ } while (0) #define ZSTR_ALLOCA_FREE(str, use_heap) free_alloca(str, use_heap) #define ZSTR_INIT_LITERAL(s, persistent) (zend_string_init((s), strlen(s), (persistent))) /*---*/ static zend_always_inline zend_ulong zend_string_hash_val(zend_string *s) { return ZSTR_H(s) ? ZSTR_H(s) : zend_string_hash_func(s); } static zend_always_inline void zend_string_forget_hash_val(zend_string *s) { ZSTR_H(s) = 0; GC_DEL_FLAGS(s, IS_STR_VALID_UTF8); } static zend_always_inline uint32_t zend_string_refcount(const zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { return GC_REFCOUNT(s); } return 1; } static zend_always_inline uint32_t zend_string_addref(zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { return GC_ADDREF(s); } return 1; } static zend_always_inline uint32_t zend_string_delref(zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { return GC_DELREF(s); } return 1; } static zend_always_inline zend_string *zend_string_alloc(size_t len, bool persistent) { zend_string *ret = (zend_string *)pemalloc(ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(len)), persistent); GC_SET_REFCOUNT(ret, 1); GC_TYPE_INFO(ret) = GC_STRING | ((persistent ? IS_STR_PERSISTENT : 0) << GC_FLAGS_SHIFT); ZSTR_H(ret) = 0; ZSTR_LEN(ret) = len; return ret; } static zend_always_inline zend_string *zend_string_safe_alloc(size_t n, size_t m, size_t l, bool persistent) { zend_string *ret = (zend_string *)safe_pemalloc(n, m, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(l)), persistent); GC_SET_REFCOUNT(ret, 1); GC_TYPE_INFO(ret) = GC_STRING | ((persistent ? IS_STR_PERSISTENT : 0) << GC_FLAGS_SHIFT); ZSTR_H(ret) = 0; ZSTR_LEN(ret) = (n * m) + l; return ret; } static zend_always_inline zend_string *zend_string_init(const char *str, size_t len, bool persistent) { zend_string *ret = zend_string_alloc(len, persistent); memcpy(ZSTR_VAL(ret), str, len); ZSTR_VAL(ret)[len] = '\0'; return ret; } static zend_always_inline zend_string *zend_string_init_fast(const char *str, size_t len) { if (len > 1) { return zend_string_init(str, len, 0); } else if (len == 0) { return zend_empty_string; } else /* if (len == 1) */ { return ZSTR_CHAR((zend_uchar) *str); } } static zend_always_inline zend_string *zend_string_copy(zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { GC_ADDREF(s); } return s; } static zend_always_inline zend_string *zend_string_dup(zend_string *s, bool persistent) { if (ZSTR_IS_INTERNED(s)) { return s; } else { return zend_string_init(ZSTR_VAL(s), ZSTR_LEN(s), persistent); } } static zend_always_inline zend_string *zend_string_separate(zend_string *s, bool persistent) { if (ZSTR_IS_INTERNED(s) || GC_REFCOUNT(s) > 1) { if (!ZSTR_IS_INTERNED(s)) { GC_DELREF(s); } return zend_string_init(ZSTR_VAL(s), ZSTR_LEN(s), persistent); } zend_string_forget_hash_val(s); return s; } static zend_always_inline zend_string *zend_string_realloc(zend_string *s, size_t len, bool persistent) { zend_string *ret; if (!ZSTR_IS_INTERNED(s)) { if (EXPECTED(GC_REFCOUNT(s) == 1)) { ret = (zend_string *)perealloc(s, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(len)), persistent); ZSTR_LEN(ret) = len; zend_string_forget_hash_val(ret); return ret; } } ret = zend_string_alloc(len, persistent); memcpy(ZSTR_VAL(ret), ZSTR_VAL(s), MIN(len, ZSTR_LEN(s)) + 1); if (!ZSTR_IS_INTERNED(s)) { GC_DELREF(s); } return ret; } static zend_always_inline zend_string *zend_string_extend(zend_string *s, size_t len, bool persistent) { zend_string *ret; ZEND_ASSERT(len >= ZSTR_LEN(s)); if (!ZSTR_IS_INTERNED(s)) { if (EXPECTED(GC_REFCOUNT(s) == 1)) { ret = (zend_string *)perealloc(s, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(len)), persistent); ZSTR_LEN(ret) = len; zend_string_forget_hash_val(ret); return ret; } } ret = zend_string_alloc(len, persistent); memcpy(ZSTR_VAL(ret), ZSTR_VAL(s), ZSTR_LEN(s) + 1); if (!ZSTR_IS_INTERNED(s)) { GC_DELREF(s); } return ret; } static zend_always_inline zend_string *zend_string_truncate(zend_string *s, size_t len, bool persistent) { zend_string *ret; ZEND_ASSERT(len <= ZSTR_LEN(s)); if (!ZSTR_IS_INTERNED(s)) { if (EXPECTED(GC_REFCOUNT(s) == 1)) { ret = (zend_string *)perealloc(s, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(len)), persistent); ZSTR_LEN(ret) = len; zend_string_forget_hash_val(ret); return ret; } } ret = zend_string_alloc(len, persistent); memcpy(ZSTR_VAL(ret), ZSTR_VAL(s), len + 1); if (!ZSTR_IS_INTERNED(s)) { GC_DELREF(s); } return ret; } static zend_always_inline zend_string *zend_string_safe_realloc(zend_string *s, size_t n, size_t m, size_t l, bool persistent) { zend_string *ret; if (!ZSTR_IS_INTERNED(s)) { if (GC_REFCOUNT(s) == 1) { ret = (zend_string *)safe_perealloc(s, n, m, ZEND_MM_ALIGNED_SIZE(_ZSTR_STRUCT_SIZE(l)), persistent); ZSTR_LEN(ret) = (n * m) + l; zend_string_forget_hash_val(ret); return ret; } } ret = zend_string_safe_alloc(n, m, l, persistent); memcpy(ZSTR_VAL(ret), ZSTR_VAL(s), MIN((n * m) + l, ZSTR_LEN(s)) + 1); if (!ZSTR_IS_INTERNED(s)) { GC_DELREF(s); } return ret; } static zend_always_inline void zend_string_free(zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { ZEND_ASSERT(GC_REFCOUNT(s) <= 1); pefree(s, GC_FLAGS(s) & IS_STR_PERSISTENT); } } static zend_always_inline void zend_string_efree(zend_string *s) { ZEND_ASSERT(!ZSTR_IS_INTERNED(s)); ZEND_ASSERT(GC_REFCOUNT(s) <= 1); ZEND_ASSERT(!(GC_FLAGS(s) & IS_STR_PERSISTENT)); efree(s); } static zend_always_inline void zend_string_release(zend_string *s) { if (!ZSTR_IS_INTERNED(s)) { if (GC_DELREF(s) == 0) { pefree(s, GC_FLAGS(s) & IS_STR_PERSISTENT); } } } static zend_always_inline void zend_string_release_ex(zend_string *s, bool persistent) { if (!ZSTR_IS_INTERNED(s)) { if (GC_DELREF(s) == 0) { if (persistent) { ZEND_ASSERT(GC_FLAGS(s) & IS_STR_PERSISTENT); free(s); } else { ZEND_ASSERT(!(GC_FLAGS(s) & IS_STR_PERSISTENT)); efree(s); } } } } static zend_always_inline bool zend_string_equals_cstr(const zend_string *s1, const char *s2, size_t s2_length) { return ZSTR_LEN(s1) == s2_length && !memcmp(ZSTR_VAL(s1), s2, s2_length); } #if defined(__GNUC__) && (defined(__i386__) || (defined(__x86_64__) && !defined(__ILP32__))) BEGIN_EXTERN_C() ZEND_API bool ZEND_FASTCALL zend_string_equal_val(const zend_string *s1, const zend_string *s2); END_EXTERN_C() #else static zend_always_inline bool zend_string_equal_val(const zend_string *s1, const zend_string *s2) { return !memcmp(ZSTR_VAL(s1), ZSTR_VAL(s2), ZSTR_LEN(s1)); } #endif static zend_always_inline bool zend_string_equal_content(const zend_string *s1, const zend_string *s2) { return ZSTR_LEN(s1) == ZSTR_LEN(s2) && zend_string_equal_val(s1, s2); } static zend_always_inline bool zend_string_equals(const zend_string *s1, const zend_string *s2) { return s1 == s2 || zend_string_equal_content(s1, s2); } #define zend_string_equals_ci(s1, s2) \ (ZSTR_LEN(s1) == ZSTR_LEN(s2) && !zend_binary_strcasecmp(ZSTR_VAL(s1), ZSTR_LEN(s1), ZSTR_VAL(s2), ZSTR_LEN(s2))) #define zend_string_equals_literal_ci(str, c) \ (ZSTR_LEN(str) == sizeof("" c) - 1 && !zend_binary_strcasecmp(ZSTR_VAL(str), ZSTR_LEN(str), (c), sizeof(c) - 1)) #define zend_string_equals_literal(str, literal) \ zend_string_equals_cstr(str, "" literal, sizeof(literal) - 1) static zend_always_inline bool zend_string_starts_with_cstr(const zend_string *str, const char *prefix, size_t prefix_length) { return ZSTR_LEN(str) >= prefix_length && !memcmp(ZSTR_VAL(str), prefix, prefix_length); } static zend_always_inline bool zend_string_starts_with(const zend_string *str, const zend_string *prefix) { return zend_string_starts_with_cstr(str, ZSTR_VAL(prefix), ZSTR_LEN(prefix)); } #define zend_string_starts_with_literal(str, prefix) \ zend_string_starts_with_cstr(str, prefix, strlen(prefix)) static zend_always_inline bool zend_string_starts_with_cstr_ci(const zend_string *str, const char *prefix, size_t prefix_length) { return ZSTR_LEN(str) >= prefix_length && !strncasecmp(ZSTR_VAL(str), prefix, prefix_length); } static zend_always_inline bool zend_string_starts_with_ci(const zend_string *str, const zend_string *prefix) { return zend_string_starts_with_cstr_ci(str, ZSTR_VAL(prefix), ZSTR_LEN(prefix)); } #define zend_string_starts_with_literal_ci(str, prefix) \ zend_string_starts_with_cstr(str, prefix, strlen(prefix)) /* * DJBX33A (Daniel J. Bernstein, Times 33 with Addition) * * This is Daniel J. Bernstein's popular `times 33' hash function as * posted by him years ago on comp.lang.c. It basically uses a function * like ``hash(i) = hash(i-1) * 33 + str[i]''. This is one of the best * known hash functions for strings. Because it is both computed very * fast and distributes very well. * * The magic of number 33, i.e. why it works better than many other * constants, prime or not, has never been adequately explained by * anyone. So I try an explanation: if one experimentally tests all * multipliers between 1 and 256 (as RSE did now) one detects that even * numbers are not usable at all. The remaining 128 odd numbers * (except for the number 1) work more or less all equally well. They * all distribute in an acceptable way and this way fill a hash table * with an average percent of approx. 86%. * * If one compares the Chi^2 values of the variants, the number 33 not * even has the best value. But the number 33 and a few other equally * good numbers like 17, 31, 63, 127 and 129 have nevertheless a great * advantage to the remaining numbers in the large set of possible * multipliers: their multiply operation can be replaced by a faster * operation based on just one shift plus either a single addition * or subtraction operation. And because a hash function has to both * distribute good _and_ has to be very fast to compute, those few * numbers should be preferred and seems to be the reason why Daniel J. * Bernstein also preferred it. * * * -- Ralf S. Engelschall <[email protected]> */ static zend_always_inline zend_ulong zend_inline_hash_func(const char *str, size_t len) { zend_ulong hash = Z_UL(5381); #if defined(_WIN32) || defined(__i386__) || defined(__x86_64__) || defined(__aarch64__) /* Version with multiplication works better on modern CPU */ for (; len >= 8; len -= 8, str += 8) { # if defined(__aarch64__) && !defined(WORDS_BIGENDIAN) /* On some architectures it is beneficial to load 8 bytes at a time and extract each byte with a bit field extract instr. */ uint64_t chunk; memcpy(&chunk, str, sizeof(chunk)); hash = hash * 33 * 33 * 33 * 33 + ((chunk >> (8 * 0)) & 0xff) * 33 * 33 * 33 + ((chunk >> (8 * 1)) & 0xff) * 33 * 33 + ((chunk >> (8 * 2)) & 0xff) * 33 + ((chunk >> (8 * 3)) & 0xff); hash = hash * 33 * 33 * 33 * 33 + ((chunk >> (8 * 4)) & 0xff) * 33 * 33 * 33 + ((chunk >> (8 * 5)) & 0xff) * 33 * 33 + ((chunk >> (8 * 6)) & 0xff) * 33 + ((chunk >> (8 * 7)) & 0xff); # else hash = hash * Z_L(33 * 33 * 33 * 33) + str[0] * Z_L(33 * 33 * 33) + str[1] * Z_L(33 * 33) + str[2] * Z_L(33) + str[3]; hash = hash * Z_L(33 * 33 * 33 * 33) + str[4] * Z_L(33 * 33 * 33) + str[5] * Z_L(33 * 33) + str[6] * Z_L(33) + str[7]; # endif } if (len >= 4) { hash = hash * Z_L(33 * 33 * 33 * 33) + str[0] * Z_L(33 * 33 * 33) + str[1] * Z_L(33 * 33) + str[2] * Z_L(33) + str[3]; len -= 4; str += 4; } if (len >= 2) { if (len > 2) { hash = hash * Z_L(33 * 33 * 33) + str[0] * Z_L(33 * 33) + str[1] * Z_L(33) + str[2]; } else { hash = hash * Z_L(33 * 33) + str[0] * Z_L(33) + str[1]; } } else if (len != 0) { hash = hash * Z_L(33) + *str; } #else /* variant with the hash unrolled eight times */ for (; len >= 8; len -= 8) { hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; hash = ((hash << 5) + hash) + *str++; } switch (len) { case 7: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 6: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 5: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 4: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 3: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 2: hash = ((hash << 5) + hash) + *str++; /* fallthrough... */ case 1: hash = ((hash << 5) + hash) + *str++; break; case 0: break; EMPTY_SWITCH_DEFAULT_CASE() } #endif /* Hash value can't be zero, so we always set the high bit */ #if SIZEOF_ZEND_LONG == 8 return hash | Z_UL(0x8000000000000000); #elif SIZEOF_ZEND_LONG == 4 return hash | Z_UL(0x80000000); #else # error "Unknown SIZEOF_ZEND_LONG" #endif } #define ZEND_KNOWN_STRINGS(_) \ _(ZEND_STR_FILE, "file") \ _(ZEND_STR_LINE, "line") \ _(ZEND_STR_FUNCTION, "function") \ _(ZEND_STR_CLASS, "class") \ _(ZEND_STR_OBJECT, "object") \ _(ZEND_STR_TYPE, "type") \ _(ZEND_STR_OBJECT_OPERATOR, "->") \ _(ZEND_STR_PAAMAYIM_NEKUDOTAYIM, "::") \ _(ZEND_STR_ARGS, "args") \ _(ZEND_STR_UNKNOWN, "unknown") \ _(ZEND_STR_UNKNOWN_CAPITALIZED, "Unknown") \ _(ZEND_STR_EVAL, "eval") \ _(ZEND_STR_INCLUDE, "include") \ _(ZEND_STR_REQUIRE, "require") \ _(ZEND_STR_INCLUDE_ONCE, "include_once") \ _(ZEND_STR_REQUIRE_ONCE, "require_once") \ _(ZEND_STR_SCALAR, "scalar") \ _(ZEND_STR_ERROR_REPORTING, "error_reporting") \ _(ZEND_STR_STATIC, "static") \ _(ZEND_STR_THIS, "this") \ _(ZEND_STR_VALUE, "value") \ _(ZEND_STR_KEY, "key") \ _(ZEND_STR_MAGIC_INVOKE, "__invoke") \ _(ZEND_STR_PREVIOUS, "previous") \ _(ZEND_STR_CODE, "code") \ _(ZEND_STR_MESSAGE, "message") \ _(ZEND_STR_SEVERITY, "severity") \ _(ZEND_STR_STRING, "string") \ _(ZEND_STR_TRACE, "trace") \ _(ZEND_STR_SCHEME, "scheme") \ _(ZEND_STR_HOST, "host") \ _(ZEND_STR_PORT, "port") \ _(ZEND_STR_USER, "user") \ _(ZEND_STR_PASS, "pass") \ _(ZEND_STR_PATH, "path") \ _(ZEND_STR_QUERY, "query") \ _(ZEND_STR_FRAGMENT, "fragment") \ _(ZEND_STR_NULL, "NULL") \ _(ZEND_STR_BOOLEAN, "boolean") \ _(ZEND_STR_INTEGER, "integer") \ _(ZEND_STR_DOUBLE, "double") \ _(ZEND_STR_ARRAY, "array") \ _(ZEND_STR_RESOURCE, "resource") \ _(ZEND_STR_CLOSED_RESOURCE, "resource (closed)") \ _(ZEND_STR_NAME, "name") \ _(ZEND_STR_ARGV, "argv") \ _(ZEND_STR_ARGC, "argc") \ _(ZEND_STR_ARRAY_CAPITALIZED, "Array") \ _(ZEND_STR_BOOL, "bool") \ _(ZEND_STR_INT, "int") \ _(ZEND_STR_FLOAT, "float") \ _(ZEND_STR_CALLABLE, "callable") \ _(ZEND_STR_ITERABLE, "iterable") \ _(ZEND_STR_VOID, "void") \ _(ZEND_STR_NEVER, "never") \ _(ZEND_STR_FALSE, "false") \ _(ZEND_STR_TRUE, "true") \ _(ZEND_STR_NULL_LOWERCASE, "null") \ _(ZEND_STR_MIXED, "mixed") \ _(ZEND_STR_TRAVERSABLE, "Traversable") \ _(ZEND_STR_SLEEP, "__sleep") \ _(ZEND_STR_WAKEUP, "__wakeup") \ _(ZEND_STR_CASES, "cases") \ _(ZEND_STR_FROM, "from") \ _(ZEND_STR_TRYFROM, "tryFrom") \ _(ZEND_STR_TRYFROM_LOWERCASE, "tryfrom") \ _(ZEND_STR_AUTOGLOBAL_SERVER, "_SERVER") \ _(ZEND_STR_AUTOGLOBAL_ENV, "_ENV") \ _(ZEND_STR_AUTOGLOBAL_REQUEST, "_REQUEST") \ _(ZEND_STR_COUNT, "count") \ _(ZEND_STR_SENSITIVEPARAMETER, "SensitiveParameter") \ _(ZEND_STR_CONST_EXPR_PLACEHOLDER, "[constant expression]") \ typedef enum _zend_known_string_id { #define _ZEND_STR_ID(id, str) id, ZEND_KNOWN_STRINGS(_ZEND_STR_ID) #undef _ZEND_STR_ID ZEND_STR_LAST_KNOWN } zend_known_string_id; #endif /* ZEND_STRING_H */
22,404
33.790373
128
h
php-src
php-src-master/Zend/zend_strtod.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <[email protected]> | +----------------------------------------------------------------------+ */ /* This is a header file for the strtod implementation by David M. Gay which * can be found in zend_strtod.c */ #ifndef ZEND_STRTOD_H #define ZEND_STRTOD_H #include <zend.h> BEGIN_EXTERN_C() ZEND_API void zend_freedtoa(char *s); ZEND_API char *zend_dtoa(double _d, int mode, int ndigits, int *decpt, bool *sign, char **rve); ZEND_API char *zend_gcvt(double value, int ndigit, char dec_point, char exponent, char *buf); ZEND_API double zend_strtod(const char *s00, const char **se); ZEND_API double zend_hex_strtod(const char *str, const char **endptr); ZEND_API double zend_oct_strtod(const char *str, const char **endptr); ZEND_API double zend_bin_strtod(const char *str, const char **endptr); ZEND_API int zend_startup_strtod(void); ZEND_API int zend_shutdown_strtod(void); END_EXTERN_C() /* double limits */ #include <float.h> #if defined(DBL_MANT_DIG) && defined(DBL_MIN_EXP) #define ZEND_DOUBLE_MAX_LENGTH (3 + DBL_MANT_DIG - DBL_MIN_EXP) #else #define ZEND_DOUBLE_MAX_LENGTH 1080 #endif #endif
2,151
45.782609
95
h
php-src
php-src-master/Zend/zend_strtod_int.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Anatol Belski <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_STRTOD_INT_H #define ZEND_STRTOD_INT_H #ifdef ZTS #include <TSRM.h> #endif #include <stddef.h> #include <stdio.h> #include <ctype.h> #include <stdarg.h> #include <math.h> #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif /* TODO check to undef this option, this might make more perf. destroy_freelist() should be adapted then. */ #define Omit_Private_Memory 1 /* HEX strings aren't supported as per https://wiki.php.net/rfc/remove_hex_support_in_numeric_strings */ #define NO_HEX_FP 1 #include <inttypes.h> #ifdef USE_LOCALE #undef USE_LOCALE #endif #ifndef NO_INFNAN_CHECK #define NO_INFNAN_CHECK #endif #ifndef NO_ERRNO #define NO_ERRNO #endif #ifdef WORDS_BIGENDIAN #define IEEE_BIG_ENDIAN 1 #else #define IEEE_LITTLE_ENDIAN 1 #endif #if (defined(__APPLE__) || defined(__APPLE_CC__)) && (defined(__BIG_ENDIAN__) || defined(__LITTLE_ENDIAN__)) # if defined(__LITTLE_ENDIAN__) # undef WORDS_BIGENDIAN # else # if defined(__BIG_ENDIAN__) # define WORDS_BIGENDIAN # endif # endif #endif #if defined(__arm__) && !defined(__VFP_FP__) /* * * Although the CPU is little endian the FP has different * * byte and word endianness. The byte order is still little endian * * but the word order is big endian. * */ #define IEEE_BIG_ENDIAN #undef IEEE_LITTLE_ENDIAN #endif #ifdef __vax__ #define VAX #undef IEEE_LITTLE_ENDIAN #endif #ifdef IEEE_LITTLE_ENDIAN #define IEEE_8087 1 #endif #ifdef IEEE_BIG_ENDIAN #define IEEE_MC68k 1 #endif #if defined(_MSC_VER) #ifndef int32_t #define int32_t __int32 #endif #ifndef uint32_t #define uint32_t unsigned __int32 #endif #endif #ifdef ZTS #define MULTIPLE_THREADS 1 #define ACQUIRE_DTOA_LOCK(x) \ if (0 == x) { \ tsrm_mutex_lock(dtoa_mutex); \ } else if (1 == x) { \ tsrm_mutex_lock(pow5mult_mutex); \ } #define FREE_DTOA_LOCK(x) \ if (0 == x) { \ tsrm_mutex_unlock(dtoa_mutex); \ } else if (1 == x) { \ tsrm_mutex_unlock(pow5mult_mutex); \ } #endif #endif /* ZEND_STRTOD_INT_H */
3,135
23.5
108
h
php-src
php-src-master/Zend/zend_system_id.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Sammy Kaye Powers <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_SYSTEM_ID_H #define ZEND_SYSTEM_ID_H BEGIN_EXTERN_C() /* True global; Write-only during MINIT/startup */ extern ZEND_API char zend_system_id[32]; ZEND_API ZEND_RESULT_CODE zend_add_system_entropy(const char *module_name, const char *hook_name, const void *data, size_t size); END_EXTERN_C() void zend_startup_system_id(void); void zend_finalize_system_id(void); #endif /* ZEND_SYSTEM_ID_H */
1,404
44.322581
129
h
php-src
php-src-master/Zend/zend_variables.c
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #include <stdio.h> #include "zend.h" #include "zend_API.h" #include "zend_ast.h" #include "zend_globals.h" #include "zend_constants.h" #include "zend_list.h" #if ZEND_DEBUG static void ZEND_FASTCALL zend_string_destroy(zend_string *str); #else # define zend_string_destroy _efree #endif static void ZEND_FASTCALL zend_reference_destroy(zend_reference *ref); static void ZEND_FASTCALL zend_empty_destroy(zend_reference *ref); typedef void (ZEND_FASTCALL *zend_rc_dtor_func_t)(zend_refcounted *p); static const zend_rc_dtor_func_t zend_rc_dtor_func[] = { [IS_UNDEF] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_NULL] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_FALSE] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_TRUE] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_LONG] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_DOUBLE] = (zend_rc_dtor_func_t)zend_empty_destroy, [IS_STRING] = (zend_rc_dtor_func_t)zend_string_destroy, [IS_ARRAY] = (zend_rc_dtor_func_t)zend_array_destroy, [IS_OBJECT] = (zend_rc_dtor_func_t)zend_objects_store_del, [IS_RESOURCE] = (zend_rc_dtor_func_t)zend_list_free, [IS_REFERENCE] = (zend_rc_dtor_func_t)zend_reference_destroy, [IS_CONSTANT_AST] = (zend_rc_dtor_func_t)zend_ast_ref_destroy }; ZEND_API void ZEND_FASTCALL rc_dtor_func(zend_refcounted *p) { ZEND_ASSERT(GC_TYPE(p) <= IS_CONSTANT_AST); zend_rc_dtor_func[GC_TYPE(p)](p); } #if ZEND_DEBUG static void ZEND_FASTCALL zend_string_destroy(zend_string *str) { CHECK_ZVAL_STRING(str); ZEND_ASSERT(!ZSTR_IS_INTERNED(str)); ZEND_ASSERT(GC_REFCOUNT(str) == 0); ZEND_ASSERT(!(GC_FLAGS(str) & IS_STR_PERSISTENT)); efree(str); } #endif static void ZEND_FASTCALL zend_reference_destroy(zend_reference *ref) { ZEND_ASSERT(!ZEND_REF_HAS_TYPE_SOURCES(ref)); i_zval_ptr_dtor(&ref->val); efree_size(ref, sizeof(zend_reference)); } static void ZEND_FASTCALL zend_empty_destroy(zend_reference *ref) { } ZEND_API void zval_ptr_dtor(zval *zval_ptr) /* {{{ */ { i_zval_ptr_dtor(zval_ptr); } /* }}} */ ZEND_API void zval_internal_ptr_dtor(zval *zval_ptr) /* {{{ */ { if (Z_REFCOUNTED_P(zval_ptr)) { zend_refcounted *ref = Z_COUNTED_P(zval_ptr); if (GC_DELREF(ref) == 0) { if (Z_TYPE_P(zval_ptr) == IS_STRING) { zend_string *str = (zend_string*)ref; CHECK_ZVAL_STRING(str); ZEND_ASSERT(!ZSTR_IS_INTERNED(str)); ZEND_ASSERT((GC_FLAGS(str) & IS_STR_PERSISTENT)); free(str); } else { zend_error_noreturn(E_CORE_ERROR, "Internal zval's can't be arrays, objects, resources or reference"); } } } } /* }}} */ /* This function should only be used as a copy constructor, i.e. it * should only be called AFTER a zval has been copied to another * location using ZVAL_COPY_VALUE. Do not call it before copying, * otherwise a reference may be leaked. */ ZEND_API void zval_add_ref(zval *p) { if (Z_REFCOUNTED_P(p)) { if (Z_ISREF_P(p) && Z_REFCOUNT_P(p) == 1) { ZVAL_COPY(p, Z_REFVAL_P(p)); } else { Z_ADDREF_P(p); } } } ZEND_API void ZEND_FASTCALL zval_copy_ctor_func(zval *zvalue) { if (EXPECTED(Z_TYPE_P(zvalue) == IS_ARRAY)) { ZVAL_ARR(zvalue, zend_array_dup(Z_ARRVAL_P(zvalue))); } else if (EXPECTED(Z_TYPE_P(zvalue) == IS_STRING)) { ZEND_ASSERT(!ZSTR_IS_INTERNED(Z_STR_P(zvalue))); CHECK_ZVAL_STRING(Z_STR_P(zvalue)); ZVAL_NEW_STR(zvalue, zend_string_dup(Z_STR_P(zvalue), 0)); } else { ZEND_UNREACHABLE(); } }
4,747
33.911765
106
c
php-src
php-src-master/Zend/zend_variables.h
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Zeev Suraski <[email protected]> | | Dmitry Stogov <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef ZEND_VARIABLES_H #define ZEND_VARIABLES_H #include "zend_types.h" #include "zend_gc.h" BEGIN_EXTERN_C() ZEND_API void ZEND_FASTCALL rc_dtor_func(zend_refcounted *p); ZEND_API void ZEND_FASTCALL zval_copy_ctor_func(zval *zvalue); static zend_always_inline void zval_ptr_dtor_nogc(zval *zval_ptr) { if (Z_REFCOUNTED_P(zval_ptr) && !Z_DELREF_P(zval_ptr)) { rc_dtor_func(Z_COUNTED_P(zval_ptr)); } } static zend_always_inline void i_zval_ptr_dtor(zval *zval_ptr) { if (Z_REFCOUNTED_P(zval_ptr)) { zend_refcounted *ref = Z_COUNTED_P(zval_ptr); if (!GC_DELREF(ref)) { rc_dtor_func(ref); } else { gc_check_possible_root(ref); } } } static zend_always_inline void zval_copy_ctor(zval *zvalue) { if (Z_TYPE_P(zvalue) == IS_ARRAY) { ZVAL_ARR(zvalue, zend_array_dup(Z_ARR_P(zvalue))); } else if (Z_REFCOUNTED_P(zvalue)) { Z_ADDREF_P(zvalue); } } static zend_always_inline void zval_opt_copy_ctor(zval *zvalue) { if (Z_OPT_TYPE_P(zvalue) == IS_ARRAY) { ZVAL_ARR(zvalue, zend_array_dup(Z_ARR_P(zvalue))); } else if (Z_OPT_REFCOUNTED_P(zvalue)) { Z_ADDREF_P(zvalue); } } static zend_always_inline void zval_ptr_dtor_str(zval *zval_ptr) { if (Z_REFCOUNTED_P(zval_ptr) && !Z_DELREF_P(zval_ptr)) { ZEND_ASSERT(Z_TYPE_P(zval_ptr) == IS_STRING); ZEND_ASSERT(!ZSTR_IS_INTERNED(Z_STR_P(zval_ptr))); ZEND_ASSERT(!(GC_FLAGS(Z_STR_P(zval_ptr)) & IS_STR_PERSISTENT)); efree(Z_STR_P(zval_ptr)); } } ZEND_API void zval_ptr_dtor(zval *zval_ptr); ZEND_API void zval_internal_ptr_dtor(zval *zvalue); /* Kept for compatibility */ #define zval_dtor(zvalue) zval_ptr_dtor_nogc(zvalue) ZEND_API void zval_add_ref(zval *p); END_EXTERN_C() #define ZVAL_PTR_DTOR zval_ptr_dtor #define ZVAL_INTERNAL_PTR_DTOR zval_internal_ptr_dtor #endif
3,065
31.967742
75
h
php-src
php-src-master/Zend/zend_virtual_cwd.h
/* +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | https://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <[email protected]> | | Sascha Schumann <[email protected]> | | Pierre Joye <[email protected]> | +----------------------------------------------------------------------+ */ #ifndef VIRTUAL_CWD_H #define VIRTUAL_CWD_H #include "TSRM.h" #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #ifdef HAVE_UTIME_H #include <utime.h> #endif #include <stdarg.h> #include <limits.h> #if HAVE_SYS_PARAM_H # include <sys/param.h> #endif #ifndef MAXPATHLEN # if _WIN32 # include "win32/ioutil.h" # define MAXPATHLEN PHP_WIN32_IOUTIL_MAXPATHLEN # elif PATH_MAX # define MAXPATHLEN PATH_MAX # elif defined(MAX_PATH) # define MAXPATHLEN MAX_PATH # else # define MAXPATHLEN 256 # endif #endif #ifdef ZTS #define VIRTUAL_DIR #endif #ifndef ZEND_WIN32 #include <unistd.h> #else #include <direct.h> #endif #if defined(__osf__) || defined(_AIX) #include <errno.h> #endif #ifdef ZEND_WIN32 #include "win32/readdir.h" #include <sys/utime.h> #include "win32/ioutil.h" /* mode_t isn't defined on Windows */ typedef unsigned short mode_t; #define DEFAULT_SLASH '\\' #define DEFAULT_DIR_SEPARATOR ';' #define IS_SLASH(c) ((c) == '/' || (c) == '\\') #define IS_SLASH_P(c) (*(c) == '/' || \ (*(c) == '\\' && !IsDBCSLeadByte(*(c-1)))) /* COPY_WHEN_ABSOLUTE is 2 under Win32 because by chance both regular absolute paths in the file system and UNC paths need copying of two characters */ #define COPY_WHEN_ABSOLUTE(path) 2 #define IS_UNC_PATH(path, len) \ (len >= 2 && IS_SLASH(path[0]) && IS_SLASH(path[1])) #define IS_ABSOLUTE_PATH(path, len) \ (len >= 2 && (/* is local */isalpha(path[0]) && path[1] == ':' || /* is UNC */IS_SLASH(path[0]) && IS_SLASH(path[1]))) #else #ifdef HAVE_DIRENT_H #include <dirent.h> #ifndef DT_UNKNOWN # define DT_UNKNOWN 0 #endif #ifndef DT_DIR # define DT_DIR 4 #endif #ifndef DT_REG # define DT_REG 8 #endif #endif #define DEFAULT_SLASH '/' #ifdef __riscos__ #define DEFAULT_DIR_SEPARATOR ';' #else #define DEFAULT_DIR_SEPARATOR ':' #endif #define IS_SLASH(c) ((c) == '/') #define IS_SLASH_P(c) (*(c) == '/') #endif #ifndef COPY_WHEN_ABSOLUTE #define COPY_WHEN_ABSOLUTE(path) 0 #endif #ifndef IS_ABSOLUTE_PATH #define IS_ABSOLUTE_PATH(path, len) \ (IS_SLASH(path[0])) #endif #ifdef TSRM_EXPORTS #define CWD_EXPORTS #endif #ifdef ZEND_WIN32 # ifdef CWD_EXPORTS # define CWD_API __declspec(dllexport) # else # define CWD_API __declspec(dllimport) # endif #elif defined(__GNUC__) && __GNUC__ >= 4 # define CWD_API __attribute__ ((visibility("default"))) #else # define CWD_API #endif #ifdef ZEND_WIN32 # define php_sys_stat_ex php_win32_ioutil_stat_ex # define php_sys_stat php_win32_ioutil_stat # define php_sys_lstat php_win32_ioutil_lstat # define php_sys_fstat php_win32_ioutil_fstat # define php_sys_readlink php_win32_ioutil_readlink # define php_sys_symlink php_win32_ioutil_symlink # define php_sys_link php_win32_ioutil_link #else # define php_sys_stat stat # define php_sys_lstat lstat # define php_sys_fstat fstat # ifdef HAVE_SYMLINK # define php_sys_readlink(link, target, target_len) readlink(link, target, target_len) # define php_sys_symlink symlink # define php_sys_link link # endif #endif typedef struct _cwd_state { char *cwd; size_t cwd_length; } cwd_state; typedef int (*verify_path_func)(const cwd_state *); CWD_API void virtual_cwd_startup(void); CWD_API void virtual_cwd_shutdown(void); CWD_API int virtual_cwd_activate(void); CWD_API int virtual_cwd_deactivate(void); CWD_API char *virtual_getcwd_ex(size_t *length); CWD_API char *virtual_getcwd(char *buf, size_t size); CWD_API zend_result virtual_chdir(const char *path); CWD_API int virtual_chdir_file(const char *path, int (*p_chdir)(const char *path)); CWD_API int virtual_filepath(const char *path, char **filepath); CWD_API int virtual_filepath_ex(const char *path, char **filepath, verify_path_func verify_path); CWD_API char *virtual_realpath(const char *path, char *real_path); CWD_API FILE *virtual_fopen(const char *path, const char *mode); CWD_API int virtual_open(const char *path, int flags, ...); CWD_API int virtual_creat(const char *path, mode_t mode); CWD_API int virtual_rename(const char *oldname, const char *newname); CWD_API int virtual_stat(const char *path, zend_stat_t *buf); CWD_API int virtual_lstat(const char *path, zend_stat_t *buf); CWD_API int virtual_unlink(const char *path); CWD_API int virtual_mkdir(const char *pathname, mode_t mode); CWD_API int virtual_rmdir(const char *pathname); CWD_API DIR *virtual_opendir(const char *pathname); CWD_API FILE *virtual_popen(const char *command, const char *type); CWD_API int virtual_access(const char *pathname, int mode); #if HAVE_UTIME CWD_API int virtual_utime(const char *filename, struct utimbuf *buf); #endif CWD_API int virtual_chmod(const char *filename, mode_t mode); #if !defined(ZEND_WIN32) CWD_API int virtual_chown(const char *filename, uid_t owner, gid_t group, int link); #endif /* One of the following constants must be used as the last argument in virtual_file_ex() call. */ // TODO Make this into an enum #define CWD_EXPAND 0 /* expand "." and ".." but don't resolve symlinks */ #define CWD_FILEPATH 1 /* resolve symlinks if file is exist otherwise expand */ #define CWD_REALPATH 2 /* call realpath(), resolve symlinks. File must exist */ CWD_API int virtual_file_ex(cwd_state *state, const char *path, verify_path_func verify_path, int use_realpath); CWD_API char *tsrm_realpath(const char *path, char *real_path); #define REALPATH_CACHE_TTL (2*60) /* 2 minutes */ #define REALPATH_CACHE_SIZE 0 /* disabled while php.ini isn't loaded */ typedef struct _realpath_cache_bucket { zend_ulong key; char *path; char *realpath; struct _realpath_cache_bucket *next; time_t expires; uint16_t path_len; uint16_t realpath_len; uint8_t is_dir:1; #ifdef ZEND_WIN32 uint8_t is_rvalid:1; uint8_t is_readable:1; uint8_t is_wvalid:1; uint8_t is_writable:1; #endif } realpath_cache_bucket; typedef struct _virtual_cwd_globals { cwd_state cwd; zend_long realpath_cache_size; zend_long realpath_cache_size_limit; zend_long realpath_cache_ttl; realpath_cache_bucket *realpath_cache[1024]; } virtual_cwd_globals; #ifdef ZTS extern ts_rsrc_id cwd_globals_id; extern size_t cwd_globals_offset; # define CWDG(v) ZEND_TSRMG_FAST(cwd_globals_offset, virtual_cwd_globals *, v) #else extern virtual_cwd_globals cwd_globals; # define CWDG(v) (cwd_globals.v) #endif CWD_API void realpath_cache_clean(void); CWD_API void realpath_cache_del(const char *path, size_t path_len); CWD_API realpath_cache_bucket* realpath_cache_lookup(const char *path, size_t path_len, time_t t); CWD_API zend_long realpath_cache_size(void); CWD_API zend_long realpath_cache_max_buckets(void); CWD_API realpath_cache_bucket** realpath_cache_get_buckets(void); #ifdef CWD_EXPORTS extern void virtual_cwd_main_cwd_init(uint8_t); #endif /* The actual macros to be used in programs using TSRM * If the program defines VIRTUAL_DIR it will use the * virtual_* functions */ #ifdef VIRTUAL_DIR #define VCWD_GETCWD(buff, size) virtual_getcwd(buff, size) #define VCWD_FOPEN(path, mode) virtual_fopen(path, mode) /* Because open() has two modes, we have to macros to replace it */ #define VCWD_OPEN(path, flags) virtual_open(path, flags) #define VCWD_OPEN_MODE(path, flags, mode) virtual_open(path, flags, mode) #define VCWD_CREAT(path, mode) virtual_creat(path, mode) #define VCWD_CHDIR(path) virtual_chdir(path) #define VCWD_CHDIR_FILE(path) virtual_chdir_file(path, (int (*)(const char *)) virtual_chdir) #define VCWD_GETWD(buf) #define VCWD_REALPATH(path, real_path) virtual_realpath(path, real_path) #define VCWD_RENAME(oldname, newname) virtual_rename(oldname, newname) #define VCWD_STAT(path, buff) virtual_stat(path, buff) # define VCWD_LSTAT(path, buff) virtual_lstat(path, buff) #define VCWD_UNLINK(path) virtual_unlink(path) #define VCWD_MKDIR(pathname, mode) virtual_mkdir(pathname, mode) #define VCWD_RMDIR(pathname) virtual_rmdir(pathname) #define VCWD_OPENDIR(pathname) virtual_opendir(pathname) #define VCWD_POPEN(command, type) virtual_popen(command, type) #define VCWD_ACCESS(pathname, mode) virtual_access(pathname, mode) #if HAVE_UTIME #define VCWD_UTIME(path, time) virtual_utime(path, time) #endif #define VCWD_CHMOD(path, mode) virtual_chmod(path, mode) #if !defined(ZEND_WIN32) #define VCWD_CHOWN(path, owner, group) virtual_chown(path, owner, group, 0) #if HAVE_LCHOWN #define VCWD_LCHOWN(path, owner, group) virtual_chown(path, owner, group, 1) #endif #endif #else #define VCWD_CREAT(path, mode) creat(path, mode) /* rename on windows will fail if newname already exists. MoveFileEx has to be used */ #if defined(ZEND_WIN32) #define VCWD_FOPEN(path, mode) php_win32_ioutil_fopen(path, mode) #define VCWD_OPEN(path, flags) php_win32_ioutil_open(path, flags) #define VCWD_OPEN_MODE(path, flags, mode) php_win32_ioutil_open(path, flags, mode) # define VCWD_RENAME(oldname, newname) php_win32_ioutil_rename(oldname, newname) #define VCWD_MKDIR(pathname, mode) php_win32_ioutil_mkdir(pathname, mode) #define VCWD_RMDIR(pathname) php_win32_ioutil_rmdir(pathname) #define VCWD_UNLINK(path) php_win32_ioutil_unlink(path) #define VCWD_CHDIR(path) php_win32_ioutil_chdir(path) #define VCWD_ACCESS(pathname, mode) tsrm_win32_access(pathname, mode) #define VCWD_GETCWD(buff, size) php_win32_ioutil_getcwd(buff, size) #define VCWD_CHMOD(path, mode) php_win32_ioutil_chmod(path, mode) #else #define VCWD_FOPEN(path, mode) fopen(path, mode) #define VCWD_OPEN(path, flags) open(path, flags) #define VCWD_OPEN_MODE(path, flags, mode) open(path, flags, mode) # define VCWD_RENAME(oldname, newname) rename(oldname, newname) #define VCWD_MKDIR(pathname, mode) mkdir(pathname, mode) #define VCWD_RMDIR(pathname) rmdir(pathname) #define VCWD_UNLINK(path) unlink(path) #define VCWD_CHDIR(path) chdir(path) #define VCWD_ACCESS(pathname, mode) access(pathname, mode) #define VCWD_GETCWD(buff, size) getcwd(buff, size) #define VCWD_CHMOD(path, mode) chmod(path, mode) #endif #define VCWD_CHDIR_FILE(path) virtual_chdir_file(path, chdir) #define VCWD_GETWD(buf) getwd(buf) #define VCWD_STAT(path, buff) php_sys_stat(path, buff) #define VCWD_LSTAT(path, buff) lstat(path, buff) #define VCWD_OPENDIR(pathname) opendir(pathname) #define VCWD_POPEN(command, type) popen(command, type) #define VCWD_REALPATH(path, real_path) tsrm_realpath(path, real_path) #if HAVE_UTIME # ifdef ZEND_WIN32 # define VCWD_UTIME(path, time) win32_utime(path, time) # else # define VCWD_UTIME(path, time) utime(path, time) # endif #endif #if !defined(ZEND_WIN32) #define VCWD_CHOWN(path, owner, group) chown(path, owner, group) #if HAVE_LCHOWN #define VCWD_LCHOWN(path, owner, group) lchown(path, owner, group) #endif #endif #endif /* Global stat declarations */ #ifndef _S_IFDIR #define _S_IFDIR S_IFDIR #endif #ifndef _S_IFREG #define _S_IFREG S_IFREG #endif #ifndef S_IFLNK #define _IFLNK 0120000 /* symbolic link */ #define S_IFLNK _IFLNK #endif #ifndef S_ISDIR #define S_ISDIR(mode) (((mode)&S_IFMT) == S_IFDIR) #endif #ifndef S_ISREG #define S_ISREG(mode) (((mode)&S_IFMT) == S_IFREG) #endif #ifndef S_ISLNK #define S_ISLNK(mode) (((mode)&S_IFMT) == S_IFLNK) #endif #ifndef S_IXROOT #define S_IXROOT ( S_IXUSR | S_IXGRP | S_IXOTH ) #endif /* XXX should be _S_IFIFO? */ #ifndef S_IFIFO #define _IFIFO 0010000 /* fifo */ #define S_IFIFO _IFIFO #endif #ifndef S_IFBLK #define _IFBLK 0060000 /* block special */ #define S_IFBLK _IFBLK #endif #endif /* VIRTUAL_CWD_H */
12,774
31.341772
119
h