Debian Codegraph @

js/src/shell/OSObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 // OSObject.h - os object for exposing posix system calls in the JS shell
8
9 #include "shell/OSObject.h"
10
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/ScopeExit.h"
13 #include "mozilla/TextUtils.h"
14
15 #include <errno.h>
16 #include <stdlib.h>
17 #ifdef XP_WIN
18 # include <direct.h>
19 # include <process.h>
20 # include <string.h>
21 # include <wchar.h>
22 # include "util/WindowsWrapper.h"
23 #elif __wasi__
24 # include <dirent.h>
25 # include <sys/types.h>
26 # include <unistd.h>
27 #else
28 # include <dirent.h>
29 # include <sys/types.h>
30 # include <sys/wait.h>
31 # include <unistd.h>
32 #endif
33
34 #include "jsapi.h"
35 // For JSFunctionSpecWithHelp
36 #include "jsfriendapi.h"
37
38 #include "gc/GCContext.h"
39 #include "js/CharacterEncoding.h"
40 #include "js/Conversions.h"
41 #include "js/experimental/TypedData.h" // JS_NewUint8Array
42 #include "js/Object.h" // JS::GetReservedSlot
43 #include "js/PropertyAndElement.h" // JS_DefineProperty
44 #include "js/PropertySpec.h"
45 #include "js/Value.h" // JS::Value
46 #include "js/Wrapper.h"
47 #include "shell/jsshell.h"
48 #include "shell/StringUtils.h"
49 #include "util/GetPidProvider.h" // getpid()
50 #include "util/StringBuilder.h"
51 #include "util/Text.h"
52 #include "util/WindowsWrapper.h"
53 #include "vm/JSObject.h"
54 #include "vm/TypedArrayObject.h"
55
56 #include "vm/JSObject-inl.h"
57
58 #ifdef XP_WIN
59 # ifndef PATH_MAX
60 # define PATH_MAX (MAX_PATH > _MAX_DIR ? MAX_PATH : _MAX_DIR)
61 # endif
62 # define getcwd _getcwd
63 #elif defined(__wasi__)
64 // Nothing.
65 #else
66 # include <libgen.h>
67 #endif
68
69 using js::shell::RCFile;
70
71 namespace js {
72 namespace shell {
73
74 bool IsAbsolutePath(JSLinearString* filename) {
75 size_t length = filename->length();
76
77 #ifdef XP_WIN
78 // On Windows there are various forms of absolute paths (see
79 // http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
80 // for details):
81 //
82 // "\..."
83 // "\\..."
84 // "C:\..."
85 //
86 // The first two cases are handled by the common test below so we only need a
87 // specific test for the last one here.
88
89 if (length > 3 && mozilla::IsAsciiAlpha(CharAt(filename, 0)) &&
90 CharAt(filename, 1) == u':' && CharAt(filename, 2) == u'\\') {
91 return true;
92 }
93 #endif
94
95 return length > 0 && CharAt(filename, 0) == PathSeparator;
96 }
97
98 static UniqueChars DirectoryName(JSContext* cx, const char* path) {
99 #ifdef XP_WIN
100 UniqueWideChars widePath = JS::EncodeUtf8ToWide(cx, path);
101 if (!widePath) {
102 return nullptr;
103 }
104
105 wchar_t dirName[PATH_MAX + 1];
106 wchar_t* drive = nullptr;
107 wchar_t* fileName = nullptr;
108 wchar_t* fileExt = nullptr;
109
110 // The docs say it can return EINVAL, but the compiler says it's void
111 _wsplitpath(widePath.get(), drive, dirName, fileName, fileExt);
112
113 return JS::EncodeWideToUtf8(cx, dirName);
114 #else
115 UniqueChars narrowPath = JS::EncodeUtf8ToNarrow(cx, path);
116 if (!narrowPath) {
117 return nullptr;
118 }
119
120 char dirName[PATH_MAX + 1];
121 strncpy(dirName, narrowPath.get(), PATH_MAX);
122 if (dirName[PATH_MAX - 1] != '\0') {
123 JS_ReportErrorASCII(cx, "Path is too long");
124 return nullptr;
125 }
126
127 # ifdef __wasi__
128 // dirname() seems not to behave properly with wasi-libc; so we do our own
129 // simple thing here.
130 char* p = dirName + strlen(dirName);
131 bool found = false;
132 while (p > dirName) {
133 if (*p == '/') {
134 found = true;
135 *p = '\0';
136 break;
137 }
138 p--;
139 }
140 if (!found) {
141 // There's no '/'. Possible cases are the following:
142 // * "."
143 // * ".."
144 // * filename only
145 //
146 // dirname() returns "." for all cases.
147 dirName[0] = '.';
148 dirName[1] = '\0';
149 }
150 # else
151 // dirname(dirName) might return dirName, or it might return a
152 // statically-allocated string
153 memmove(dirName, dirname(dirName), strlen(dirName) + 1);
154 # endif
155
156 return JS::EncodeNarrowToUtf8(cx, dirName);
157 #endif
158 }
159
160 /*
161 * Resolve a (possibly) relative filename to an absolute path. If
162 * |scriptRelative| is true, then the result will be relative to the directory
163 * containing the currently-running script, or the current working directory if
164 * the currently-running script is "-e" (namely, you're using it from the
165 * command line.) Otherwise, it will be relative to the current working
166 * directory.
167 */
168 JSString* ResolvePath(JSContext* cx, HandleString filenameStr,
169 PathResolutionMode resolveMode) {
170 if (!filenameStr) {
171 #ifdef XP_WIN
172 return JS_NewStringCopyZ(cx, "nul");
173 #elif defined(__wasi__)
174 MOZ_CRASH("NYI for WASI");
175 return nullptr;
176 #else
177 return JS_NewStringCopyZ(cx, "/dev/null");
178 #endif
179 }
180
181 Rooted<JSLinearString*> str(cx, JS_EnsureLinearString(cx, filenameStr));
182 if (!str) {
183 return nullptr;
184 }
185
186 if (IsAbsolutePath(str)) {
187 return str;
188 }
189
190 UniqueChars filename = JS_EncodeStringToUTF8(cx, str);
191 if (!filename) {
192 return nullptr;
193 }
194
195 JS::AutoFilename scriptFilename;
196 if (resolveMode == ScriptRelative) {
197 // Get the currently executing script's name.
198
199 if (!DescribeScriptedCaller(&scriptFilename, cx) || !scriptFilename.get()) {
200 JS_ReportErrorASCII(
201 cx, "cannot resolve path due to hidden or unscripted caller");
202 return nullptr;
203 }
204
205 if (strcmp(scriptFilename.get(), "-e") == 0 ||
206 strcmp(scriptFilename.get(), "typein") == 0) {
207 resolveMode = RootRelative;
208 }
209 }
210
211 UniqueChars path;
212 if (resolveMode == ScriptRelative) {
213 path = DirectoryName(cx, scriptFilename.get());
214 } else {
215 path = GetCWD(cx);
216 }
217
218 if (!path) {
219 return nullptr;
220 }
221
222 size_t pathLen = strlen(path.get());
223 size_t filenameLen = strlen(filename.get());
224 size_t resultLen = pathLen + 1 + filenameLen;
225
226 UniqueChars result = cx->make_pod_array<char>(resultLen + 1);
227 if (!result) {
228 return nullptr;
229 }
230 memcpy(result.get(), path.get(), pathLen);
231 result[pathLen] = '/';
232 memcpy(result.get() + pathLen + 1, filename.get(), filenameLen);
233 result[pathLen + 1 + filenameLen] = '\0';
234
235 return JS_NewStringCopyUTF8N(cx, JS::UTF8Chars(result.get(), resultLen));
236 }
237
238 FILE* OpenFile(JSContext* cx, const char* filename, const char* mode) {
239 #ifdef XP_WIN
240 // Maximum valid mode string is "w+xb". Longer strings or strings
241 // containing invalid input lead to undefined behavior.
242 constexpr size_t MaxValidModeLength = 4;
243 wchar_t wideMode[MaxValidModeLength + 1] = {0};
244 for (size_t i = 0; i < MaxValidModeLength && mode[i] != '\0'; i++) {
245 wideMode[i] = mode[i] & 0x7f;
246 }
247
248 UniqueWideChars wideFilename = JS::EncodeUtf8ToWide(cx, filename);
249 if (!wideFilename) {
250 return nullptr;
251 }
252
253 FILE* file = _wfopen(wideFilename.get(), wideMode);
254 #else
255 UniqueChars narrowFilename = JS::EncodeUtf8ToNarrow(cx, filename);
256 if (!narrowFilename) {
257 return nullptr;
258 }
259
260 FILE* file = fopen(narrowFilename.get(), mode);
261 #endif
262
263 if (!file) {
264 if (UniqueChars error = SystemErrorMessage(cx, errno)) {
265 JS_ReportErrorNumberUTF8(cx, my_GetErrorMessage, nullptr,
266 JSSMSG_CANT_OPEN, filename, error.get());
267 }
268 return nullptr;
269 }
270 return file;
271 }
272
273 bool ReadFile(JSContext* cx, const char* filename, FILE* file, char* buffer,
274 size_t length) {
275 size_t cc = fread(buffer, sizeof(char), length, file);
276 if (cc != length) {
277 if (ptrdiff_t(cc) < 0) {
278 if (UniqueChars error = SystemErrorMessage(cx, errno)) {
279 JS_ReportErrorNumberUTF8(cx, my_GetErrorMessage, nullptr,
280 JSSMSG_CANT_READ, filename, error.get());
281 }
282 } else {
283 JS_ReportErrorUTF8(cx, "can't read %s: short read", filename);
284 }
285 return false;
286 }
287 return true;
288 }
289
290 bool FileSize(JSContext* cx, const char* filename, FILE* file, size_t* size) {
291 if (fseek(file, 0, SEEK_END) != 0) {
292 JS_ReportErrorUTF8(cx, "can't seek end of %s", filename);
293 return false;
294 }
295
296 size_t len = ftell(file);
297 if (fseek(file, 0, SEEK_SET) != 0) {
298 JS_ReportErrorUTF8(cx, "can't seek start of %s", filename);
299 return false;
300 }
301
302 *size = len;
303 return true;
304 }
305
306 JSObject* FileAsTypedArray(JSContext* cx, JS::HandleString pathnameStr) {
307 UniqueChars pathname = JS_EncodeStringToUTF8(cx, pathnameStr);
308 if (!pathname) {
309 return nullptr;
310 }
311
312 FILE* file = OpenFile(cx, pathname.get(), "rb");
313 if (!file) {
314 return nullptr;
315 }
316 AutoCloseFile autoClose(file);
317
318 size_t len;
319 if (!FileSize(cx, pathname.get(), file, &len)) {
320 return nullptr;
321 }
322
323 if (len > ArrayBufferObject::ByteLengthLimit) {
324 JS_ReportErrorUTF8(cx, "file %s is too large for a Uint8Array",
325 pathname.get());
326 return nullptr;
327 }
328
329 JS::Rooted<JSObject*> obj(cx, JS_NewUint8Array(cx, len));
330 if (!obj) {
331 return nullptr;
332 }
333
334 js::TypedArrayObject& ta = obj->as<js::TypedArrayObject>();
335 if (ta.isSharedMemory()) {
336 // Must opt in to use shared memory. For now, don't.
337 //
338 // (It is incorrect to read into the buffer without
339 // synchronization since that can create a race. A
340 // lock here won't fix it - both sides must
341 // participate. So what one must do is to create a
342 // temporary buffer, read into that, and use a
343 // race-safe primitive to copy memory into the
344 // buffer.)
345 JS_ReportErrorUTF8(cx, "can't read %s: shared memory buffer",
346 pathname.get());
347 return nullptr;
348 }
349
350 char* buf = static_cast<char*>(ta.dataPointerUnshared());
351 if (!ReadFile(cx, pathname.get(), file, buf, len)) {
352 return nullptr;
353 }
354
355 return obj;
356 }
357
358 /**
359 * Return the current working directory or |null| on failure.
360 */
361 UniqueChars GetCWD(JSContext* cx) {
362 #ifdef XP_WIN
363 wchar_t buffer[PATH_MAX + 1];
364 const wchar_t* cwd = _wgetcwd(buffer, PATH_MAX);
365 if (!cwd) {
366 return nullptr;
367 }
368 return JS::EncodeWideToUtf8(cx, buffer);
369 #else
370 char buffer[PATH_MAX + 1];
371 const char* cwd = getcwd(buffer, PATH_MAX);
372 if (!cwd) {
373 return nullptr;
374 }
375 return JS::EncodeNarrowToUtf8(cx, buffer);
376 #endif
377 }
378
379 static bool ReadFile(JSContext* cx, unsigned argc, Value* vp,
380 PathResolutionMode resolveMode) {
381 CallArgs args = CallArgsFromVp(argc, vp);
382
383 if (args.length() < 1 || args.length() > 2) {
384 JS_ReportErrorNumberASCII(
385 cx, js::shell::my_GetErrorMessage, nullptr,
386 args.length() < 1 ? JSSMSG_NOT_ENOUGH_ARGS : JSSMSG_TOO_MANY_ARGS,
387 "snarf");
388 return false;
389 }
390
391 if (!args[0].isString() || (args.length() == 2 && !args[1].isString())) {
392 JS_ReportErrorNumberASCII(cx, js::shell::my_GetErrorMessage, nullptr,
393 JSSMSG_INVALID_ARGS, "snarf");
394 return false;
395 }
396
397 JS::Rooted<JSString*> givenPath(cx, args[0].toString());
398 JS::Rooted<JSString*> str(cx,
399 js::shell::ResolvePath(cx, givenPath, resolveMode));
400 if (!str) {
401 return false;
402 }
403
404 if (args.length() > 1) {
405 JSString* opt = JS::ToString(cx, args[1]);
406 if (!opt) {
407 return false;
408 }
409 bool match;
410 if (!JS_StringEqualsLiteral(cx, opt, "binary", &match)) {
411 return false;
412 }
413 if (match) {
414 JSObject* obj;
415 if (!(obj = FileAsTypedArray(cx, str))) {
416 return false;
417 }
418 args.rval().setObject(*obj);
419 return true;
420 }
421 }
422
423 if (!(str = FileAsString(cx, str))) {
424 return false;
425 }
426 args.rval().setString(str);
427 return true;
428 }
429
430 static bool osfile_readFile(JSContext* cx, unsigned argc, Value* vp) {
431 return ReadFile(cx, argc, vp, RootRelative);
432 }
433
434 static bool osfile_readRelativeToScript(JSContext* cx, unsigned argc,
435 Value* vp) {
436 return ReadFile(cx, argc, vp, ScriptRelative);
437 }
438
439 static bool ListDir(JSContext* cx, unsigned argc, Value* vp,
440 PathResolutionMode resolveMode) {
441 CallArgs args = CallArgsFromVp(argc, vp);
442
443 if (args.length() != 1) {
444 JS_ReportErrorASCII(cx, "os.file.listDir requires 1 argument");
445 return false;
446 }
447
448 if (!args[0].isString()) {
449 JS_ReportErrorNumberASCII(cx, js::shell::my_GetErrorMessage, nullptr,
450 JSSMSG_INVALID_ARGS, "os.file.listDir");
451 return false;
452 }
453
454 RootedString givenPath(cx, args[0].toString());
455 RootedString str(cx, ResolvePath(cx, givenPath, resolveMode));
456 if (!str) {
457 return false;
458 }
459
460 UniqueChars pathname = JS_EncodeStringToUTF8(cx, str);
461 if (!pathname) {
462 JS_ReportErrorASCII(cx, "os.file.listDir cannot convert path to UTF8");
463 return false;
464 }
465
466 RootedValueVector elems(cx);
467 auto append = [&](const char* name) -> bool {
468 if (!(str = JS_NewStringCopyZ(cx, name))) {
469 return false;
470 }
471 if (!elems.append(StringValue(str))) {
472 js::ReportOutOfMemory(cx);
473 return false;
474 }
475 return true;
476 };
477
478 #if defined(XP_UNIX)
479 {
480 DIR* dir = opendir(pathname.get());
481 if (!dir) {
482 JS_ReportErrorUTF8(cx, "os.file.listDir is unable to open: %s",
483 pathname.get());
484 return false;
485 }
486 auto close = mozilla::MakeScopeExit([&] {
487 if (closedir(dir) != 0) {
488 MOZ_CRASH("Could not close dir");
489 }
490 });
491
492 while (struct dirent* entry = readdir(dir)) {
493 if (!append(entry->d_name)) {
494 return false;
495 }
496 }
497 }
498 #elif defined(XP_WIN)
499 {
500 const size_t pathlen = strlen(pathname.get());
501 Vector<char> pattern(cx);
502 if (!pattern.append(pathname.get(), pathlen) ||
503 !pattern.append(PathSeparator) || !pattern.append("*", 2)) {
504 js::ReportOutOfMemory(cx);
505 return false;
506 }
507
508 WIN32_FIND_DATAA FindFileData;
509 HANDLE hFind = FindFirstFileA(pattern.begin(), &FindFileData);
510 if (hFind == INVALID_HANDLE_VALUE) {
511 JS_ReportErrorUTF8(cx, "os.file.listDir is unable to open: %s",
512 pathname.get());
513 return false;
514 }
515 auto close = mozilla::MakeScopeExit([&] {
516 if (!FindClose(hFind)) {
517 MOZ_CRASH("Could not close Find");
518 }
519 });
520 for (bool found = (hFind != INVALID_HANDLE_VALUE); found;
521 found = FindNextFileA(hFind, &FindFileData)) {
522 if (!append(FindFileData.cFileName)) {
523 return false;
524 }
525 }
526 }
527 #endif
528
529 JSObject* array = JS::NewArrayObject(cx, elems);
530 if (!array) {
531 return false;
532 }
533
534 args.rval().setObject(*array);
535 return true;
536 }
537
538 static bool osfile_listDir(JSContext* cx, unsigned argc, Value* vp) {
539 return ListDir(cx, argc, vp, RootRelative);
540 }
541
542 static bool osfile_listDirRelativeToScript(JSContext* cx, unsigned argc,
543 Value* vp) {
544 return ListDir(cx, argc, vp, ScriptRelative);
545 }
546
547 static bool osfile_writeTypedArrayToFile(JSContext* cx, unsigned argc,
548 Value* vp) {
549 CallArgs args = CallArgsFromVp(argc, vp);
550
551 if (args.length() != 2 || !args[0].isString() || !args[1].isObject() ||
552 !args[1].toObject().is<TypedArrayObject>()) {
553 JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr,
554 JSSMSG_INVALID_ARGS, "writeTypedArrayToFile");
555 return false;
556 }
557
558 RootedString givenPath(cx, args[0].toString());
559 RootedString str(cx, ResolvePath(cx, givenPath, RootRelative));
560 if (!str) {
561 return false;
562 }
563
564 UniqueChars filename = JS_EncodeStringToUTF8(cx, str);
565 if (!filename) {
566 return false;
567 }
568
569 FILE* file = OpenFile(cx, filename.get(), "wb");
570 if (!file) {
571 return false;
572 }
573 AutoCloseFile autoClose(file);
574
575 TypedArrayObject* obj = &args[1].toObject().as<TypedArrayObject>();
576
577 if (obj->isSharedMemory()) {
578 // Must opt in to use shared memory. For now, don't.
579 //
580 // See further comments in FileAsTypedArray, above.
581 JS_ReportErrorUTF8(cx, "can't write %s: shared memory buffer",
582 filename.get());
583 return false;
584 }
585 void* buf = obj->dataPointerUnshared();
586 size_t length = obj->length().valueOr(0);
587 if (fwrite(buf, obj->bytesPerElement(), length, file) != length ||
588 !autoClose.release()) {
589 JS_ReportErrorUTF8(cx, "can't write %s", filename.get());
590 return false;
591 }
592
593 args.rval().setUndefined();
594 return true;
595 }
596
597 /* static */
598 RCFile* RCFile::create(JSContext* cx, const char* filename, const char* mode) {
599 FILE* fp = OpenFile(cx, filename, mode);
600 if (!fp) {
601 return nullptr;
602 }
603
604 RCFile* file = cx->new_<RCFile>(fp);
605 if (!file) {
606 fclose(fp);
607 return nullptr;
608 }
609
610 return file;
611 }
612
613 void RCFile::close() {
614 if (fp) {
615 fclose(fp);
616 }
617 fp = nullptr;
618 }
619
620 bool RCFile::release() {
621 if (--numRefs) {
622 return false;
623 }
624 this->close();
625 return true;
626 }
627
628 class FileObject : public NativeObject {
629 enum : uint32_t { FILE_SLOT = 0, NUM_SLOTS };
630
631 public:
632 static const JSClass class_;
633
634 static FileObject* create(JSContext* cx, RCFile* file) {
635 FileObject* obj = js::NewBuiltinClassInstance<FileObject>(cx);
636 if (!obj) {
637 return nullptr;
638 }
639
640 InitReservedSlot(obj, FILE_SLOT, file, MemoryUse::FileObjectFile);
641 file->acquire();
642 return obj;
643 }
644
645 static void finalize(JS::GCContext* gcx, JSObject* obj) {
646 FileObject* fileObj = &obj->as<FileObject>();
647 RCFile* file = fileObj->rcFile();
648 gcx->removeCellMemory(obj, sizeof(*file), MemoryUse::FileObjectFile);
649 if (file->release()) {
650 gcx->deleteUntracked(file);
651 }
652 }
653
654 bool isOpen() {
655 RCFile* file = rcFile();
656 return file && file->isOpen();
657 }
658
659 void close() {
660 if (!isOpen()) {
661 return;
662 }
663 rcFile()->close();
664 }
665
666 RCFile* rcFile() {
667 return reinterpret_cast<RCFile*>(
668 JS::GetReservedSlot(this, FILE_SLOT).toPrivate());
669 }
670 };
671
672 static const JSClassOps FileObjectClassOps = {
673 nullptr, // addProperty
674 nullptr, // delProperty
675 nullptr, // enumerate
676 nullptr, // newEnumerate
677 nullptr, // resolve
678 nullptr, // mayResolve
679 FileObject::finalize, // finalize
680 nullptr, // call
681 nullptr, // construct
682 nullptr, // trace
683 };
684
685 const JSClass FileObject::class_ = {
686 "File",
687 JSCLASS_HAS_RESERVED_SLOTS(FileObject::NUM_SLOTS) |
688 JSCLASS_FOREGROUND_FINALIZE,
689 &FileObjectClassOps,
690 };
691
692 static FileObject* redirect(JSContext* cx, HandleString relFilename,
693 RCFile** globalFile) {
694 RootedString filename(cx, ResolvePath(cx, relFilename, RootRelative));
695 if (!filename) {
696 return nullptr;
697 }
698 UniqueChars filenameABS = JS_EncodeStringToUTF8(cx, filename);
699 if (!filenameABS) {
700 return nullptr;
701 }
702 RCFile* file = RCFile::create(cx, filenameABS.get(), "wb");
703 if (!file) {
704 return nullptr;
705 }
706
707 // Grant the global gOutFile ownership of the new file, release ownership
708 // of its old file, and return a FileObject owning the old file.
709 file->acquire(); // Global owner of new file
710
711 FileObject* fileObj =
712 FileObject::create(cx, *globalFile); // Newly created owner of old file
713 if (!fileObj) {
714 file->release();
715 return nullptr;
716 }
717
718 (*globalFile)->release(); // Release (global) ownership of old file.
719 *globalFile = file;
720
721 return fileObj;
722 }
723
724 static bool Redirect(JSContext* cx, const CallArgs& args, RCFile** outFile) {
725 if (args.length() > 1) {
726 JS_ReportErrorNumberASCII(cx, js::shell::my_GetErrorMessage, nullptr,
727 JSSMSG_INVALID_ARGS, "redirect");
728 return false;
729 }
730
731 RCFile* oldFile = *outFile;
732 RootedObject oldFileObj(cx, FileObject::create(cx, oldFile));
733 if (!oldFileObj) {
734 return false;
735 }
736
737 if (args.get(0).isUndefined()) {
738 args.rval().setObject(*oldFileObj);
739 return true;
740 }
741
742 if (args[0].isObject()) {
743 Rooted<FileObject*> fileObj(cx,
744 args[0].toObject().maybeUnwrapIf<FileObject>());
745 if (!fileObj) {
746 JS_ReportErrorNumberASCII(cx, js::shell::my_GetErrorMessage, nullptr,
747 JSSMSG_INVALID_ARGS, "redirect");
748 return false;
749 }
750
751 // Passed in a FileObject. Create a FileObject for the previous
752 // global file, and set the global file to the passed-in one.
753 *outFile = fileObj->rcFile();
754 (*outFile)->acquire();
755 oldFile->release();
756
757 args.rval().setObject(*oldFileObj);
758 return true;
759 }
760
761 RootedString filename(cx);
762 if (!args[0].isNull()) {
763 filename = JS::ToString(cx, args[0]);
764 if (!filename) {
765 return false;
766 }
767 }
768
769 if (!redirect(cx, filename, outFile)) {
770 return false;
771 }
772
773 args.rval().setObject(*oldFileObj);
774 return true;
775 }
776
777 static bool osfile_redirectOutput(JSContext* cx, unsigned argc, Value* vp) {
778 CallArgs args = CallArgsFromVp(argc, vp);
779 ShellContext* scx = GetShellContext(cx);
780 return Redirect(cx, args, scx->outFilePtr);
781 }
782
783 static bool osfile_redirectError(JSContext* cx, unsigned argc, Value* vp) {
784 CallArgs args = CallArgsFromVp(argc, vp);
785 ShellContext* scx = GetShellContext(cx);
786 return Redirect(cx, args, scx->errFilePtr);
787 }
788
789 static bool osfile_close(JSContext* cx, unsigned argc, Value* vp) {
790 CallArgs args = CallArgsFromVp(argc, vp);
791
792 Rooted<FileObject*> fileObj(cx);
793 if (args.get(0).isObject()) {
794 fileObj = args[0].toObject().maybeUnwrapIf<FileObject>();
795 }
796
797 if (!fileObj) {
798 JS_ReportErrorNumberASCII(cx, js::shell::my_GetErrorMessage, nullptr,
799 JSSMSG_INVALID_ARGS, "close");
800 return false;
801 }
802
803 fileObj->close();
804
805 args.rval().setUndefined();
806 return true;
807 }
808
809 // clang-format off
810 static const JSFunctionSpecWithHelp osfile_functions[] = {
811 JS_FN_HELP("readFile", osfile_readFile, 1, 0,
812 "readFile(filename, [\"binary\"])",
813 " Read entire contents of filename. Returns a string, unless \"binary\" is passed\n"
814 " as the second argument, in which case it returns a Uint8Array. Filename is\n"
815 " relative to the current working directory."),
816
817 JS_FN_HELP("readRelativeToScript", osfile_readRelativeToScript, 1, 0,
818 "readRelativeToScript(filename, [\"binary\"])",
819 " Read filename into returned string. Filename is relative to the directory\n"
820 " containing the current script."),
821
822 JS_FN_HELP("listDir", osfile_listDir, 1, 0,
823 "listDir(dirname)",
824 " Read entire contents of a directory. The \"dirname\" parameter is relate to the\n"
825 " current working directory. Returns a list of filenames within the given directory.\n"
826 " Note that \".\" and \"..\" are also listed."),
827
828 JS_FN_HELP("listDirRelativeToScript", osfile_listDirRelativeToScript, 1, 0,
829 "listDirRelativeToScript(dirname)",
830 " Same as \"listDir\" except that the \"dirname\" is relative to the directory\n"
831 " containing the current script."),
832
833 JS_FS_HELP_END
834 };
835 // clang-format on
836
837 // clang-format off
838 static const JSFunctionSpecWithHelp osfile_unsafe_functions[] = {
839 JS_FN_HELP("writeTypedArrayToFile", osfile_writeTypedArrayToFile, 2, 0,
840 "writeTypedArrayToFile(filename, data)",
841 " Write the contents of a typed array to the named file."),
842
843 JS_FN_HELP("redirect", osfile_redirectOutput, 1, 0,
844 "redirect([path-or-object])",
845 " Redirect print() output to the named file.\n"
846 " Return an opaque object representing the previous destination, which\n"
847 " may be passed into redirect() later to restore the output."),
848
849 JS_FN_HELP("redirectErr", osfile_redirectError, 1, 0,
850 "redirectErr([path-or-object])",
851 " Same as redirect(), but for printErr"),
852
853 JS_FN_HELP("close", osfile_close, 1, 0,
854 "close(object)",
855 " Close the file returned by an earlier redirect call."),
856
857 JS_FS_HELP_END
858 };
859 // clang-format on
860
861 static bool ospath_isAbsolute(JSContext* cx, unsigned argc, Value* vp) {
862 CallArgs args = CallArgsFromVp(argc, vp);
863
864 if (args.length() != 1 || !args[0].isString()) {
865 JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr,
866 JSSMSG_INVALID_ARGS, "isAbsolute");
867 return false;
868 }
869
870 Rooted<JSLinearString*> str(cx,
871 JS_EnsureLinearString(cx, args[0].toString()));
872 if (!str) {
873 return false;
874 }
875
876 args.rval().setBoolean(IsAbsolutePath(str));
877 return true;
878 }
879
880 static bool ospath_join(JSContext* cx, unsigned argc, Value* vp) {
881 CallArgs args = CallArgsFromVp(argc, vp);
882
883 if (args.length() < 1) {
884 JS_ReportErrorNumberASCII(cx, my_GetErrorMessage, nullptr,
885 JSSMSG_INVALID_ARGS, "join");
886 return false;
887 }
888
889 // This function doesn't take into account some aspects of Windows paths,
890 // e.g. the drive letter is always reset when an absolute path is appended.
891
892 JSStringBuilder buffer(cx);
893 Rooted<JSLinearString*> str(cx);
894
895 for (unsigned i = 0; i < args.length(); i++) {
896 if (!args[i].isString()) {
897 JS_ReportErrorASCII(cx, "join expects string arguments only");
898 return false;
899 }
900
901 str = JS_EnsureLinearString(cx, args[i].toString());
902 if (!str) {
903 return false;
904 }
905
906 if (IsAbsolutePath(str)) {
907 buffer.clear();
908 } else if (i != 0) {
909 UniqueChars path = JS_EncodeStringToUTF8(cx, str);
910 if (!path) {
911 return false;
912 }
913
914 if (!buffer.append(PathSeparator)) {
915 return false;
916 }
917 }
918
919 if (!buffer.append(args[i].toString())) {
920 return false;
921 }
922 }
923
924 JSString* result = buffer.finishString();
925 if (!result) {
926 return false;
927 }
928
929 args.rval().setString(result);
930 return true;
931 }
932
933 // clang-format off
934 static const JSFunctionSpecWithHelp ospath_functions[] = {
935 JS_FN_HELP("isAbsolute", ospath_isAbsolute, 1, 0,
936 "isAbsolute(path)",
937 " Return whether the given path is absolute."),
938
939 JS_FN_HELP("join", ospath_join, 1, 0,
940 "join(paths...)",
941 " Join one or more path components in a platform independent way."),
942
943 JS_FS_HELP_END
944 };
945 // clang-format on
946
947 static bool os_getenv(JSContext* cx, unsigned argc, Value* vp) {
948 CallArgs args = CallArgsFromVp(argc, vp);
949 if (args.length() < 1) {
950 JS_ReportErrorASCII(cx, "os.getenv requires 1 argument");
951 return false;
952 }
953 RootedString key(cx, ToString(cx, args[0]));
954 if (!key) {
955 return false;
956 }
957 UniqueChars keyBytes = JS_EncodeStringToUTF8(cx, key);
958 if (!keyBytes) {
959 return false;
960 }
961
962 if (const char* valueBytes = getenv(keyBytes.get())) {
963 RootedString value(cx, JS_NewStringCopyZ(cx, valueBytes));
964 if (!value) {
965 return false;
966 }
967 args.rval().setString(value);
968 } else {
969 args.rval().setUndefined();
970 }
971 return true;
972 }
973
974 static bool os_getpid(JSContext* cx, unsigned argc, Value* vp) {
975 CallArgs args = CallArgsFromVp(argc, vp);
976 if (args.length() != 0) {
977 JS_ReportErrorASCII(cx, "os.getpid takes no arguments");
978 return false;
979 }
980 args.rval().setInt32(getpid());
981 return true;
982 }
983
984 #if !defined(XP_WIN)
985
986 // There are two possible definitions of strerror_r floating around. The GNU
987 // one returns a char* which may or may not be the buffer you passed in. The
988 // other one returns an integer status code, and always writes the result into
989 // the provided buffer.
990
991 inline char* strerror_message(int result, char* buffer) {
992 return result == 0 ? buffer : nullptr;
993 }
994
995 inline char* strerror_message(char* result, char* buffer) { return result; }
996
997 #endif
998
999 UniqueChars SystemErrorMessage(JSContext* cx, int errnum) {
1000 #if defined(XP_WIN)
1001 wchar_t buffer[200];
1002 const wchar_t* errstr = buffer;
1003 if (_wcserror_s(buffer, std::size(buffer), errnum) != 0) {
1004 errstr = L"unknown error";
1005 }
1006 return JS::EncodeWideToUtf8(cx, errstr);
1007 #else
1008 char buffer[200];
1009 const char* errstr =
1010 strerror_message(strerror_r(errno, buffer, std::size(buffer)), buffer);
1011 if (!errstr) {
1012 errstr = "unknown error";
1013 }
1014 return JS::EncodeNarrowToUtf8(cx, errstr);
1015 #endif
1016 }
1017
1018 #ifndef __wasi__
1019 static void ReportSysError(JSContext* cx, const char* prefix) {
1020 MOZ_ASSERT(JS::StringIsASCII(prefix));
1021
1022 if (UniqueChars error = SystemErrorMessage(cx, errno)) {
1023 JS_ReportErrorUTF8(cx, "%s: %s", prefix, error.get());
1024 }
1025 }
1026
1027 static bool os_system(JSContext* cx, unsigned argc, Value* vp) {
1028 CallArgs args = CallArgsFromVp(argc, vp);
1029
1030 if (args.length() == 0) {
1031 JS_ReportErrorASCII(cx, "os.system requires 1 argument");
1032 return false;
1033 }
1034
1035 Rooted<JSString*> str(cx, JS::ToString(cx, args[0]));
1036 if (!str) {
1037 return false;
1038 }
1039
1040 UniqueChars command = JS_EncodeStringToUTF8(cx, str);
1041 if (!command) {
1042 return false;
1043 }
1044
1045 # ifdef XP_WIN
1046 UniqueWideChars wideCommand = JS::EncodeUtf8ToWide(cx, command.get());
1047 if (!wideCommand) {
1048 return false;
1049 }
1050
1051 // Existing streams must be explicitly flushed or closed before calling
1052 // the system() function on Windows.
1053 _flushall();
1054
1055 int result = _wsystem(wideCommand.get());
1056 # else
1057 UniqueChars narrowCommand = JS::EncodeUtf8ToNarrow(cx, command.get());
1058 if (!narrowCommand) {
1059 return false;
1060 }
1061
1062 int result = system(narrowCommand.get());
1063 # endif
1064 if (result == -1) {
1065 ReportSysError(cx, "system call failed");
1066 return false;
1067 }
1068
1069 args.rval().setInt32(result);
1070 return true;
1071 }
1072
1073 # ifndef XP_WIN
1074 static bool os_spawn(JSContext* cx, unsigned argc, Value* vp) {
1075 CallArgs args = CallArgsFromVp(argc, vp);
1076
1077 if (args.length() == 0) {
1078 JS_ReportErrorASCII(cx, "os.spawn requires 1 argument");
1079 return false;
1080 }
1081
1082 Rooted<JSString*> str(cx, JS::ToString(cx, args[0]));
1083 if (!str) {
1084 return false;
1085 }
1086
1087 UniqueChars command = JS_EncodeStringToUTF8(cx, str);
1088 if (!command) {
1089 return false;
1090 }
1091 UniqueChars narrowCommand = JS::EncodeUtf8ToNarrow(cx, command.get());
1092 if (!narrowCommand) {
1093 return false;
1094 }
1095
1096 int32_t childPid = fork();
1097 if (childPid == -1) {
1098 ReportSysError(cx, "fork failed");
1099 return false;
1100 }
1101
1102 if (childPid) {
1103 args.rval().setInt32(childPid);
1104 return true;
1105 }
1106
1107 // We are in the child
1108
1109 const char* cmd[] = {"sh", "-c", nullptr, nullptr};
1110 cmd[2] = narrowCommand.get();
1111
1112 execvp("sh", (char* const*)cmd);
1113 exit(1);
1114 }
1115
1116 static bool os_kill(JSContext* cx, unsigned argc, Value* vp) {
1117 CallArgs args = CallArgsFromVp(argc, vp);
1118 int32_t pid;
1119 if (args.length() < 1) {
1120 JS_ReportErrorASCII(cx, "os.kill requires 1 argument");
1121 return false;
1122 }
1123 if (!JS::ToInt32(cx, args[0], &pid)) {
1124 return false;
1125 }
1126
1127 // It is too easy to kill yourself accidentally with os.kill("goose").
1128 if (pid == 0 && !args[0].isInt32()) {
1129 JS_ReportErrorASCII(cx, "os.kill requires numeric pid");
1130 return false;
1131 }
1132
1133 int signal = SIGINT;
1134 if (args.length() > 1) {
1135 if (!JS::ToInt32(cx, args[1], &signal)) {
1136 return false;
1137 }
1138 }
1139
1140 int status = kill(pid, signal);
1141 if (status == -1) {
1142 ReportSysError(cx, "kill failed");
1143 return false;
1144 }
1145
1146 args.rval().setUndefined();
1147 return true;
1148 }
1149
1150 static bool os_waitpid(JSContext* cx, unsigned argc, Value* vp) {
1151 CallArgs args = CallArgsFromVp(argc, vp);
1152
1153 int32_t pid;
1154 if (args.length() == 0) {
1155 pid = -1;
1156 } else {
1157 if (!JS::ToInt32(cx, args[0], &pid)) {
1158 return false;
1159 }
1160 }
1161
1162 bool nohang = false;
1163 if (args.length() >= 2) {
1164 nohang = JS::ToBoolean(args[1]);
1165 }
1166
1167 int status = 0;
1168 pid_t result = waitpid(pid, &status, nohang ? WNOHANG : 0);
1169 if (result == -1) {
1170 ReportSysError(cx, "os.waitpid failed");
1171 return false;
1172 }
1173
1174 RootedObject info(cx, JS_NewPlainObject(cx));
1175 if (!info) {
1176 return false;
1177 }
1178
1179 RootedValue v(cx);
1180 if (result != 0) {
1181 v.setInt32(result);
1182 if (!JS_DefineProperty(cx, info, "pid", v, JSPROP_ENUMERATE)) {
1183 return false;
1184 }
1185 if (WIFEXITED(status)) {
1186 v.setInt32(WEXITSTATUS(status));
1187 if (!JS_DefineProperty(cx, info, "exitStatus", v, JSPROP_ENUMERATE)) {
1188 return false;
1189 }
1190 }
1191 }
1192
1193 args.rval().setObject(*info);
1194 return true;
1195 }
1196 # endif
1197 #endif // !__wasi__
1198
1199 // clang-format off
1200 static const JSFunctionSpecWithHelp os_functions[] = {
1201 JS_FN_HELP("getenv", os_getenv, 1, 0,
1202 "getenv(variable)",
1203 " Get the value of an environment variable."),
1204
1205 JS_FN_HELP("getpid", os_getpid, 0, 0,
1206 "getpid()",
1207 " Return the current process id."),
1208
1209 #ifndef __wasi__
1210 JS_FN_HELP("system", os_system, 1, 0,
1211 "system(command)",
1212 " Execute command on the current host, returning result code or throwing an\n"
1213 " exception on failure."),
1214
1215 # ifndef XP_WIN
1216 JS_FN_HELP("spawn", os_spawn, 1, 0,
1217 "spawn(command)",
1218 " Start up a separate process running the given command. Returns the pid."),
1219
1220 JS_FN_HELP("kill", os_kill, 1, 0,
1221 "kill(pid[, signal])",
1222 " Send a signal to the given pid. The default signal is SIGINT. The signal\n"
1223 " passed in must be numeric, if given."),
1224
1225 JS_FN_HELP("waitpid", os_waitpid, 1, 0,
1226 "waitpid(pid[, nohang])",
1227 " Calls waitpid(). 'nohang' is a boolean indicating whether to pass WNOHANG.\n"
1228 " The return value is an object containing a 'pid' field, if a process was waitable\n"
1229 " and an 'exitStatus' field if a pid exited."),
1230 # endif
1231 #endif // !__wasi__
1232
1233 JS_FS_HELP_END
1234 };
1235 // clang-format on
1236
1237 bool DefineOS(JSContext* cx, HandleObject global, bool fuzzingSafe,
1238 RCFile** shellOut, RCFile** shellErr) {
1239 RootedObject obj(cx, JS_NewPlainObject(cx));
1240 if (!obj || !JS_DefineProperty(cx, global, "os", obj, 0)) {
1241 return false;
1242 }
1243
1244 if (!fuzzingSafe) {
1245 if (!JS_DefineFunctionsWithHelp(cx, obj, os_functions)) {
1246 return false;
1247 }
1248 }
1249
1250 RootedObject osfile(cx, JS_NewPlainObject(cx));
1251 if (!osfile || !JS_DefineFunctionsWithHelp(cx, osfile, osfile_functions) ||
1252 !JS_DefineProperty(cx, obj, "file", osfile, 0)) {
1253 return false;
1254 }
1255
1256 if (!fuzzingSafe) {
1257 if (!JS_DefineFunctionsWithHelp(cx, osfile, osfile_unsafe_functions)) {
1258 return false;
1259 }
1260 }
1261
1262 if (!GenerateInterfaceHelp(cx, osfile, "os.file")) {
1263 return false;
1264 }
1265
1266 RootedObject ospath(cx, JS_NewPlainObject(cx));
1267 if (!ospath || !JS_DefineFunctionsWithHelp(cx, ospath, ospath_functions) ||
1268 !JS_DefineProperty(cx, obj, "path", ospath, 0) ||
1269 !GenerateInterfaceHelp(cx, ospath, "os.path")) {
1270 return false;
1271 }
1272
1273 if (!GenerateInterfaceHelp(cx, obj, "os")) {
1274 return false;
1275 }
1276
1277 ShellContext* scx = GetShellContext(cx);
1278 scx->outFilePtr = shellOut;
1279 scx->errFilePtr = shellErr;
1280
1281 // For backwards compatibility, expose various os.file.* functions as
1282 // direct methods on the global.
1283 struct Export {
1284 const char* src;
1285 const char* dst;
1286 };
1287
1288 const Export osfile_exports[] = {
1289 {"readFile", "read"},
1290 {"readFile", "snarf"},
1291 {"readRelativeToScript", "readRelativeToScript"},
1292 };
1293
1294 for (auto pair : osfile_exports) {
1295 if (!CreateAlias(cx, pair.dst, osfile, pair.src)) {
1296 return false;
1297 }
1298 }
1299
1300 if (!fuzzingSafe) {
1301 const Export unsafe_osfile_exports[] = {{"redirect", "redirect"},
1302 {"redirectErr", "redirectErr"}};
1303
1304 for (auto pair : unsafe_osfile_exports) {
1305 if (!CreateAlias(cx, pair.dst, osfile, pair.src)) {
1306 return false;
1307 }
1308 }
1309 }
1310
1311 return true;
1312 }
1313
1314 } // namespace shell
1315 } // namespace js