OILS / cpp / stdlib.cc View on Github | oils.pub

257 lines, 144 significant
1// stdlib.cc: Replacement for standard library modules
2// and native/posixmodule.c
3
4#include "stdlib.h"
5
6#include <dirent.h> // closedir(), opendir(), readdir()
7#include <errno.h>
8#include <fcntl.h> // open
9#include <math.h> // isinf, isnan
10#include <signal.h> // kill
11#include <sys/stat.h> // umask
12#include <sys/types.h> // umask
13#include <sys/wait.h> // WUNTRACED
14#include <time.h>
15#include <unistd.h>
16
17#include "mycpp/runtime.h"
18// To avoid circular dependency with e_die()
19#include "prebuilt/core/error.mycpp.h"
20
21using error::e_die;
22
23namespace fcntl_ {
24
25int fcntl(int fd, int cmd) {
26 int result = ::fcntl(fd, cmd);
27 if (result < 0) {
28 throw Alloc<IOError>(errno);
29 }
30 return result;
31}
32
33int fcntl(int fd, int cmd, int arg) {
34 int result = ::fcntl(fd, cmd, arg);
35 if (result < 0) {
36 throw Alloc<IOError>(errno);
37 }
38 return result;
39}
40
41} // namespace fcntl_
42
43namespace posix {
44
45mode_t umask(mode_t mask) {
46 // No error case: always succeeds
47 return ::umask(mask);
48}
49
50int open(BigStr* path, int flags, int perms) {
51 int result = ::open(path->data_, flags, perms);
52 if (result < 0) {
53 throw Alloc<OSError>(errno);
54 }
55 return result;
56}
57
58void dup2(int oldfd, int newfd) {
59 if (::dup2(oldfd, newfd) < 0) {
60 throw Alloc<OSError>(errno);
61 }
62}
63void putenv(BigStr* name, BigStr* value) {
64 int overwrite = 1;
65 int ret = ::setenv(name->data_, value->data_, overwrite);
66 if (ret < 0) {
67 throw Alloc<IOError>(errno);
68 }
69}
70
71mylib::File* fdopen(int fd, BigStr* c_mode) {
72 // CPython checks if it's a directory first
73
74 struct stat buf;
75 if (fstat(fd, &buf) == 0 && S_ISDIR(buf.st_mode)) {
76 throw Alloc<OSError>(EISDIR);
77 }
78
79 return Alloc<mylib::CFile>(fd);
80}
81
82void execve(BigStr* argv0, List<BigStr*>* argv,
83 Dict<BigStr*, BigStr*>* environ) {
84 int n_args = len(argv);
85 int n_env = len(environ);
86 int combined_size = 0;
87 for (DictIter<BigStr*, BigStr*> it(environ); !it.Done(); it.Next()) {
88 BigStr* k = it.Key();
89 BigStr* v = it.Value();
90
91 int joined_len = len(k) + len(v) + 2; // = and NUL terminator
92 combined_size += joined_len;
93 }
94 const int argv_size = (n_args + 1) * sizeof(char*);
95 const int env_size = (n_env + 1) * sizeof(char*);
96 combined_size += argv_size;
97 combined_size += env_size;
98 char* combined_buf = static_cast<char*>(malloc(combined_size));
99
100 // never deallocated
101 char** _argv = reinterpret_cast<char**>(combined_buf);
102 combined_buf += argv_size;
103
104 // Annoying const_cast
105 // https://stackoverflow.com/questions/190184/execv-and-const-ness
106 for (int i = 0; i < n_args; ++i) {
107 _argv[i] = const_cast<char*>(argv->at(i)->data_);
108 }
109 _argv[n_args] = nullptr;
110
111 // Convert environ into an array of pointers to strings of the form: "k=v".
112 char** envp = reinterpret_cast<char**>(combined_buf);
113 combined_buf += env_size;
114 int env_index = 0;
115 for (DictIter<BigStr*, BigStr*> it(environ); !it.Done(); it.Next()) {
116 BigStr* k = it.Key();
117 BigStr* v = it.Value();
118
119 char* buf = combined_buf;
120 int joined_len = len(k) + len(v) + 1;
121 combined_buf += joined_len + 1;
122 memcpy(buf, k->data_, len(k));
123 buf[len(k)] = '=';
124 memcpy(buf + len(k) + 1, v->data_, len(v));
125 buf[joined_len] = '\0';
126
127 envp[env_index++] = buf;
128 }
129 envp[n_env] = nullptr;
130
131 int ret = ::execve(argv0->data_, _argv, envp);
132 if (ret == -1) {
133 throw Alloc<OSError>(errno);
134 }
135
136 // ::execve() never returns on success
137 FAIL(kShouldNotGetHere);
138}
139
140void kill(int pid, int sig) {
141 if (::kill(pid, sig) != 0) {
142 throw Alloc<OSError>(errno);
143 }
144}
145
146void killpg(int pgid, int sig) {
147 if (::killpg(pgid, sig) != 0) {
148 throw Alloc<OSError>(errno);
149 }
150}
151
152List<BigStr*>* listdir(BigStr* path) {
153 DIR* dirp = opendir(path->data());
154 if (dirp == NULL) {
155 throw Alloc<OSError>(errno);
156 }
157
158 auto* ret = Alloc<List<BigStr*>>();
159 while (true) {
160 errno = 0;
161 struct dirent* ep = readdir(dirp);
162 if (ep == NULL) {
163 if (errno != 0) {
164 closedir(dirp);
165 throw Alloc<OSError>(errno);
166 }
167 break; // no more files
168 }
169 // Skip . and ..
170 int name_len = strlen(ep->d_name);
171 if (ep->d_name[0] == '.' &&
172 (name_len == 1 || (ep->d_name[1] == '.' && name_len == 2))) {
173 continue;
174 }
175 ret->append(StrFromC(ep->d_name, name_len));
176 }
177
178 closedir(dirp);
179
180 return ret;
181}
182
183} // namespace posix
184
185namespace time_ {
186
187void tzset() {
188 // No error case: no return value
189 ::tzset();
190}
191
192double time() {
193 struct timespec spec;
194 // Get current time
195 if (clock_gettime(CLOCK_REALTIME, &spec) == -1) {
196 throw Alloc<IOError>(errno);
197 }
198 return static_cast<double>(spec.tv_sec) +
199 static_cast<double>(spec.tv_nsec) / 1e9;
200}
201
202// NOTE(Jesse): time_t is specified to be an arithmetic type by C++. On most
203// systems it's a 64-bit integer. 64 bits is used because 32 will overflow in
204// 2038. Someone on a committee somewhere thought of that when moving to
205// 64-bit architectures to prevent breaking ABI again; on 32-bit systems it's
206// usually 32 bits. Point being, using anything but the time_t typedef here
207// could (unlikely, but possible) produce weird behavior.
208time_t localtime(time_t ts) {
209 // localtime returns a pointer to a static buffer
210 tm* loc_time = ::localtime(&ts);
211
212 time_t result = mktime(loc_time);
213 if (result < 0) {
214 throw Alloc<IOError>(errno);
215 }
216 return result;
217}
218
219BigStr* strftime(BigStr* s, time_t ts) {
220 tm* loc_time = ::localtime(&ts);
221
222 const int max_len = 1024;
223 BigStr* result = OverAllocatedStr(max_len);
224 int n = strftime(result->data(), max_len, s->data_, loc_time);
225 if (n == 0) {
226 // bash silently truncates on large format string like
227 // printf '%(%Y)T'
228 // Oils doesn't mask errors
229 // Leaving out location info points to 'printf' builtin
230
231 e_die(StrFromC("strftime() result exceeds 1024 bytes"));
232 }
233 result->MaybeShrink(n);
234 return result;
235}
236
237// Used by TestAction in core/completion.py - not really necessary
238void sleep(double seconds) {
239 struct timespec req, rem;
240 req.tv_sec = (time_t)seconds;
241 req.tv_nsec = (long)((seconds - req.tv_sec) * 1000000000);
242
243 // Note: Python 2.7 floatsleep() uses select()
244 while (nanosleep(&req, &rem) == -1) {
245 // log("nano errno %d", errno);
246 if (errno == EINTR) {
247 req = rem; // keep sleeping
248 } else {
249 // Ignore other errors
250 // log("nano other break");
251 break;
252 }
253 }
254 // log("nano done");
255}
256
257} // namespace time_