Files
palemoon27/toolkit/components/osfile/NativeOSFileInternals.cpp
roytam1 69d1f32ff7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1268085 - Remove unused post barrier callbacks r=terrence (0ab13411c9)
- Bug 1267699 - Move some public types to the right namespace; r=sfink (3d5008e610)
- Bug 1267550 (part 1) - Rename MOZ_MUST_USE as MOZ_MUST_USE_TYPE. r=ehsan. (6f47375796)
- Bug 1259021 - Rename Vector::extractRawBuffer to extractOrCopyRawBuffer r=Waldo (97ca94495b)
- Bug 1259021 - Add Vector::extractRawBuffer method that doesn't copy the buffer r=Waldo (e58deec48f)
- Bug 1265892 - Change Vector to use Impl::new_ consistently. r=Waldo (7a52d21b29)
- Bug 1267912 - Rename nsNetUtil.inl as nsNetUtilInlines.h. r=valentin. (548a41b293)
- Bug 1265690 part 1 - Mark StringBuffer methods WARN_UNUSED_RESULT, fix OOM issues. r=jonco (0d7e6837e3)
- Bug 1265690 part 2 - Fix some more OOM issues in TypedObject code. r=jonco (b60902453e)
- Bug 1263490 - Part 2: Add GetFirstDollarIndex intrinsic and use it inRegExpReplace. r=till (4ba19db8c4)
- Bug 1263490 - Part 3: Inline GetFirstDollarIndex intrinsic. r=h4writer (e7d9b5d1cc)
- Bug 1263490 - Part 4: Fold GetFirstDollarIndex into a integer constant. r=h4writer (3479c7d1af)
- Bug 1267269 - Make MIRType an enum class. r=bbouvier (d580ef372a)
- Bug 1259295 - BaldrMonkey: Postorder (r=luke) (6ef7a77663)
- Bug 1254142: BaldrMonkey: make br_table yield (r=luke) (80e7635e58)
- Bug 1263202 - BaldrMonkey: switch to arities on branches, calls and return (r=bbouvier) (f5a0358634)
- Bug 1236358 - Improper reading of string16 in Pickle::ReadString16. r=jld (8370ba6a0b)
- Bug 1263205 - BaldrMonkey: Update section headers for proposed spec changes (r=luke) (0def2e6bc2)
- Bug 1263205 - BaldrMonkey: Update for proposed new section names (r=luke) (e57f0e3367)
- Bug 1263205 - BaldrMonkey: Add 'form' field to types section (r=bbouvier) (794edc890f)
- Bug 1259021 - Use in-place storage in AutoStableStringChars to avoid allocation for short strings r=jandem r=Waldo (ffb53cbcf4)
- Bug 1267550 (part 2) - Rename MOZ_WARN_UNUSED_RESULT as MOZ_MUST_USE. r=froydnj. (47bc674b86)
- Bug 1268518: Baldr: implement int32/int64 rotations; r=luke (0d5eedccce)
- Bug 1255008: IonMonkey - Add a by default disabled flow sensitive alias analysis pass, r=jandem (521c585d75)
- Bug 1266781: Baldr: implement proper checked truncations to integer types; r=sunfish (46078fb3d3)
- Bug 1266781: Rename MTruncateToInt64 into MWasmTruncateInt64; r=sunfish (c7d7d1ac11)
- Bug 1266781: Add new traps; r=luke (b7ed3d44e6)
- Bug 1268024: Pass the atomic attribute down to EmitHeapAccess; r=luke (6195f7d7a3)
- Bug 1268024: A few cleanups related to loads/stores; r=luke (88141e3a01)
- Bug 1258312 - Make Pickle::Resize infallible r=jld (241ee9b60d)
- Bug 1162772, part 1 - Allow CompartmentCreationOptions to store Secure Context state. r=jorendorff (ff666384cf)
- Bug 1162772, part 2 - Expose whether SEC_FORCE_INHERIT_PRINCIPAL was dropped from an nsILoadInfo. r=bz (ada46f86bf)
- Bug 1162772, part 3 - Add a getChannelResultPrincipalIfNotSandboxed method to nsIScriptSecurityManager. r=bz (5b1d9f6807)
- Bug 1162772, part 4 - Implement nsGlobalWindow::IsSecureContext. r=bz (f392f439c9)
- Bug 1162772, part 5 - Expose Window.isSecureContext to content. r=bz (e7296e2cf1)
- Bug 1267509 - Make nsContentSecurityManager::IsURIPotentiallyTrustworthy act on an nsIPrincipal. r=bz (83de80350a)
- Bug 1219098 - Use UniquePtr in UncompressedSourceCache, for it is good (r=jandem) (b68769c729)
- Bug 1244279 - Part 1: Take a bit in ObjectElements::Flags to indicate whether the object is in the whole cell store buffer. r=terrence (968cf373f9)
- Bug 1244279 - Part 0: Add a GC ubench for large arrays with both elements and properties. r=terrence (ec76b48323)
- Bug 1255925 - Give a name to getters/setters and integer-named methods. r=efaust (f978cc6916)
- Bug 888969 - Make the getPrototypeOf/setPrototypeOf traps scriptable. r=efaust, r=bholley (eb2325a9ea)
- Bug 1267557 part 0 - Move JS poison constants to jsutil.h. r=jonco (65afc690d2)
- Bug 1267557 part 1 - Also poison bytes allocated before the actual jitcode. r=nbp (70f0b327d3)
- Bug 1267557 part 2 - Use different jitcode poison values. r=nbp (08008ab9dc)
- Bug 1267557 part 3 - Define JS_SWEPT_CODE_PATTERN for mips. r=nbp (17e894d59d)
- Bug 1267449 - Do not infinite loop in js_fputs; r=jimb (67f961b6cd)
- Bug 1219098 - Reenable compression on large sources, but revert to uncompressed if decompression happens (r=jandem) (b44ee8d77d)
- Bug 1267551 (part 1) - Use MOZ_MUST_USE more in jsnum.h. r=jonco. (d2476bf8f4)
- Bug 1267551 (part 2) - Use MOZ_MUST_USE more in js/src/ds/. r=jonco. (4ff5d9aa88)
- Bug 1267412 - Use MutableHandleValue instead of pointer-to-AutoValueVector; r=sfink (3f6dd284bb)
- Bug 1266406 - Use EnumSet<AllocKind> to simplify GC sweeping phase information r=terrence (64811500e7)
- Bug 1266457 - Update pointers in GC things in two phases when compacting r=terrence (f6f5bc4e4d)
- Bug 1266457 - Simplify typed object trace hook r=terence (3b06c8d1e5)
- Bug 1268541 - Compact arenas containing base shapes r=terrence (b458b92eea)
- Bug 1268805 - Implement PrivateGCThingValue. (r=terrence) (deec9a83ae)
- Bug 1268415: Initialize members in UpdatePointerTasks; r=jonco (6cb219005a)
- Bug 1268501 - Release the GC lock periodically when releasing arenas on the backgound thread r=terrence (37f0997682)
- Bug 1263572 - Wait for background sweeping to finish before checking base shapes r=terrence (354801a411)
- Bug 1266887 - Store Rooted heads on the Zone; r=sfink (91c0101ee3)
- Bug 1266402 - Add iteration to EnumSet<T> so that it can be used in range-based for loops r=Waldo (e9507a2524)
- Bug 1266404 - Allow construction of an EnumSet<T> using an initializer list r=Waldo (1b6d340e99)
- Bug 1254020 - Always compute theme scaling factor when per-monitor dpi aware, even if only a single display is currently present. r=emk (a00cda21f4)
- Bug 1263525 - Add dedicated function for std_Array self-hosted intrinsic. r=efaust (449d8bb7eb)
- Bug 1255925 - Change JSFunction::name to return a JSAtom. r=efaust (5ab396ce83)
- Bug 888969 - Make our tree's sole implementation of nsIRemoteTagService.getRemoteObjectTag not depend upon the infallibility of [[GetPrototypeOf]] on the object provided to it. r=bz (f388f4bf1f)
- Bug 1264896 - Kill off nsIRemoteTagService and do what it does, in its sole caller, in far-faster C++. r=billm (5ed3fb103d)
- Bug 1268246 - Add a simple Poison class lifetime checker. r=froydnj (7b237bc70e)
- Bug 1249496 - Don't apply dpi-based scaling for window titlebar dimensions when on a secondary display, because windows doesn't scale it. r=emk (64dd706dbc)
- Bug 1164518 - Avoid unnecessary DB updates when caching Safe Browsing results. r=gcp (3cafd9a4df)
- Bug 1264472 - Use nsRunnables in FIDO U2F. r=keeler (3aa9570132)
- Bug 1236060 - Dispatch error should advance queue. r=smaug (74155b75dd)
- Bug 1251697 part 1. Thread an ErrorResult reference through the worker XHR WorkerThreadProxySyncRunnable implementations. r=khuey (77804cbb7c)
- Bug 1251697 part 2. Have WorkerThreadProxySyncRunnable hand the ErrorResult reference it holds to its ResponseRunnable so it can report exceptions on there instead of on a JSContext. r=khuey (355c9ee313)
- Bug 1251697 part 3. Remove the JSContext argument of StopSyncLoopRunnable::MaybeSetException. r=khuey (010f5b1058)
- Bug 1155328. r=smaug (e1f8dac304)
- Bug 1265927: Move nsRunnable to mozilla::Runnable, CancelableRunnable to mozilla::CancelableRunnable. r=froydnj (f83bfcae02)
- Bug 1239946 - Change test to return error on Speak. r=eeejay (1d402beb02)
- Bug 1254378 - Update synth tests and introduce no voiceschanged test. r=smaug (f5823bb70e)
- Bug 1251627. Fix XMLHttpRequest.send() to follow the spec better in terms of the exceptions it throws. r=khuey (cd0e321948)
- Bug 1268868: [MSE] P1. Re-enable gap detection within a media segment. r=gerald (b8b8df4bc2)
- Bug 1268868: [MSE] P2. Reset longest duration after keyframe is seen. r=gerald (2b1401465c)
- Bug 1268868: [MSE] P3. Prevent crash should gap be detected in content. r=gerald (063d9376fc)
- Bug 1254378 - Implement nsISynthVoiceRegistry.notifyVoicesChanged. r=smaug (4b63b1c360)
- Bug 1266804 - Un-inline js::Unbox(); r=jorendorff (0f288b6173)
- Bug 1268863 - Report ScriptSources that are only reachable via AsmJSModule (r=njn) (5ba40acb64)
- bump version to 45.1b1 (1414db0ca8)
- Bug 1262062 - remove old futex names. r=bbouvier (62662bdd2e)
- memory: build fix after renaming MOZ_WARN_UNUSED_RESULT (7254dc8d53)
- import from mozilla:
 - Bug 1268725 - BaldrMonkey: Refactor away the internal storage from ExprIter. r=luke (1931bd636f17)
 - Bug 1268725 - BaldrMonkey: Convert default arguments into explicit arguments. r=luke (c8a11b8b6bbd) (867ec715d6)
2024-08-21 10:45:07 +08:00

917 lines
27 KiB
C++

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Native implementation of some OS.File operations.
*/
#include "nsString.h"
#include "nsNetCID.h"
#include "nsThreadUtils.h"
#include "nsXPCOMCID.h"
#include "nsCycleCollectionParticipant.h"
#include "nsServiceManagerUtils.h"
#include "nsProxyRelease.h"
#include "nsINativeOSFileInternals.h"
#include "NativeOSFileInternals.h"
#include "mozilla/dom/NativeOSFileInternalsBinding.h"
#include "nsIUnicodeDecoder.h"
#include "nsIEventTarget.h"
#include "mozilla/dom/EncodingUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Scoped.h"
#include "mozilla/HoldDropJSObjects.h"
#include "mozilla/TimeStamp.h"
#include "prio.h"
#include "prerror.h"
#include "private/pprio.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "js/Utility.h"
#include "xpcpublic.h"
#include <algorithm>
#if defined(XP_UNIX)
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/uio.h>
#endif // defined (XP_UNIX)
#if defined(XP_WIN)
#include <windows.h>
#endif // defined (XP_WIN)
namespace mozilla {
MOZ_TYPE_SPECIFIC_SCOPED_POINTER_TEMPLATE(ScopedPRFileDesc, PRFileDesc, PR_Close)
namespace {
// Utilities for safely manipulating ArrayBuffer contents even in the
// absence of a JSContext.
/**
* The C buffer underlying to an ArrayBuffer. Throughout the code, we manipulate
* this instead of a void* buffer, as this lets us transfer data across threads
* and into JavaScript without copy.
*/
struct ArrayBufferContents {
/**
* The data of the ArrayBuffer. This is the pointer manipulated to
* read/write the contents of the buffer.
*/
uint8_t* data;
/**
* The number of bytes in the ArrayBuffer.
*/
size_t nbytes;
};
/**
* RAII for ArrayBufferContents.
*/
struct ScopedArrayBufferContentsTraits {
typedef ArrayBufferContents type;
const static type empty() {
type result = {0, 0};
return result;
}
static void release(type ptr) {
js_free(ptr.data);
ptr.data = nullptr;
ptr.nbytes = 0;
}
};
struct MOZ_NON_TEMPORARY_CLASS ScopedArrayBufferContents: public Scoped<ScopedArrayBufferContentsTraits> {
explicit ScopedArrayBufferContents(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM):
Scoped<ScopedArrayBufferContentsTraits>(MOZ_GUARD_OBJECT_NOTIFIER_ONLY_PARAM_TO_PARENT)
{ }
explicit ScopedArrayBufferContents(const ArrayBufferContents& v
MOZ_GUARD_OBJECT_NOTIFIER_PARAM):
Scoped<ScopedArrayBufferContentsTraits>(v MOZ_GUARD_OBJECT_NOTIFIER_PARAM_TO_PARENT)
{ }
ScopedArrayBufferContents& operator=(ArrayBufferContents ptr) {
Scoped<ScopedArrayBufferContentsTraits>::operator=(ptr);
return *this;
}
/**
* Request memory for this ArrayBufferContent. This memory may later
* be used to create an ArrayBuffer object (possibly on another
* thread) without copy.
*
* @return true In case of success, false otherwise.
*/
bool Allocate(uint32_t length) {
dispose();
ArrayBufferContents& value = rwget();
void *ptr = js_calloc(1, length);
if (ptr) {
value.data = (uint8_t *) ptr;
value.nbytes = length;
return true;
}
return false;
}
private:
explicit ScopedArrayBufferContents(ScopedArrayBufferContents& source) = delete;
ScopedArrayBufferContents& operator=(ScopedArrayBufferContents& source) = delete;
};
///////// Cross-platform issues
// Platform specific constants. As OS.File always uses OS-level
// errors, we need to map a few high-level errors to OS-level
// constants.
#if defined(XP_UNIX)
#define OS_ERROR_NOMEM ENOMEM
#define OS_ERROR_INVAL EINVAL
#define OS_ERROR_TOO_LARGE EFBIG
#define OS_ERROR_RACE EIO
#elif defined(XP_WIN)
#define OS_ERROR_NOMEM ERROR_NOT_ENOUGH_MEMORY
#define OS_ERROR_INVAL ERROR_BAD_ARGUMENTS
#define OS_ERROR_TOO_LARGE ERROR_FILE_TOO_LARGE
#define OS_ERROR_RACE ERROR_SHARING_VIOLATION
#else
#error "We do not have platform-specific constants for this platform"
#endif
///////// Results of OS.File operations
/**
* Base class for results passed to the callbacks.
*
* This base class implements caching of JS values returned to the client.
* We make use of this caching in derived classes e.g. to avoid accidents
* when we transfer data allocated on another thread into JS. Note that
* this caching can lead to cycles (e.g. if a client adds a back-reference
* in the JS value), so we implement all Cycle Collector primitives in
* AbstractResult.
*/
class AbstractResult: public nsINativeOSFileResult {
public:
NS_DECL_NSINATIVEOSFILERESULT
NS_DECL_CYCLE_COLLECTING_ISUPPORTS
NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(AbstractResult)
/**
* Construct the result object. Must be called on the main thread
* as the AbstractResult is cycle-collected.
*
* @param aStartDate The instant at which the operation was
* requested. Used to collect Telemetry statistics.
*/
explicit AbstractResult(TimeStamp aStartDate)
: mStartDate(aStartDate)
{
MOZ_ASSERT(NS_IsMainThread());
mozilla::HoldJSObjects(this);
}
/**
* Setup the AbstractResult once data is available.
*
* @param aDispatchDate The instant at which the IO thread received
* the operation request. Used to collect Telemetry statistics.
* @param aExecutionDuration The duration of the operation on the
* IO thread.
*/
void Init(TimeStamp aDispatchDate,
TimeDuration aExecutionDuration) {
MOZ_ASSERT(!NS_IsMainThread());
mDispatchDuration = (aDispatchDate - mStartDate);
mExecutionDuration = aExecutionDuration;
}
/**
* Drop any data that could lead to a cycle.
*/
void DropJSData() {
mCachedResult = JS::UndefinedValue();
}
protected:
virtual ~AbstractResult() {
MOZ_ASSERT(NS_IsMainThread());
DropJSData();
mozilla::DropJSObjects(this);
}
virtual nsresult GetCacheableResult(JSContext *cx, JS::MutableHandleValue aResult) = 0;
private:
TimeStamp mStartDate;
TimeDuration mDispatchDuration;
TimeDuration mExecutionDuration;
JS::Heap<JS::Value> mCachedResult;
};
NS_IMPL_CYCLE_COLLECTING_ADDREF(AbstractResult)
NS_IMPL_CYCLE_COLLECTING_RELEASE(AbstractResult)
NS_IMPL_CYCLE_COLLECTION_CLASS(AbstractResult)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(AbstractResult)
NS_INTERFACE_MAP_ENTRY(nsINativeOSFileResult)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(AbstractResult)
NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mCachedResult)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(AbstractResult)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(AbstractResult)
tmp->DropJSData();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMETHODIMP
AbstractResult::GetDispatchDurationMS(double *aDispatchDuration)
{
*aDispatchDuration = mDispatchDuration.ToMilliseconds();
return NS_OK;
}
NS_IMETHODIMP
AbstractResult::GetExecutionDurationMS(double *aExecutionDuration)
{
*aExecutionDuration = mExecutionDuration.ToMilliseconds();
return NS_OK;
}
NS_IMETHODIMP
AbstractResult::GetResult(JSContext *cx, JS::MutableHandleValue aResult)
{
if (mCachedResult.isUndefined()) {
nsresult rv = GetCacheableResult(cx, aResult);
if (NS_FAILED(rv)) {
return rv;
}
mCachedResult = aResult;
return NS_OK;
}
aResult.set(mCachedResult);
return NS_OK;
}
/**
* Return a result as a string.
*
* In this implementation, attribute |result| is a string. Strings are
* passed to JS without copy.
*/
class StringResult final : public AbstractResult
{
public:
explicit StringResult(TimeStamp aStartDate)
: AbstractResult(aStartDate)
{
}
/**
* Initialize the object once the contents of the result as available.
*
* @param aContents The string to pass to JavaScript. Ownership of the
* string and its contents is passed to StringResult. The string must
* be valid UTF-16.
*/
void Init(TimeStamp aDispatchDate,
TimeDuration aExecutionDuration,
nsString& aContents) {
AbstractResult::Init(aDispatchDate, aExecutionDuration);
mContents = aContents;
}
protected:
nsresult GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult) override;
private:
nsString mContents;
};
nsresult
StringResult::GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult)
{
MOZ_ASSERT(NS_IsMainThread());
MOZ_ASSERT(mContents.get());
// Convert mContents to a js string without copy. Note that this
// may have the side-effect of stealing the contents of the string
// from XPCOM and into JS.
if (!xpc::StringToJsval(cx, mContents, aResult)) {
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/**
* Return a result as a Uint8Array.
*
* In this implementation, attribute |result| is a Uint8Array. The array
* is passed to JS without memory copy.
*/
class TypedArrayResult final : public AbstractResult
{
public:
explicit TypedArrayResult(TimeStamp aStartDate)
: AbstractResult(aStartDate)
{
}
/**
* @param aContents The contents to pass to JS. Calling this method.
* transmits ownership of the ArrayBufferContents to the TypedArrayResult.
* Do not reuse this value anywhere else.
*/
void Init(TimeStamp aDispatchDate,
TimeDuration aExecutionDuration,
ArrayBufferContents aContents) {
AbstractResult::Init(aDispatchDate, aExecutionDuration);
mContents = aContents;
}
protected:
nsresult GetCacheableResult(JSContext* cx, JS::MutableHandleValue aResult) override;
private:
ScopedArrayBufferContents mContents;
};
nsresult
TypedArrayResult::GetCacheableResult(JSContext* cx, JS::MutableHandle<JS::Value> aResult)
{
MOZ_ASSERT(NS_IsMainThread());
// We cannot simply construct a typed array using contents.data as
// this would allow us to have several otherwise unrelated
// ArrayBuffers with the same underlying C buffer. As this would be
// very unsafe, we need to cache the result once we have it.
const ArrayBufferContents& contents = mContents.get();
MOZ_ASSERT(contents.data);
JS::Rooted<JSObject*>
arrayBuffer(cx, JS_NewArrayBufferWithContents(cx, contents.nbytes, contents.data));
if (!arrayBuffer) {
return NS_ERROR_OUT_OF_MEMORY;
}
JS::Rooted<JSObject*>
result(cx, JS_NewUint8ArrayWithBuffer(cx, arrayBuffer,
0, contents.nbytes));
if (!result) {
return NS_ERROR_OUT_OF_MEMORY;
}
// The memory of contents has been allocated on a thread that
// doesn't have a JSRuntime, hence without a context. Now that we
// have a context, attach the memory to where it belongs.
JS_updateMallocCounter(cx, contents.nbytes);
mContents.forget();
aResult.setObject(*result);
return NS_OK;
}
//////// Callback events
/**
* An event used to notify asynchronously of an error.
*/
class ErrorEvent final : public Runnable {
public:
/**
* @param aOnSuccess The success callback.
* @param aOnError The error callback.
* @param aDiscardedResult The discarded result.
* @param aOperation The name of the operation, used for error reporting.
* @param aOSError The OS error of the operation, as returned by errno/
* GetLastError().
*
* Note that we pass both the success callback and the error
* callback, as well as the discarded result to ensure that they are
* all released on the main thread, rather than on the IO thread
* (which would hopefully segfault). Also, we pass the callbacks as
* alread_AddRefed to ensure that we do not manipulate main-thread
* only refcounters off the main thread.
*/
ErrorEvent(nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError,
already_AddRefed<AbstractResult>& aDiscardedResult,
const nsACString& aOperation,
int32_t aOSError)
: mOnSuccess(aOnSuccess)
, mOnError(aOnError)
, mDiscardedResult(aDiscardedResult)
, mOSError(aOSError)
, mOperation(aOperation)
{
MOZ_ASSERT(!NS_IsMainThread());
}
NS_METHOD Run() {
MOZ_ASSERT(NS_IsMainThread());
(void)mOnError->Complete(mOperation, mOSError);
// Ensure that the callbacks are released on the main thread.
mOnSuccess = nullptr;
mOnError = nullptr;
mDiscardedResult = nullptr;
return NS_OK;
}
private:
// The callbacks. Maintained as nsMainThreadPtrHandle as they are generally
// xpconnect values, which cannot be manipulated with nsCOMPtr off
// the main thread. We store both the success callback and the
// error callback to ensure that they are safely released on the
// main thread.
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback> mOnSuccess;
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback> mOnError;
RefPtr<AbstractResult> mDiscardedResult;
int32_t mOSError;
nsCString mOperation;
};
/**
* An event used to notify of a success.
*/
class SuccessEvent final : public Runnable {
public:
/**
* @param aOnSuccess The success callback.
* @param aOnError The error callback.
*
* Note that we pass both the success callback and the error
* callback to ensure that they are both released on the main
* thread, rather than on the IO thread (which would hopefully
* segfault). Also, we pass them as alread_AddRefed to ensure that
* we do not manipulate xpconnect refcounters off the main thread
* (which is illegal).
*/
SuccessEvent(nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError,
already_AddRefed<nsINativeOSFileResult>& aResult)
: mOnSuccess(aOnSuccess)
, mOnError(aOnError)
, mResult(aResult)
{
MOZ_ASSERT(!NS_IsMainThread());
}
NS_METHOD Run() {
MOZ_ASSERT(NS_IsMainThread());
(void)mOnSuccess->Complete(mResult);
// Ensure that the callbacks are released on the main thread.
mOnSuccess = nullptr;
mOnError = nullptr;
mResult = nullptr;
return NS_OK;
}
private:
// The callbacks. Maintained as nsMainThreadPtrHandle as they are generally
// xpconnect values, which cannot be manipulated with nsCOMPtr off
// the main thread. We store both the success callback and the
// error callback to ensure that they are safely released on the
// main thread.
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback> mOnSuccess;
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback> mOnError;
RefPtr<nsINativeOSFileResult> mResult;
};
//////// Action events
/**
* Base class shared by actions.
*/
class AbstractDoEvent: public Runnable {
public:
AbstractDoEvent(nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError)
: mOnSuccess(aOnSuccess)
, mOnError(aOnError)
#if defined(DEBUG)
, mResolved(false)
#endif // defined(DEBUG)
{
MOZ_ASSERT(NS_IsMainThread());
}
/**
* Fail, asynchronously.
*/
void Fail(const nsACString& aOperation,
already_AddRefed<AbstractResult>&& aDiscardedResult,
int32_t aOSError = 0) {
Resolve();
RefPtr<ErrorEvent> event = new ErrorEvent(mOnSuccess,
mOnError,
aDiscardedResult,
aOperation,
aOSError);
nsresult rv = NS_DispatchToMainThread(event);
if (NS_FAILED(rv)) {
// Last ditch attempt to release on the main thread - some of
// the members of event are not thread-safe, so letting the
// pointer go out of scope would cause a crash.
NS_ReleaseOnMainThread(event.forget());
}
}
/**
* Succeed, asynchronously.
*/
void Succeed(already_AddRefed<nsINativeOSFileResult>&& aResult) {
Resolve();
RefPtr<SuccessEvent> event = new SuccessEvent(mOnSuccess,
mOnError,
aResult);
nsresult rv = NS_DispatchToMainThread(event);
if (NS_FAILED(rv)) {
// Last ditch attempt to release on the main thread - some of
// the members of event are not thread-safe, so letting the
// pointer go out of scope would cause a crash.
NS_ReleaseOnMainThread(event.forget());
}
}
private:
/**
* Mark the event as complete, for debugging purposes.
*/
void Resolve() {
#if defined(DEBUG)
MOZ_ASSERT(!mResolved);
mResolved = true;
#endif // defined(DEBUG)
}
private:
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback> mOnSuccess;
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback> mOnError;
#if defined(DEBUG)
// |true| once the action is complete
bool mResolved;
#endif // defined(DEBUG)
};
/**
* An abstract event implementing reading from a file.
*
* Concrete subclasses are responsible for handling the
* data obtained from the file and possibly post-processing it.
*/
class AbstractReadEvent: public AbstractDoEvent {
public:
/**
* @param aPath The path of the file.
*/
AbstractReadEvent(const nsAString& aPath,
const uint64_t aBytes,
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError)
: AbstractDoEvent(aOnSuccess, aOnError)
, mPath(aPath)
, mBytes(aBytes)
{
MOZ_ASSERT(NS_IsMainThread());
}
NS_METHOD Run() override {
MOZ_ASSERT(!NS_IsMainThread());
TimeStamp dispatchDate = TimeStamp::Now();
nsresult rv = BeforeRead();
if (NS_FAILED(rv)) {
// Error reporting is handled by BeforeRead();
return NS_OK;
}
ScopedArrayBufferContents buffer;
rv = Read(buffer);
if (NS_FAILED(rv)) {
// Error reporting is handled by Read();
return NS_OK;
}
AfterRead(dispatchDate, buffer);
return NS_OK;
}
private:
/**
* Read synchronously.
*
* Must be called off the main thread.
*
* @param aBuffer The destination buffer.
*/
nsresult Read(ScopedArrayBufferContents& aBuffer)
{
MOZ_ASSERT(!NS_IsMainThread());
ScopedPRFileDesc file;
#if defined(XP_WIN)
// On Windows, we can't use PR_OpenFile because it doesn't
// handle UTF-16 encoding, which is pretty bad. In addition,
// PR_OpenFile opens files without sharing, which is not the
// general semantics of OS.File.
HANDLE handle =
::CreateFileW(mPath.get(),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
/*Security attributes*/nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
/*Template file*/ nullptr);
if (handle == INVALID_HANDLE_VALUE) {
Fail(NS_LITERAL_CSTRING("open"), nullptr, ::GetLastError());
return NS_ERROR_FAILURE;
}
file = PR_ImportFile((PROsfd)handle);
if (!file) {
// |file| is closed by PR_ImportFile
Fail(NS_LITERAL_CSTRING("ImportFile"), nullptr, PR_GetOSError());
return NS_ERROR_FAILURE;
}
#else
// On other platforms, PR_OpenFile will do.
NS_ConvertUTF16toUTF8 path(mPath);
file = PR_OpenFile(path.get(), PR_RDONLY, 0);
if (!file) {
Fail(NS_LITERAL_CSTRING("open"), nullptr, PR_GetOSError());
return NS_ERROR_FAILURE;
}
#endif // defined(XP_XIN)
PRFileInfo64 stat;
if (PR_GetOpenFileInfo64(file, &stat) != PR_SUCCESS) {
Fail(NS_LITERAL_CSTRING("stat"), nullptr, PR_GetOSError());
return NS_ERROR_FAILURE;
}
uint64_t bytes = std::min((uint64_t)stat.size, mBytes);
if (bytes > UINT32_MAX) {
Fail(NS_LITERAL_CSTRING("Arithmetics"), nullptr, OS_ERROR_INVAL);
return NS_ERROR_FAILURE;
}
if (!aBuffer.Allocate(bytes)) {
Fail(NS_LITERAL_CSTRING("allocate"), nullptr, OS_ERROR_NOMEM);
return NS_ERROR_FAILURE;
}
uint64_t total_read = 0;
int32_t just_read = 0;
char* dest_chars = reinterpret_cast<char*>(aBuffer.rwget().data);
do {
just_read = PR_Read(file, dest_chars + total_read,
std::min(uint64_t(PR_INT32_MAX), bytes - total_read));
if (just_read == -1) {
Fail(NS_LITERAL_CSTRING("read"), nullptr, PR_GetOSError());
return NS_ERROR_FAILURE;
}
total_read += just_read;
} while (just_read != 0 && total_read < bytes);
if (total_read != bytes) {
// We seem to have a race condition here.
Fail(NS_LITERAL_CSTRING("read"), nullptr, OS_ERROR_RACE);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
protected:
/**
* Any steps that need to be taken before reading.
*
* In case of error, this method should call Fail() and return
* a failure code.
*/
virtual
nsresult BeforeRead() {
return NS_OK;
}
/**
* Proceed after reading.
*/
virtual
void AfterRead(TimeStamp aDispatchDate, ScopedArrayBufferContents& aBuffer) = 0;
protected:
const nsString mPath;
const uint64_t mBytes;
};
/**
* An implementation of a Read event that provides the data
* as a TypedArray.
*/
class DoReadToTypedArrayEvent final : public AbstractReadEvent {
public:
DoReadToTypedArrayEvent(const nsAString& aPath,
const uint32_t aBytes,
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError)
: AbstractReadEvent(aPath, aBytes,
aOnSuccess, aOnError)
, mResult(new TypedArrayResult(TimeStamp::Now()))
{ }
~DoReadToTypedArrayEvent() {
// If AbstractReadEvent::Run() has bailed out, we may need to cleanup
// mResult, which is main-thread only data
if (!mResult) {
return;
}
NS_ReleaseOnMainThread(mResult.forget());
}
protected:
void AfterRead(TimeStamp aDispatchDate,
ScopedArrayBufferContents& aBuffer) override {
MOZ_ASSERT(!NS_IsMainThread());
mResult->Init(aDispatchDate, TimeStamp::Now() - aDispatchDate, aBuffer.forget());
Succeed(mResult.forget());
}
private:
RefPtr<TypedArrayResult> mResult;
};
/**
* An implementation of a Read event that provides the data
* as a JavaScript string.
*/
class DoReadToStringEvent final : public AbstractReadEvent {
public:
DoReadToStringEvent(const nsAString& aPath,
const nsACString& aEncoding,
const uint32_t aBytes,
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback>& aOnSuccess,
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback>& aOnError)
: AbstractReadEvent(aPath, aBytes, aOnSuccess, aOnError)
, mEncoding(aEncoding)
, mResult(new StringResult(TimeStamp::Now()))
{ }
~DoReadToStringEvent() {
// If AbstraactReadEvent::Run() has bailed out, we may need to cleanup
// mResult, which is main-thread only data
if (!mResult) {
return;
}
NS_ReleaseOnMainThread(mResult.forget());
}
protected:
nsresult BeforeRead() override {
// Obtain the decoder. We do this before reading to avoid doing
// any unnecessary I/O in case the name of the encoding is incorrect.
MOZ_ASSERT(!NS_IsMainThread());
nsAutoCString encodingName;
if (!dom::EncodingUtils::FindEncodingForLabel(mEncoding, encodingName)) {
Fail(NS_LITERAL_CSTRING("Decode"), mResult.forget(), OS_ERROR_INVAL);
return NS_ERROR_FAILURE;
}
mDecoder = dom::EncodingUtils::DecoderForEncoding(encodingName);
if (!mDecoder) {
Fail(NS_LITERAL_CSTRING("DecoderForEncoding"), mResult.forget(), OS_ERROR_INVAL);
return NS_ERROR_FAILURE;
}
return NS_OK;
}
void AfterRead(TimeStamp aDispatchDate,
ScopedArrayBufferContents& aBuffer) override {
MOZ_ASSERT(!NS_IsMainThread());
int32_t maxChars;
const char* sourceChars = reinterpret_cast<const char*>(aBuffer.get().data);
int32_t sourceBytes = aBuffer.get().nbytes;
if (sourceBytes < 0) {
Fail(NS_LITERAL_CSTRING("arithmetics"), mResult.forget(), OS_ERROR_TOO_LARGE);
return;
}
nsresult rv = mDecoder->GetMaxLength(sourceChars, sourceBytes, &maxChars);
if (NS_FAILED(rv)) {
Fail(NS_LITERAL_CSTRING("GetMaxLength"), mResult.forget(), OS_ERROR_INVAL);
return;
}
if (maxChars < 0) {
Fail(NS_LITERAL_CSTRING("arithmetics"), mResult.forget(), OS_ERROR_TOO_LARGE);
return;
}
nsString resultString;
resultString.SetLength(maxChars);
if (resultString.Length() != (nsString::size_type)maxChars) {
Fail(NS_LITERAL_CSTRING("allocation"), mResult.forget(), OS_ERROR_TOO_LARGE);
return;
}
rv = mDecoder->Convert(sourceChars, &sourceBytes,
resultString.BeginWriting(), &maxChars);
MOZ_ASSERT(NS_SUCCEEDED(rv));
resultString.SetLength(maxChars);
mResult->Init(aDispatchDate, TimeStamp::Now() - aDispatchDate, resultString);
Succeed(mResult.forget());
}
private:
nsCString mEncoding;
nsCOMPtr<nsIUnicodeDecoder> mDecoder;
RefPtr<StringResult> mResult;
};
} // namespace
// The OS.File service
NS_IMPL_ISUPPORTS(NativeOSFileInternalsService, nsINativeOSFileInternalsService);
NS_IMETHODIMP
NativeOSFileInternalsService::Read(const nsAString& aPath,
JS::HandleValue aOptions,
nsINativeOSFileSuccessCallback *aOnSuccess,
nsINativeOSFileErrorCallback *aOnError,
JSContext* cx)
{
// Extract options
nsCString encoding;
uint64_t bytes = UINT64_MAX;
if (aOptions.isObject()) {
dom::NativeOSFileReadOptions dict;
if (!dict.Init(cx, aOptions)) {
return NS_ERROR_INVALID_ARG;
}
if (dict.mEncoding.WasPassed()) {
CopyUTF16toUTF8(dict.mEncoding.Value(), encoding);
}
if (dict.mBytes.WasPassed() && !dict.mBytes.Value().IsNull()) {
bytes = dict.mBytes.Value().Value();
}
}
// Prepare the off main thread event and dispatch it
nsCOMPtr<nsINativeOSFileSuccessCallback> onSuccess(aOnSuccess);
nsMainThreadPtrHandle<nsINativeOSFileSuccessCallback> onSuccessHandle(
new nsMainThreadPtrHolder<nsINativeOSFileSuccessCallback>(onSuccess));
nsCOMPtr<nsINativeOSFileErrorCallback> onError(aOnError);
nsMainThreadPtrHandle<nsINativeOSFileErrorCallback> onErrorHandle(
new nsMainThreadPtrHolder<nsINativeOSFileErrorCallback>(onError));
RefPtr<AbstractDoEvent> event;
if (encoding.IsEmpty()) {
event = new DoReadToTypedArrayEvent(aPath, bytes,
onSuccessHandle,
onErrorHandle);
} else {
event = new DoReadToStringEvent(aPath, encoding, bytes,
onSuccessHandle,
onErrorHandle);
}
nsresult rv;
nsCOMPtr<nsIEventTarget> target = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) {
return rv;
}
return target->Dispatch(event, NS_DISPATCH_NORMAL);
}
} // namespace mozilla