1 /*
2  * Copyright (c) 2018 Intel Corporation
3  * Copyright (c) 2023 Meta
4  * Copyright (c) 2025 Tenstorrent AI ULC
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <errno.h>
10 #include <string.h>
11 #include <sys/time.h>
12 #include <time.h>
13 
14 #include <zephyr/drivers/hwinfo.h>
15 #include <zephyr/kernel.h>
16 #include <zephyr/logging/log.h>
17 #include <zephyr/sys_clock.h>
18 #include <zephyr/sys/clock.h>
19 #include <zephyr/toolchain.h>
20 
21 LOG_MODULE_REGISTER(xsi_single_process, CONFIG_XSI_SINGLE_PROCESS_LOG_LEVEL);
22 
23 extern int z_setenv(const char *name, const char *val, int overwrite);
24 
gethostid(void)25 long gethostid(void)
26 {
27 	int rc;
28 	uint32_t buf = 0;
29 
30 	rc = hwinfo_get_device_id((uint8_t *)&buf, sizeof(buf));
31 	if ((rc < 0) || (rc != sizeof(buf)) || (buf == 0)) {
32 		LOG_DBG("%s() failed: %d", "hwinfo_get_device_id", rc);
33 		return (long)rc;
34 	}
35 
36 	return (long)buf;
37 }
38 
gettimeofday(struct timeval * tv,void * tz)39 int gettimeofday(struct timeval *tv, void *tz)
40 {
41 	struct timespec ts;
42 	int res;
43 
44 	/*
45 	 * As per POSIX, "if tzp is not a null pointer, the behavior is unspecified."  "tzp" is the
46 	 * "tz" parameter above.
47 	 */
48 	ARG_UNUSED(tz);
49 
50 	res = sys_clock_gettime(SYS_CLOCK_REALTIME, &ts);
51 	if (res < 0) {
52 		LOG_DBG("%s() failed: %d", "sys_clock_gettime", res);
53 		errno = -res;
54 		return -1;
55 	}
56 
57 	tv->tv_sec = ts.tv_sec;
58 	tv->tv_usec = ts.tv_nsec / NSEC_PER_USEC;
59 
60 	return 0;
61 }
62 
putenv(char * string)63 int putenv(char *string)
64 {
65 	if (string == NULL) {
66 		errno = EINVAL;
67 		return -1;
68 	}
69 
70 	char *const name = string;
71 
72 	for (char *val = name; *val != '\0'; ++val) {
73 		if (*val == '=') {
74 			int rc;
75 
76 			*val = '\0';
77 			++val;
78 			rc = z_setenv(name, val, 1);
79 			--val;
80 			*val = '=';
81 
82 			if (rc < 0) {
83 				LOG_DBG("%s() failed: %d", "setenv", rc);
84 				return rc;
85 			}
86 
87 			return 0;
88 		}
89 	}
90 
91 	/* was unable to find '=' in string */
92 	errno = EINVAL;
93 	return -1;
94 }
95