Bug 1805294 [wpt PR 37463] - WebKit export of https://bugs.webkit.org/show_bug.cgi...
[gecko.git] / dom / system / IOUtils.h
bloba5fea23c60ff01456fd35842aa0b5bd195b28167
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/. */
7 #ifndef mozilla_dom_IOUtils__
8 #define mozilla_dom_IOUtils__
10 #include "js/Utility.h"
11 #include "mozilla/AlreadyAddRefed.h"
12 #include "mozilla/Attributes.h"
13 #include "mozilla/Buffer.h"
14 #include "mozilla/DataMutex.h"
15 #include "mozilla/MozPromise.h"
16 #include "mozilla/Result.h"
17 #include "mozilla/StaticPtr.h"
18 #include "mozilla/dom/BindingDeclarations.h"
19 #include "mozilla/dom/IOUtilsBinding.h"
20 #include "mozilla/dom/TypedArray.h"
21 #include "nsIAsyncShutdown.h"
22 #include "nsIFile.h"
23 #include "nsISerialEventTarget.h"
24 #include "nsPrintfCString.h"
25 #include "nsProxyRelease.h"
26 #include "nsString.h"
27 #include "nsStringFwd.h"
28 #include "nsTArray.h"
29 #include "prio.h"
31 class nsFileRandomAccessStream;
33 namespace mozilla {
35 /**
36 * Utility class to be used with |UniquePtr| to automatically close NSPR file
37 * descriptors when they go out of scope.
39 * Example:
41 * UniquePtr<PRFileDesc, PR_CloseDelete> fd = PR_Open(path, flags, mode);
43 class PR_CloseDelete {
44 public:
45 constexpr PR_CloseDelete() = default;
46 PR_CloseDelete(const PR_CloseDelete& aOther) = default;
47 PR_CloseDelete(PR_CloseDelete&& aOther) = default;
48 PR_CloseDelete& operator=(const PR_CloseDelete& aOther) = default;
49 PR_CloseDelete& operator=(PR_CloseDelete&& aOther) = default;
51 void operator()(PRFileDesc* aPtr) const { PR_Close(aPtr); }
54 namespace dom {
56 /**
57 * Implementation for the Web IDL interface at dom/chrome-webidl/IOUtils.webidl.
58 * Methods of this class must only be called from the parent process.
60 class IOUtils final {
61 public:
62 class IOError;
64 enum class ShutdownPhase : uint8_t {
65 ProfileBeforeChange,
66 SendTelemetry,
67 XpcomWillShutdown,
68 Count,
71 template <typename T>
72 using PhaseArray =
73 EnumeratedArray<IOUtils::ShutdownPhase, IOUtils::ShutdownPhase::Count, T>;
75 static already_AddRefed<Promise> Read(GlobalObject& aGlobal,
76 const nsAString& aPath,
77 const ReadOptions& aOptions,
78 ErrorResult& aError);
80 static already_AddRefed<Promise> ReadUTF8(GlobalObject& aGlobal,
81 const nsAString& aPath,
82 const ReadUTF8Options& aOptions,
83 ErrorResult& aError);
85 static already_AddRefed<Promise> ReadJSON(GlobalObject& aGlobal,
86 const nsAString& aPath,
87 const ReadUTF8Options& aOptions,
88 ErrorResult& aError);
90 static already_AddRefed<Promise> Write(GlobalObject& aGlobal,
91 const nsAString& aPath,
92 const Uint8Array& aData,
93 const WriteOptions& aOptions,
94 ErrorResult& aError);
96 static already_AddRefed<Promise> WriteUTF8(GlobalObject& aGlobal,
97 const nsAString& aPath,
98 const nsACString& aString,
99 const WriteOptions& aOptions,
100 ErrorResult& aError);
102 static already_AddRefed<Promise> WriteJSON(GlobalObject& aGlobal,
103 const nsAString& aPath,
104 JS::Handle<JS::Value> aValue,
105 const WriteOptions& aOptions,
106 ErrorResult& aError);
108 static already_AddRefed<Promise> Move(GlobalObject& aGlobal,
109 const nsAString& aSourcePath,
110 const nsAString& aDestPath,
111 const MoveOptions& aOptions,
112 ErrorResult& aError);
114 static already_AddRefed<Promise> Remove(GlobalObject& aGlobal,
115 const nsAString& aPath,
116 const RemoveOptions& aOptions,
117 ErrorResult& aError);
119 static already_AddRefed<Promise> MakeDirectory(
120 GlobalObject& aGlobal, const nsAString& aPath,
121 const MakeDirectoryOptions& aOptions, ErrorResult& aError);
123 static already_AddRefed<Promise> Stat(GlobalObject& aGlobal,
124 const nsAString& aPath,
125 ErrorResult& aError);
127 static already_AddRefed<Promise> Copy(GlobalObject& aGlobal,
128 const nsAString& aSourcePath,
129 const nsAString& aDestPath,
130 const CopyOptions& aOptions,
131 ErrorResult& aError);
133 static already_AddRefed<Promise> SetAccessTime(
134 GlobalObject& aGlobal, const nsAString& aPath,
135 const Optional<int64_t>& aAccess, ErrorResult& aError);
137 static already_AddRefed<Promise> SetModificationTime(
138 GlobalObject& aGlobal, const nsAString& aPath,
139 const Optional<int64_t>& aModification, ErrorResult& aError);
141 private:
142 using SetTimeFn = decltype(&nsIFile::SetLastAccessedTime);
144 static_assert(
145 std::is_same_v<SetTimeFn, decltype(&nsIFile::SetLastModifiedTime)>);
147 static already_AddRefed<Promise> SetTime(GlobalObject& aGlobal,
148 const nsAString& aPath,
149 const Optional<int64_t>& aNewTime,
150 SetTimeFn aSetTimeFn,
151 ErrorResult& aError);
153 public:
154 static already_AddRefed<Promise> GetChildren(
155 GlobalObject& aGlobal, const nsAString& aPath,
156 const GetChildrenOptions& aOptions, ErrorResult& aError);
158 static already_AddRefed<Promise> SetPermissions(GlobalObject& aGlobal,
159 const nsAString& aPath,
160 uint32_t aPermissions,
161 const bool aHonorUmask,
162 ErrorResult& aError);
164 static already_AddRefed<Promise> Exists(GlobalObject& aGlobal,
165 const nsAString& aPath,
166 ErrorResult& aError);
168 static already_AddRefed<Promise> CreateUniqueFile(GlobalObject& aGlobal,
169 const nsAString& aParent,
170 const nsAString& aPrefix,
171 const uint32_t aPermissions,
172 ErrorResult& aError);
173 static already_AddRefed<Promise> CreateUniqueDirectory(
174 GlobalObject& aGlobal, const nsAString& aParent, const nsAString& aPrefix,
175 const uint32_t aPermissions, ErrorResult& aError);
177 private:
179 * A helper method for CreateUniqueFile and CreateUniqueDirectory.
181 static already_AddRefed<Promise> CreateUnique(GlobalObject& aGlobal,
182 const nsAString& aParent,
183 const nsAString& aPrefix,
184 const uint32_t aFileType,
185 const uint32_t aPermissions,
186 ErrorResult& aError);
188 public:
189 static already_AddRefed<Promise> ComputeHexDigest(
190 GlobalObject& aGlobal, const nsAString& aPath,
191 const HashAlgorithm aAlgorithm, ErrorResult& aError);
193 #if defined(XP_WIN)
194 static already_AddRefed<Promise> GetWindowsAttributes(GlobalObject& aGlobal,
195 const nsAString& aPath,
196 ErrorResult& aError);
198 static already_AddRefed<Promise> SetWindowsAttributes(
199 GlobalObject& aGlobal, const nsAString& aPath,
200 const mozilla::dom::WindowsFileAttributes& aAttrs, ErrorResult& aError);
201 #elif defined(XP_MACOSX)
202 static already_AddRefed<Promise> HasMacXAttr(GlobalObject& aGlobal,
203 const nsAString& aPath,
204 const nsACString& aAttr,
205 ErrorResult& aError);
206 static already_AddRefed<Promise> GetMacXAttr(GlobalObject& aGlobal,
207 const nsAString& aPath,
208 const nsACString& aAttr,
209 ErrorResult& aError);
210 static already_AddRefed<Promise> SetMacXAttr(GlobalObject& aGlobal,
211 const nsAString& aPath,
212 const nsACString& aAttr,
213 const Uint8Array& aValue,
214 ErrorResult& aError);
215 static already_AddRefed<Promise> DelMacXAttr(GlobalObject& aGlobal,
216 const nsAString& aPath,
217 const nsACString& aAttr,
218 ErrorResult& aError);
219 #endif
221 #ifdef XP_UNIX
222 using UnixString = OwningUTF8StringOrUint8Array;
223 static uint32_t LaunchProcess(GlobalObject& aGlobal,
224 const Sequence<UnixString>& aArgv,
225 const LaunchOptions& aOptions,
226 ErrorResult& aRv);
227 #endif
229 static already_AddRefed<Promise> GetFile(
230 GlobalObject& aGlobal, const Sequence<nsString>& aComponents,
231 ErrorResult& aError);
233 static already_AddRefed<Promise> GetDirectory(
234 GlobalObject& aGlobal, const Sequence<nsString>& aComponents,
235 ErrorResult& aError);
237 static void GetProfileBeforeChange(GlobalObject& aGlobal,
238 JS::MutableHandle<JS::Value>,
239 ErrorResult& aRv);
241 static void GetSendTelemetry(GlobalObject& aGlobal,
242 JS::MutableHandle<JS::Value>, ErrorResult& aRv);
244 static RefPtr<SyncReadFile> OpenFileForSyncReading(GlobalObject& aGlobal,
245 const nsAString& aPath,
246 ErrorResult& aRv);
248 class JsBuffer;
251 * The kind of buffer to allocate.
253 * This controls what kind of JS object (a JSString or a Uint8Array) is
254 * returned by |ToJSValue()|.
256 enum class BufferKind {
257 String,
258 Uint8Array,
261 private:
262 ~IOUtils() = default;
264 template <typename T>
265 using IOPromise = MozPromise<T, IOError, true>;
267 friend class IOUtilsShutdownBlocker;
268 struct InternalFileInfo;
269 struct InternalWriteOpts;
270 class MozLZ4;
271 class EventQueue;
272 class State;
274 template <typename Fn>
275 static already_AddRefed<Promise> WithPromiseAndState(GlobalObject& aGlobal,
276 ErrorResult& aError,
277 Fn aFn);
280 * Dispatch a task on the event queue and resolve or reject the associated
281 * promise based on the result.
283 * NB: If the calling thread is a worker, this function takes care of keepting
284 * it alive until the |IOPromise| can complete.
286 * @param aPromise The promise corresponding to the task running on the event
287 * queue.
288 * @param aFunc The task to run.
290 template <typename OkT, typename Fn>
291 static void DispatchAndResolve(EventQueue* aQueue, Promise* aPromise,
292 Fn aFunc);
295 * Creates a new JS Promise.
297 * @return The new promise, or |nullptr| on failure.
299 static already_AddRefed<Promise> CreateJSPromise(GlobalObject& aGlobal,
300 ErrorResult& aError);
302 // Allow conversion of |InternalFileInfo| with |ToJSValue|.
303 friend bool ToJSValue(JSContext* aCx,
304 const InternalFileInfo& aInternalFileInfo,
305 JS::MutableHandle<JS::Value> aValue);
308 * Attempts to read the entire file at |aPath| into a buffer.
310 * @param aFile The location of the file.
311 * @param aOffset The offset to start reading from.
312 * @param aMaxBytes If |Some|, then only read up this this number of bytes,
313 * otherwise attempt to read the whole file.
314 * @param aDecompress If true, decompress the bytes read from disk before
315 * returning the result to the caller.
316 * @param aBufferKind The kind of buffer to allocate.
318 * @return A buffer containing the entire (decompressed) file contents, or an
319 * error.
321 static Result<JsBuffer, IOError> ReadSync(nsIFile* aFile,
322 const uint64_t aOffset,
323 const Maybe<uint32_t> aMaxBytes,
324 const bool aDecompress,
325 BufferKind aBufferKind);
328 * Attempts to read the entire file at |aPath| as a UTF-8 string.
330 * @param aFile The location of the file.
331 * @param aDecompress If true, decompress the bytes read from disk before
332 * returning the result to the caller.
334 * @return The (decompressed) contents of the file re-encoded as a UTF-16
335 * string.
337 static Result<JsBuffer, IOError> ReadUTF8Sync(nsIFile* aFile,
338 const bool aDecompress);
341 * Attempt to write the entirety of |aByteArray| to the file at |aPath|.
342 * This may occur by writing to an intermediate destination and performing a
343 * move, depending on |aOptions|.
345 * @param aFile The location of the file.
346 * @param aByteArray The data to write to the file.
347 * @param aOptions Options to modify the way the write is completed.
349 * @return The number of bytes written to the file, or an error if the write
350 * failed or was incomplete.
352 static Result<uint32_t, IOError> WriteSync(
353 nsIFile* aFile, const Span<const uint8_t>& aByteArray,
354 const InternalWriteOpts& aOptions);
357 * Attempts to move the file located at |aSourceFile| to |aDestFile|.
359 * @param aSourceFile The location of the file to move.
360 * @param aDestFile The destination for the file.
361 * @param aNoOverWrite If true, abort with an error if a file already exists
362 * at |aDestFile|. Otherwise, the file will be overwritten by the move.
364 * @return Ok if the file was moved successfully, or an error.
366 static Result<Ok, IOError> MoveSync(nsIFile* aSourceFile, nsIFile* aDestFile,
367 bool aNoOverwrite);
370 * Attempts to copy the file at |aSourceFile| to |aDestFile|.
372 * @param aSourceFile The location of the file to copy.
373 * @param aDestFile The destination that the file will be copied to.
375 * @return Ok if the operation was successful, or an error.
377 static Result<Ok, IOError> CopySync(nsIFile* aSourceFile, nsIFile* aDestFile,
378 bool aNoOverWrite, bool aRecursive);
381 * Provides the implementation for |CopySync| and |MoveSync|.
383 * @param aMethod A pointer to one of |nsIFile::MoveTo| or |CopyTo|
384 * instance methods.
385 * @param aMethodName The name of the method to the performed. Either "move"
386 * or "copy".
387 * @param aSource The source file to be copied or moved.
388 * @param aDest The destination file.
389 * @param aNoOverwrite If true, allow overwriting |aDest| during the copy or
390 * move. Otherwise, abort with an error if the file would
391 * be overwritten.
393 * @return Ok if the operation was successful, or an error.
395 template <typename CopyOrMoveFn>
396 static Result<Ok, IOError> CopyOrMoveSync(CopyOrMoveFn aMethod,
397 const char* aMethodName,
398 nsIFile* aSource, nsIFile* aDest,
399 bool aNoOverwrite);
402 * Attempts to remove the file located at |aFile|.
404 * @param aFile The location of the file.
405 * @param aIgnoreAbsent If true, suppress errors due to an absent target file.
406 * @param aRecursive If true, attempt to recursively remove descendant
407 * files. This option is safe to use even if the target
408 * is not a directory.
410 * @return Ok if the file was removed successfully, or an error.
412 static Result<Ok, IOError> RemoveSync(nsIFile* aFile, bool aIgnoreAbsent,
413 bool aRecursive);
416 * Attempts to create a new directory at |aFile|.
418 * @param aFile The location of the directory to create.
419 * @param aCreateAncestors If true, create missing ancestor directories as
420 * needed. Otherwise, report an error if the target
421 * has non-existing ancestor directories.
422 * @param aIgnoreExisting If true, suppress errors that occur if the target
423 * directory already exists. Otherwise, propagate the
424 * error if it occurs.
425 * @param aMode Optional file mode. Defaults to 0777 to allow the
426 * system umask to compute the best mode for the new
427 * directory.
429 * @return Ok if the directory was created successfully, or an error.
431 static Result<Ok, IOError> MakeDirectorySync(nsIFile* aFile,
432 bool aCreateAncestors,
433 bool aIgnoreExisting,
434 int32_t aMode = 0777);
437 * Attempts to stat a file at |aFile|.
439 * @param aFile The location of the file.
441 * @return An |InternalFileInfo| struct if successful, or an error.
443 static Result<IOUtils::InternalFileInfo, IOError> StatSync(nsIFile* aFile);
446 * Attempts to update the last access or modification time of the file at
447 * |aFile|.
449 * @param aFile The location of the file.
450 * @param SetTimeFn A member function pointer to either
451 * nsIFile::SetLastAccessedTime or
452 * nsIFile::SetLastModifiedTime.
453 * @param aNewTime Some value in milliseconds since Epoch.
455 * @return Timestamp of the file if the operation was successful, or an error.
457 static Result<int64_t, IOError> SetTimeSync(nsIFile* aFile,
458 SetTimeFn aSetTimeFn,
459 int64_t aNewTime);
462 * Returns the immediate children of the directory at |aFile|, if any.
464 * @param aFile The location of the directory.
466 * @return An array of absolute paths identifying the children of |aFile|.
467 * If there are no children, an empty array. Otherwise, an error.
469 static Result<nsTArray<nsString>, IOError> GetChildrenSync(
470 nsIFile* aFile, bool aIgnoreAbsent);
473 * Set the permissions of the given file.
475 * Windows does not make a distinction between user, group, and other
476 * permissions like UNICES do. If a permission flag is set for any of user,
477 * group, or other has a permission, then all users will have that
478 * permission.
480 * @param aFile The location of the file.
481 * @param aPermissions The permissions to set, as a UNIX file mode.
483 * @return |Ok| if the permissions were successfully set, or an error.
485 static Result<Ok, IOError> SetPermissionsSync(nsIFile* aFile,
486 const uint32_t aPermissions);
489 * Return whether or not the file exists.
491 * @param aFile The location of the file.
493 * @return Whether or not the file exists.
495 static Result<bool, IOError> ExistsSync(nsIFile* aFile);
498 * Create a file or directory with a unique path.
500 * @param aFile The location of the file or directory (including prefix)
501 * @param aFileType One of |nsIFile::NORMAL_FILE_TYPE| or
502 * |nsIFile::DIRECTORY_TYPE|.
503 * @param aperms The permissions to create the file or directory with.
505 * @return A unique path.
507 static Result<nsString, IOError> CreateUniqueSync(
508 nsIFile* aFile, const uint32_t aFileType, const uint32_t aPermissions);
511 * Compute the hash of a file.
513 * @param aFile The file to hash.
514 * @param aAlgorithm The hashing algorithm to use.
516 * @return The hash of the file, as a hex digest.
518 static Result<nsCString, IOError> ComputeHexDigestSync(
519 nsIFile* aFile, const HashAlgorithm aAlgorithm);
521 #if defined(XP_WIN)
523 * Return the Windows-specific attributes of the file.
525 * @param aFile The location of the file.
527 * @return The Windows-specific attributes of the file.
529 static Result<uint32_t, IOError> GetWindowsAttributesSync(nsIFile* aFile);
532 * Set the Windows-specific attributes of the file.
534 * @param aFile The location of the file.
535 * @param aAttrs The attributes to set on the file.
537 * @return |Ok| if the attributes were successfully set, or an error.
539 static Result<Ok, IOError> SetWindowsAttributesSync(
540 nsIFile* aFile, const uint32_t aSetAttrs, const uint32_t aClearAttrs);
541 #elif defined(XP_MACOSX)
542 static Result<bool, IOError> HasMacXAttrSync(nsIFile* aFile,
543 const nsCString& aAttr);
544 static Result<nsTArray<uint8_t>, IOError> GetMacXAttrSync(
545 nsIFile* aFile, const nsCString& aAttr);
546 static Result<Ok, IOError> SetMacXAttrSync(nsIFile* aFile,
547 const nsCString& aAttr,
548 const nsTArray<uint8_t>& aValue);
549 static Result<Ok, IOError> DelMacXAttrSync(nsIFile* aFile,
550 const nsCString& aAttr);
551 #endif
553 static void GetShutdownClient(GlobalObject& aGlobal,
554 JS::MutableHandle<JS::Value> aClient,
555 ErrorResult& aRv, const ShutdownPhase aPhase);
557 enum class EventQueueStatus {
558 Uninitialized,
559 Initialized,
560 Shutdown,
563 enum class ShutdownBlockerStatus {
564 Uninitialized,
565 Initialized,
566 Failed,
570 * Internal IOUtils state.
572 class State {
573 public:
574 StaticAutoPtr<EventQueue> mEventQueue;
575 EventQueueStatus mQueueStatus = EventQueueStatus::Uninitialized;
576 ShutdownBlockerStatus mBlockerStatus = ShutdownBlockerStatus::Uninitialized;
579 * Set up shutdown hooks to free our internals at shutdown.
581 * NB: Must be called on main thread.
583 void SetShutdownHooks();
586 using StateMutex = StaticDataMutex<State>;
589 * Lock the state mutex and return a handle. If shutdown has not yet
590 * finished, the internals will be constructed if necessary.
592 * @returns A handle to the internal state, which can be used to retrieve the
593 * event queue.
594 * If |Some| is returned, |mEventQueue| is guaranteed to be
595 * initialized. If shutdown has finished, |Nothing| is returned.
597 static Maybe<StateMutex::AutoLock> GetState();
599 static StateMutex sState;
603 * The IOUtils event queue.
605 class IOUtils::EventQueue final {
606 friend void IOUtils::State::SetShutdownHooks();
608 public:
609 EventQueue();
611 EventQueue(const EventQueue&) = delete;
612 EventQueue(EventQueue&&) = delete;
613 EventQueue& operator=(const EventQueue&) = delete;
614 EventQueue& operator=(EventQueue&&) = delete;
617 * Dispatch a task on the event queue.
619 * NB: If using this directly from |IOUtils| instead of
620 * |IOUtils::DispatchAndResolve| *and* the calling thread is a worker, you
621 * *must* take care to keep the worker thread alive until the |IOPromise|
622 * resolves or rejects. See the implementation of
623 * |IOUtils::DispatchAndResolve| or |IOUtils::GetWindowsAttributes| for an
624 * example.
626 * @param aFunc The task to dispatch on the event queue.
628 * @return A promise that resolves to the task's return value or rejects with
629 * an error.
631 template <typename OkT, typename Fn>
632 RefPtr<IOPromise<OkT>> Dispatch(Fn aFunc);
634 Result<already_AddRefed<nsIAsyncShutdownBarrier>, nsresult>
635 GetShutdownBarrier(const ShutdownPhase aPhase);
636 Result<already_AddRefed<nsIAsyncShutdownClient>, nsresult> GetShutdownClient(
637 const ShutdownPhase aPhase);
639 private:
640 nsresult SetShutdownHooks();
642 nsCOMPtr<nsISerialEventTarget> mBackgroundEventTarget;
643 IOUtils::PhaseArray<nsCOMPtr<nsIAsyncShutdownBarrier>> mBarriers;
647 * An error class used with the |Result| type returned by most private |IOUtils|
648 * methods.
650 class IOUtils::IOError {
651 public:
652 MOZ_IMPLICIT IOError(nsresult aCode) : mCode(aCode), mMessage(Nothing()) {}
655 * Replaces the message associated with this error.
657 template <typename... Args>
658 IOError WithMessage(const char* const aMessage, Args... aArgs) {
659 mMessage.emplace(nsPrintfCString(aMessage, aArgs...));
660 return *this;
662 IOError WithMessage(const char* const aMessage) {
663 mMessage.emplace(nsCString(aMessage));
664 return *this;
666 IOError WithMessage(const nsCString& aMessage) {
667 mMessage.emplace(aMessage);
668 return *this;
672 * Returns the |nsresult| associated with this error.
674 nsresult Code() const { return mCode; }
677 * Maybe returns a message associated with this error.
679 const Maybe<nsCString>& Message() const { return mMessage; }
681 private:
682 nsresult mCode;
683 Maybe<nsCString> mMessage;
687 * This is an easier to work with representation of a |mozilla::dom::FileInfo|
688 * for private use in the IOUtils implementation.
690 * Because web IDL dictionaries are not easily copy/moveable, this class is
691 * used instead, until converted to the proper |mozilla::dom::FileInfo| before
692 * returning any results to JavaScript.
694 struct IOUtils::InternalFileInfo {
695 nsString mPath;
696 FileType mType = FileType::Other;
697 uint64_t mSize = 0;
698 Maybe<PRTime> mCreationTime; // In ms since epoch.
699 PRTime mLastAccessed = 0; // In ms since epoch.
700 PRTime mLastModified = 0; // In ms since epoch.
701 uint32_t mPermissions = 0;
705 * This is an easier to work with representation of a
706 * |mozilla::dom::WriteOptions| for private use in the |IOUtils|
707 * implementation.
709 * Because web IDL dictionaries are not easily copy/moveable, this class is
710 * used instead.
712 struct IOUtils::InternalWriteOpts {
713 RefPtr<nsIFile> mBackupFile;
714 RefPtr<nsIFile> mTmpFile;
715 WriteMode mMode;
716 bool mFlush = false;
717 bool mCompress = false;
719 static Result<InternalWriteOpts, IOUtils::IOError> FromBinding(
720 const WriteOptions& aOptions);
724 * Re-implements the file compression and decompression utilities found
725 * in toolkit/components/lz4/lz4.js
727 * This implementation uses the non-standard data layout:
729 * - MAGIC_NUMBER (8 bytes)
730 * - content size (uint32_t, little endian)
731 * - content, as obtained from mozilla::Compression::LZ4::compress
733 * See bug 1209390 for more info.
735 class IOUtils::MozLZ4 {
736 public:
737 static constexpr std::array<uint8_t, 8> MAGIC_NUMBER{
738 {'m', 'o', 'z', 'L', 'z', '4', '0', '\0'}};
740 static const uint32_t HEADER_SIZE = 8 + sizeof(uint32_t);
743 * Compresses |aUncompressed| byte array, and returns a byte array with the
744 * correct format whose contents may be written to disk.
746 static Result<nsTArray<uint8_t>, IOError> Compress(
747 Span<const uint8_t> aUncompressed);
750 * Checks |aFileContents| for the correct file header, and returns the
751 * decompressed content.
753 static Result<IOUtils::JsBuffer, IOError> Decompress(
754 Span<const uint8_t> aFileContents, IOUtils::BufferKind);
757 class IOUtilsShutdownBlocker : public nsIAsyncShutdownBlocker,
758 public nsIAsyncShutdownCompletionCallback {
759 public:
760 NS_DECL_THREADSAFE_ISUPPORTS
761 NS_DECL_NSIASYNCSHUTDOWNBLOCKER
762 NS_DECL_NSIASYNCSHUTDOWNCOMPLETIONCALLBACK
764 explicit IOUtilsShutdownBlocker(const IOUtils::ShutdownPhase aPhase)
765 : mPhase(aPhase) {}
767 private:
768 virtual ~IOUtilsShutdownBlocker() = default;
771 * Called on the main thread after the event queue has been flushed.
773 void OnFlush();
775 static constexpr IOUtils::PhaseArray<const char16_t*> PHASE_NAMES{
776 u"profile-before-change",
777 u"profile-before-change-telemetry",
778 u"xpcom-will-shutdown",
781 // The last shutdown phase before we should shut down the event loop.
782 static constexpr auto LAST_IO_PHASE = IOUtils::ShutdownPhase::SendTelemetry;
784 IOUtils::ShutdownPhase mPhase;
785 nsCOMPtr<nsIAsyncShutdownClient> mParentClient;
789 * A buffer that is allocated inside one of JS heaps so that it can be converted
790 * to a JSString or Uint8Array object with at most one copy in the worst case.
792 class IOUtils::JsBuffer final {
793 public:
795 * Create a new buffer of the given kind with the requested capacity.
797 * @param aBufferKind The kind of buffer to create (either a string or an
798 * array).
799 * @param aCapacity The capacity of the buffer.
801 * @return Either a successfully created buffer or an error if it could not be
802 * allocated.
804 static Result<JsBuffer, IOUtils::IOError> Create(
805 IOUtils::BufferKind aBufferKind, size_t aCapacity);
808 * Create a new, empty buffer.
810 * This operation cannot fail.
812 * @param aBufferKind The kind of buffer to create (either a string or an
813 * array).
815 * @return An empty JsBuffer.
817 static JsBuffer CreateEmpty(IOUtils::BufferKind aBufferKind);
819 JsBuffer(const JsBuffer&) = delete;
820 JsBuffer(JsBuffer&& aOther) noexcept;
821 JsBuffer& operator=(const JsBuffer&) = delete;
822 JsBuffer& operator=(JsBuffer&& aOther) noexcept;
824 size_t Length() { return mLength; }
825 char* Elements() { return mBuffer.get(); }
826 void SetLength(size_t aNewLength) {
827 MOZ_RELEASE_ASSERT(aNewLength <= mCapacity);
828 mLength = aNewLength;
832 * Return a span for writing to the buffer.
834 * |SetLength| should be called after the buffer has been written to.
836 * @returns A span for writing to. The size of the span is the entire
837 * allocated capacity.
839 Span<char> BeginWriting() {
840 MOZ_RELEASE_ASSERT(mBuffer.get());
841 return Span(mBuffer.get(), mCapacity);
845 * Return a span for reading from.
847 * @returns A span for reading form. The size of the span is the set length
848 * of the buffer.
850 Span<const char> BeginReading() const {
851 MOZ_RELEASE_ASSERT(mBuffer.get() || mLength == 0);
852 return Span(mBuffer.get(), mLength);
856 * Consume the JsBuffer and convert it into a JSString.
858 * NOTE: This method asserts the buffer was allocated as a string buffer.
860 * @param aBuffer The buffer to convert to a string. After this call, the
861 * buffer will be invaldated and |IntoString| cannot be called
862 * again.
864 * @returns A JSString with the contents of |aBuffer|.
866 static JSString* IntoString(JSContext* aCx, JsBuffer aBuffer);
869 * Consume the JsBuffer and convert it into a Uint8Array.
871 * NOTE: This method asserts the buffer was allocated as an array buffer.
873 * @param aBuffer The buffer to convert to an array. After this call, the
874 * buffer will be invalidated and |IntoUint8Array| cannot be
875 * called again.
877 * @returns A JSBuffer
879 static JSObject* IntoUint8Array(JSContext* aCx, JsBuffer aBuffer);
881 friend bool ToJSValue(JSContext* aCx, JsBuffer&& aBuffer,
882 JS::MutableHandle<JS::Value> aValue);
884 private:
885 IOUtils::BufferKind mBufferKind;
886 size_t mCapacity;
887 size_t mLength;
888 JS::UniqueChars mBuffer;
890 JsBuffer(BufferKind aBufferKind, size_t aCapacity);
893 class SyncReadFile : public nsISupports, public nsWrapperCache {
894 public:
895 SyncReadFile(nsISupports* aParent, RefPtr<nsFileRandomAccessStream>&& aStream,
896 int64_t aSize);
898 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
899 NS_DECL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(SyncReadFile)
901 nsISupports* GetParentObject() const { return mParent; }
903 virtual JSObject* WrapObject(JSContext* aCx,
904 JS::Handle<JSObject*> aGivenProto) override;
906 int64_t Size() const { return mSize; }
907 void ReadBytesInto(const Uint8Array&, const int64_t, ErrorResult& aRv);
908 void Close();
910 private:
911 virtual ~SyncReadFile();
913 nsCOMPtr<nsISupports> mParent;
914 RefPtr<nsFileRandomAccessStream> mStream;
915 int64_t mSize = 0;
918 } // namespace dom
919 } // namespace mozilla
921 #endif