Merge mozilla-central to inbound. a=merge CLOSED TREE

This commit is contained in:
Narcis Beleuzu 2019-02-21 18:11:40 +02:00
commit 1cc1d33847
150 changed files with 3558 additions and 1133 deletions

View file

@ -22,7 +22,6 @@ extensions/spellcheck/**
extensions/universalchardet/** extensions/universalchardet/**
image/** image/**
layout/** layout/**
modules/**
netwerk/cookie/test/browser/** netwerk/cookie/test/browser/**
netwerk/test/browser/** netwerk/test/browser/**
netwerk/test/mochitests/** netwerk/test/mochitests/**

View file

@ -958,7 +958,7 @@ ROLE(NON_NATIVE_DOCUMENT,
"non-native document", "non-native document",
ATK_ROLE_DOCUMENT_FRAME, ATK_ROLE_DOCUMENT_FRAME,
NSAccessibilityGroupRole, NSAccessibilityGroupRole,
USE_ROLE_STRING, ROLE_SYSTEM_DOCUMENT,
ROLE_SYSTEM_DOCUMENT, ROLE_SYSTEM_DOCUMENT,
java::SessionAccessibility::CLASSNAME_VIEW, java::SessionAccessibility::CLASSNAME_VIEW,
eNoNameRule) eNoNameRule)

View file

@ -77,7 +77,8 @@ DocAccessibleWrap::get_accValue(VARIANT aVarChild, BSTR __RPC_FAR* aValue) {
// If document is being used to create a widget, don't use the URL hack // If document is being used to create a widget, don't use the URL hack
roles::Role role = Role(); roles::Role role = Role();
if (role != roles::DOCUMENT && role != roles::APPLICATION && if (role != roles::DOCUMENT && role != roles::APPLICATION &&
role != roles::DIALOG && role != roles::ALERT) role != roles::DIALOG && role != roles::ALERT &&
role != roles::NON_NATIVE_DOCUMENT)
return hr; return hr;
nsAutoString url; nsAutoString url;

View file

@ -674,6 +674,10 @@ async function sanitizeOnShutdown(progress) {
await Sanitizer.sanitize(itemsToClear, { progress }); await Sanitizer.sanitize(itemsToClear, { progress });
} }
// Here is the list of principals with site data.
progress.advancement = "get-principals";
let principals = await getAllPrincipals(progress);
// Clear out QuotaManager storage for principals that have been marked as // Clear out QuotaManager storage for principals that have been marked as
// session only. The cookie service has special logic that avoids writing // session only. The cookie service has special logic that avoids writing
// such cookies to disk, but QuotaManager always touches disk, so we need to // such cookies to disk, but QuotaManager always touches disk, so we need to
@ -700,8 +704,8 @@ async function sanitizeOnShutdown(progress) {
Ci.nsICookieService.ACCEPT_NORMALLY) == Ci.nsICookieService.ACCEPT_SESSION) { Ci.nsICookieService.ACCEPT_NORMALLY) == Ci.nsICookieService.ACCEPT_SESSION) {
log("Session-only configuration detected"); log("Session-only configuration detected");
progress.advancement = "session-only"; progress.advancement = "session-only";
let principals = await getAllPrincipals(progress);
await maybeSanitizeSessionPrincipals(progress, principals); await maybeSanitizeSessionPrincipals(progress, principals);
return;
} }
progress.advancement = "session-permission"; progress.advancement = "session-permission";
@ -721,8 +725,8 @@ async function sanitizeOnShutdown(progress) {
log("Custom session cookie permission detected for: " + permission.principal.URI.spec); log("Custom session cookie permission detected for: " + permission.principal.URI.spec);
// We use just the URI here, because permissions ignore OriginAttributes. // We use just the URI here, because permissions ignore OriginAttributes.
let principals = await getAllPrincipals(progress, permission.principal.URI); let selectedPrincipals = extractMatchingPrincipals(principals, permission.principal.URI);
await maybeSanitizeSessionPrincipals(progress, principals); await maybeSanitizeSessionPrincipals(progress, selectedPrincipals);
} }
if (Sanitizer.shouldSanitizeNewTabContainer) { if (Sanitizer.shouldSanitizeNewTabContainer) {
@ -741,10 +745,8 @@ async function sanitizeOnShutdown(progress) {
progress.advancement = "done"; progress.advancement = "done";
} }
// Retrieve the list of nsIPrincipals with site data. If matchUri is not null, // Retrieve the list of nsIPrincipals with site data.
// it returns only the principals matching that URI, ignoring the async function getAllPrincipals(progress) {
// OriginAttributes.
async function getAllPrincipals(progress, matchUri = null) {
progress.step = "principals-quota-manager"; progress.step = "principals-quota-manager";
let principals = await new Promise(resolve => { let principals = await new Promise(resolve => {
quotaManagerService.getUsage(request => { quotaManagerService.getUsage(request => {
@ -759,11 +761,7 @@ async function getAllPrincipals(progress, matchUri = null) {
for (let item of request.result) { for (let item of request.result) {
let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(item.origin); let principal = Services.scriptSecurityManager.createCodebasePrincipalFromOrigin(item.origin);
let uri = principal.URI; let uri = principal.URI;
if (!isSupportedURI(uri)) { if (isSupportedURI(uri)) {
continue;
}
if (!matchUri || Services.eTLD.hasRootDomain(matchUri.host, uri.host)) {
list.push(principal); list.push(principal);
} }
} }
@ -775,11 +773,8 @@ async function getAllPrincipals(progress, matchUri = null) {
let serviceWorkers = serviceWorkerManager.getAllRegistrations(); let serviceWorkers = serviceWorkerManager.getAllRegistrations();
for (let i = 0; i < serviceWorkers.length; i++) { for (let i = 0; i < serviceWorkers.length; i++) {
let sw = serviceWorkers.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo); let sw = serviceWorkers.queryElementAt(i, Ci.nsIServiceWorkerRegistrationInfo);
let uri = sw.principal.URI;
// We don't need to check the scheme. SW are just exposed to http/https URLs. // We don't need to check the scheme. SW are just exposed to http/https URLs.
if (!matchUri || Services.eTLD.hasRootDomain(matchUri.host, uri.host)) { principals.push(sw.principal);
principals.push(sw.principal);
}
} }
// Let's take the list of unique hosts+OA from cookies. // Let's take the list of unique hosts+OA from cookies.
@ -787,9 +782,7 @@ async function getAllPrincipals(progress, matchUri = null) {
let enumerator = Services.cookies.enumerator; let enumerator = Services.cookies.enumerator;
let hosts = new Set(); let hosts = new Set();
for (let cookie of enumerator) { for (let cookie of enumerator) {
if (!matchUri || Services.eTLD.hasRootDomain(matchUri.host, cookie.rawHost)) { hosts.add(cookie.rawHost + ChromeUtils.originAttributesToSuffix(cookie.originAttributes));
hosts.add(cookie.rawHost + ChromeUtils.originAttributesToSuffix(cookie.originAttributes));
}
} }
progress.step = "principals-host-cookie"; progress.step = "principals-host-cookie";
@ -804,6 +797,13 @@ async function getAllPrincipals(progress, matchUri = null) {
return principals; return principals;
} }
// Extracts the principals matching matchUri as root domain.
function extractMatchingPrincipals(principals, matchUri) {
return principals.filter(principal => {
return Services.eTLD.hasRootDomain(matchUri.host, principal.URI.host);
});
}
// This method receives a list of principals and it checks if some of them or // This method receives a list of principals and it checks if some of them or
// some of their sub-domain need to be sanitize. // some of their sub-domain need to be sanitize.
async function maybeSanitizeSessionPrincipals(progress, principals) { async function maybeSanitizeSessionPrincipals(progress, principals) {

View file

@ -3190,13 +3190,11 @@ nsresult Selection::NotifySelectionListeners() {
if (newEditingHost && newEditingHost != focusedElement) { if (newEditingHost && newEditingHost != focusedElement) {
MOZ_ASSERT(!newEditingHost->IsInNativeAnonymousSubtree()); MOZ_ASSERT(!newEditingHost->IsInNativeAnonymousSubtree());
// Note that don't steal focus from focused window if the window doesn't // Note that don't steal focus from focused window if the window doesn't
// have focus and if the window isn't focused window, shouldn't be // have focus. Additionally, although when an element gets focus, we
// scrolled to the new focused element. // usually scroll to the element, but in this case, we shouldn't do it
uint32_t flags = nsIFocusManager::FLAG_NOSWITCHFRAME; // because Chrome does not do so.
if (focusedWindow != fm->GetFocusedWindow()) { fm->SetFocus(newEditingHost, nsIFocusManager::FLAG_NOSWITCHFRAME |
flags |= nsIFocusManager::FLAG_NOSCROLL; nsIFocusManager::FLAG_NOSCROLL);
}
fm->SetFocus(newEditingHost, flags);
} }
} }
} }

View file

@ -5733,6 +5733,13 @@ bool CanvasRenderingContext2D::ShouldForceInactiveLayer(
return !aManager->CanUseCanvasLayerForSize(GetSize()); return !aManager->CanUseCanvasLayerForSize(GetSize());
} }
void CanvasRenderingContext2D::SetWriteOnly() {
mWriteOnly = true;
if (mCanvasElement) {
mCanvasElement->SetWriteOnly();
}
}
NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(CanvasPath, AddRef) NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(CanvasPath, AddRef)
NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(CanvasPath, Release) NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(CanvasPath, Release)

View file

@ -1114,7 +1114,7 @@ class CanvasRenderingContext2D final : public nsICanvasRenderingContextInternal,
friend class CanvasDrawObserver; friend class CanvasDrawObserver;
friend class ImageBitmap; friend class ImageBitmap;
void SetWriteOnly() { mWriteOnly = true; } void SetWriteOnly();
bool IsWriteOnly() const { return mWriteOnly; } bool IsWriteOnly() const { return mWriteOnly; }

View file

@ -1283,7 +1283,7 @@ tags = suspend
skip-if = toolkit == 'android' # bug 1346705 skip-if = toolkit == 'android' # bug 1346705
tags = suspend tags = suspend
[test_background_video_resume_after_end_show_last_frame.html] [test_background_video_resume_after_end_show_last_frame.html]
skip-if = toolkit == 'android' # bug 1346705 skip-if = toolkit == 'android' || ( webrender && os == "linux") # bug 1346705, bug 1516043
tags = suspend tags = suspend
[test_background_video_suspend.html] [test_background_video_suspend.html]
skip-if = toolkit == 'android' # android(bug 1304480) skip-if = toolkit == 'android' # android(bug 1304480)

View file

@ -1198,6 +1198,13 @@ void AudioContext::Unmute() const {
} }
} }
void AudioContext::SetParamMapForWorkletName(
const nsAString& aName, AudioParamDescriptorMap* aParamMap) {
MOZ_ASSERT(!mWorkletParamDescriptors.GetValue(aName));
Unused << mWorkletParamDescriptors.Put(aName, std::move(*aParamMap),
fallible);
}
size_t AudioContext::SizeOfIncludingThis( size_t AudioContext::SizeOfIncludingThis(
mozilla::MallocSizeOf aMallocSizeOf) const { mozilla::MallocSizeOf aMallocSizeOf) const {
// AudioNodes are tracked separately because we do not want the AudioContext // AudioNodes are tracked separately because we do not want the AudioContext

View file

@ -7,6 +7,7 @@
#ifndef AudioContext_h_ #ifndef AudioContext_h_
#define AudioContext_h_ #define AudioContext_h_
#include "AudioParamDescriptorMap.h"
#include "mozilla/dom/OfflineAudioContextBinding.h" #include "mozilla/dom/OfflineAudioContextBinding.h"
#include "MediaBufferDecoder.h" #include "MediaBufferDecoder.h"
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
@ -311,6 +312,14 @@ class AudioContext final : public DOMEventTargetHelper,
bool CheckClosed(ErrorResult& aRv); bool CheckClosed(ErrorResult& aRv);
// Steals from |aParamMap|
void SetParamMapForWorkletName(const nsAString& aName,
AudioParamDescriptorMap* aParamMap);
const AudioParamDescriptorMap* GetParamMapForWorkletName(
const nsAString& aName) {
return mWorkletParamDescriptors.GetValue(aName);
}
void Dispatch(already_AddRefed<nsIRunnable>&& aRunnable); void Dispatch(already_AddRefed<nsIRunnable>&& aRunnable);
private: private:
@ -371,6 +380,8 @@ class AudioContext final : public DOMEventTargetHelper,
nsTHashtable<nsRefPtrHashKey<AudioNode>> mActiveNodes; nsTHashtable<nsRefPtrHashKey<AudioNode>> mActiveNodes;
// Raw (non-owning) references to all AudioNodes for this AudioContext. // Raw (non-owning) references to all AudioNodes for this AudioContext.
nsTHashtable<nsPtrHashKey<AudioNode>> mAllNodes; nsTHashtable<nsPtrHashKey<AudioNode>> mAllNodes;
nsDataHashtable<nsStringHashKey, AudioParamDescriptorMap>
mWorkletParamDescriptors;
// Cache to avoid recomputing basic waveforms all the time. // Cache to avoid recomputing basic waveforms all the time.
RefPtr<BasicWaveFormCache> mBasicWaveFormCache; RefPtr<BasicWaveFormCache> mBasicWaveFormCache;
// Number of channels passed in the OfflineAudioContext ctor. // Number of channels passed in the OfflineAudioContext ctor.

View file

@ -6,6 +6,8 @@
#include "AudioWorkletGlobalScope.h" #include "AudioWorkletGlobalScope.h"
#include "AudioNodeEngine.h"
#include "AudioNodeStream.h"
#include "AudioWorkletImpl.h" #include "AudioWorkletImpl.h"
#include "jsapi.h" #include "jsapi.h"
#include "mozilla/dom/AudioWorkletGlobalScopeBinding.h" #include "mozilla/dom/AudioWorkletGlobalScopeBinding.h"
@ -186,10 +188,17 @@ void AudioWorkletGlobalScope::RegisterProcessor(JSContext* aCx,
if (aRv.Failed()) { if (aRv.Failed()) {
return; return;
} }
// TODO: we don't have a proper mechanism to communicate with the
// control thread currently. See NS_DispatchToMainThread(NS_NewRunnableFunction(
// https://bugzilla.mozilla.org/show_bug.cgi?id=1473467#c3 "AudioWorkletGlobalScope: parameter descriptors",
// and https://bugzilla.mozilla.org/show_bug.cgi?id=1492014 [impl = mImpl, name = nsString(aName), map = std::move(map)]() mutable {
AudioNode* destinationNode =
impl->DestinationStream()->Engine()->NodeMainThread();
if (!destinationNode) {
return;
}
destinationNode->Context()->SetParamMapForWorkletName(name, &map);
}));
} }
WorkletImpl* AudioWorkletGlobalScope::Impl() const { return mImpl; } WorkletImpl* AudioWorkletGlobalScope::Impl() const { return mImpl; }

View file

@ -29,6 +29,9 @@ class AudioWorkletImpl final : public WorkletImpl {
nsresult SendControlMessage(already_AddRefed<nsIRunnable> aRunnable) override; nsresult SendControlMessage(already_AddRefed<nsIRunnable> aRunnable) override;
// Any thread:
AudioNodeStream* DestinationStream() { return mDestinationStream; }
protected: protected:
// Execution thread only. // Execution thread only.
already_AddRefed<dom::WorkletGlobalScope> ConstructGlobalScope() override; already_AddRefed<dom::WorkletGlobalScope> ConstructGlobalScope() override;

View file

@ -48,6 +48,17 @@ AudioWorkletNode::AudioWorkletNode(AudioContext* aAudioContext,
} }
} }
} }
/**
* 2. If nodeName does not exists as a key in the BaseAudioContexts node
* name to parameter descriptor map, throw a NotSupportedError exception
* and abort these steps.
*/
const AudioParamDescriptorMap* parameterDescriptors =
aAudioContext.GetParamMapForWorkletName(aName);
if (!parameterDescriptors) {
aRv.Throw(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
return nullptr;
}
RefPtr<AudioWorkletNode> audioWorkletNode = RefPtr<AudioWorkletNode> audioWorkletNode =
new AudioWorkletNode(&aAudioContext, aName); new AudioWorkletNode(&aAudioContext, aName);

View file

@ -267,7 +267,7 @@ public:
cairo_font_face_t* GetCairoFontFace() const { return fFontFace; } cairo_font_face_t* GetCairoFontFace() const { return fFontFace; }
private: private:
~SkCairoFTTypeface() ~SkCairoFTTypeface()
{ {
cairo_font_face_destroy(fFontFace); cairo_font_face_destroy(fFontFace);
@ -283,7 +283,8 @@ private:
}; };
static bool FindByCairoFontFace(SkTypeface* typeface, void* context) { static bool FindByCairoFontFace(SkTypeface* typeface, void* context) {
return static_cast<SkCairoFTTypeface*>(typeface)->GetCairoFontFace() == static_cast<cairo_font_face_t*>(context); return static_cast<SkCairoFTTypeface*>(typeface)->GetCairoFontFace() ==
static_cast<cairo_font_face_t*>(context);
} }
SkTypeface* SkCreateTypefaceFromCairoFTFontWithFontconfig(cairo_scaled_font_t* scaledFont, FcPattern* pattern) SkTypeface* SkCreateTypefaceFromCairoFTFontWithFontconfig(cairo_scaled_font_t* scaledFont, FcPattern* pattern)
@ -292,10 +293,11 @@ SkTypeface* SkCreateTypefaceFromCairoFTFontWithFontconfig(cairo_scaled_font_t* s
SkASSERT(cairo_font_face_status(fontFace) == CAIRO_STATUS_SUCCESS); SkASSERT(cairo_font_face_status(fontFace) == CAIRO_STATUS_SUCCESS);
SkASSERT(cairo_font_face_get_type(fontFace) == CAIRO_FONT_TYPE_FT); SkASSERT(cairo_font_face_get_type(fontFace) == CAIRO_FONT_TYPE_FT);
SkTypeface* typeface = SkTypefaceCache::FindByProcAndRef(FindByCairoFontFace, fontFace); SkTypeface* typeface =
SkTypefaceCache::FindByProcAndRef(FindByCairoFontFace, fontFace);
if (!typeface) { if (!typeface) {
typeface = new SkCairoFTTypeface(fontFace, pattern); typeface = new SkCairoFTTypeface(fontFace, pattern);
SkTypefaceCache::Add(typeface); SkTypefaceCache::Add(typeface);
} }
return typeface; return typeface;

1930
intl/l10n/FluentSyntax.jsm Normal file

File diff suppressed because it is too large Load diff

View file

@ -11,6 +11,10 @@ EXTRA_JS_MODULES += [
'Localization.jsm', 'Localization.jsm',
] ]
TESTING_JS_MODULES += [
'FluentSyntax.jsm',
]
XPIDL_SOURCES += [ XPIDL_SOURCES += [
'mozIDOMLocalization.idl', 'mozIDOMLocalization.idl',
] ]

View file

@ -256,8 +256,8 @@ class CxxCodeGen(CodePrinter, Visitor):
self.write(' = 0') self.write(' = 0')
def visitMethodDefn(self, md): def visitMethodDefn(self, md):
if md.decl.methodspec == MethodSpec.PURE: # Method specifiers are for decls, not defns.
return assert md.decl.methodspec == MethodSpec.NONE
self.printdent() self.printdent()
md.decl.accept(self) md.decl.accept(self)

View file

@ -4827,16 +4827,22 @@ methodDefns."""
for i, stmt in enumerate(cls.stmts): for i, stmt in enumerate(cls.stmts):
if isinstance(stmt, MethodDefn) and not stmt.decl.force_inline: if isinstance(stmt, MethodDefn) and not stmt.decl.force_inline:
decl, defn = _splitMethodDefn(stmt, cls) decl, defn = _splitMethodDeclDefn(stmt, cls)
cls.stmts[i] = StmtDecl(decl) cls.stmts[i] = StmtDecl(decl)
defns.addstmts([defn, Whitespace.NL]) if defn:
defns.addstmts([defn, Whitespace.NL])
return cls, defns return cls, defns
def _splitMethodDefn(md, cls): def _splitMethodDeclDefn(md, cls):
# Pure methods have decls but no defns.
if md.decl.methodspec == MethodSpec.PURE:
return md.decl, None
saveddecl = deepcopy(md.decl) saveddecl = deepcopy(md.decl)
md.decl.cls = cls md.decl.cls = cls
# Don't emit method specifiers on method defns.
md.decl.methodspec = MethodSpec.NONE md.decl.methodspec = MethodSpec.NONE
md.decl.warn_unused = False md.decl.warn_unused = False
md.decl.only_for_definition = True md.decl.only_for_definition = True

View file

@ -7443,10 +7443,10 @@ gcstats::ZoneGCStats GCRuntime::scanZonesBeforeGC() {
zoneStats.compartmentCount += zone->compartments().length(); zoneStats.compartmentCount += zone->compartments().length();
if (zone->canCollect()) { if (zone->canCollect()) {
zoneStats.collectableZoneCount++; zoneStats.collectableZoneCount++;
} if (zone->isGCScheduled()) {
if (zone->isGCScheduled()) { zoneStats.collectedZoneCount++;
zoneStats.collectedZoneCount++; zoneStats.collectedCompartmentCount += zone->compartments().length();
zoneStats.collectedCompartmentCount += zone->compartments().length(); }
} }
} }

View file

@ -318,7 +318,7 @@ fuzzy-if(Android,0-3,0-50) fuzzy-if(skiaContent,0-1,0-133) == 273681-1.html 2736
== 283686-2.html 283686-2-ref.html == 283686-2.html 283686-2-ref.html
== 283686-3.html about:blank == 283686-3.html about:blank
== 289384-1.xhtml 289384-ref.xhtml == 289384-1.xhtml 289384-ref.xhtml
random-if(d2d) fuzzy-if(Android,0-8,0-1439) fuzzy-if(webrender,0-6,0-1124) HTTP == 289480.html#top 289480-ref.html # basically-verbatim acid2 test, HTTP for a 404 page -- bug 578114 for the d2d failures random-if(d2d) fuzzy-if(Android,0-8,0-1439) fuzzy-if(webrender,0-6,0-1124) skip-if(webrender&&gtkWidget) HTTP == 289480.html#top 289480-ref.html # basically-verbatim acid2 test, HTTP for a 404 page -- bug 578114 for the d2d failures
== 290129-1.html 290129-1-ref.html == 290129-1.html 290129-1-ref.html
== 291078-1.html 291078-1-ref.html == 291078-1.html 291078-1-ref.html
== 291078-2.html 291078-2-ref.html == 291078-2.html 291078-2-ref.html

View file

@ -1277,6 +1277,7 @@ void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType); rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
if (header.payload_type_frequency >= 0) { if (header.payload_type_frequency >= 0) {
bool in_order = IsPacketInOrder(header); bool in_order = IsPacketInOrder(header);
statistics_proxy_->OnSendCodecFrequencyChanged(header.payload_type_frequency);
rtp_receive_statistics_->IncomingPacket( rtp_receive_statistics_->IncomingPacket(
header, packet.size(), IsPacketRetransmitted(header, in_order)); header, packet.size(), IsPacketRetransmitted(header, in_order));
rtp_payload_registry_->SetIncomingPayloadType(header); rtp_payload_registry_->SetIncomingPayloadType(header);

View file

@ -133,7 +133,7 @@ class InfallibleAllocPolicy {
return p; return p;
} }
static void* calloc_(size_t aSize) { static void* calloc_(size_t aCount, size_t aSize) {
void* p = gMallocTable.calloc(1, aSize); void* p = gMallocTable.calloc(1, aSize);
ExitOnFailure(p); ExitOnFailure(p);
return p; return p;
@ -1127,9 +1127,12 @@ static void* replace_calloc(size_t aCount, size_t aSize) {
Thread* t = Thread::Fetch(); Thread* t = Thread::Fetch();
if (t->InterceptsAreBlocked()) { if (t->InterceptsAreBlocked()) {
return InfallibleAllocPolicy::calloc_(aCount * aSize); return InfallibleAllocPolicy::calloc_(aCount, aSize);
} }
// |aCount * aSize| could overflow, but if that happens then
// |gMallocTable.calloc()| will return nullptr and |AllocCallback()| will
// return immediately without using the overflowed value.
void* ptr = gMallocTable.calloc(aCount, aSize); void* ptr = gMallocTable.calloc(aCount, aSize);
AllocCallback(ptr, aCount * aSize, t); AllocCallback(ptr, aCount * aSize, t);
return ptr; return ptr;

View file

@ -195,7 +195,10 @@ public class LauncherActivity extends Activity {
return; return;
} }
final String deepLink = intent.getData().getHost(); final String deepLink = intent.getData().getHost();
final String uid = intent.getData().getQueryParameter("uid").replaceAll("\\n", ""); String uid = intent.getData().getQueryParameter("uid");
if (uid != null) {
uid = uid.replaceAll("\\n", "");
}
final String localUid = MmaDelegate.getDeviceId(LauncherActivity.this); final String localUid = MmaDelegate.getDeviceId(LauncherActivity.this);
final boolean isMmaDeepLink = uid != null && localUid != null && uid.equals(localUid); final boolean isMmaDeepLink = uid != null && localUid != null && uid.equals(localUid);

View file

@ -21,18 +21,18 @@ https://bugzilla.mozilla.org/show_bug.cgi?id=1173171
// __xhr(method, url, responseType__. // __xhr(method, url, responseType__.
// A simple async XMLHttpRequest call. // A simple async XMLHttpRequest call.
// Returns a promise with the response. // Returns a promise with the response.
let xhr = function (method, url, responseType) { let xhr = function(method, url, responseType) {
return new Promise(function (resolve, reject) { return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest(); let xhrInstance = new XMLHttpRequest();
xhr.open(method, url, true); xhrInstance.open(method, url, true);
xhr.onload = function () { xhrInstance.onload = function() {
resolve(xhr.response); resolve(xhrInstance.response);
}; };
xhr.onerror = function() { xhrInstance.onerror = function() {
resolve(null); resolve(null);
}; };
xhr.responseType = responseType; xhrInstance.responseType = responseType;
xhr.send(); xhrInstance.send();
}); });
}; };
@ -40,7 +40,6 @@ let jarURL = "jar:http://mochi.test:8888/tests/modules/libjar/test/mochitest/bug
// Test behavior when blocking is deactivated and activated. // Test behavior when blocking is deactivated and activated.
add_task(async function() { add_task(async function() {
let shouldBlock = true;
let response = await xhr("GET", jarURL, "document"); let response = await xhr("GET", jarURL, "document");
is(response, null, "Remote jars should be blocked."); is(response, null, "Remote jars should be blocked.");
}); });

View file

@ -4,15 +4,14 @@
"use strict"; "use strict";
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Check that reading non existant inner jars results in the right error // Check that reading non existant inner jars results in the right error
add_task(async function() { add_task(async function() {
var file = do_get_file("data/test_bug597702.zip"); var file = do_get_file("data/test_bug597702.zip");
var ios = Cc["@mozilla.org/network/io-service;1"]. var outerJarBase = "jar:" + Services.io.newFileURI(file).spec + "!/";
getService(Ci.nsIIOService);
var outerJarBase = "jar:" + ios.newFileURI(file).spec + "!/";
var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello#!/ignore%20this%20part"; var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello#!/ignore%20this%20part";
var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true}); var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true});
var instr = goodChannel.open(); var instr = goodChannel.open();
@ -22,9 +21,7 @@ add_task(async function() {
add_task(async function() { add_task(async function() {
var file = do_get_file("data/test_bug597702.zip"); var file = do_get_file("data/test_bug597702.zip");
var ios = Cc["@mozilla.org/network/io-service;1"]. var outerJarBase = "jar:" + Services.io.newFileURI(file).spec + "!/";
getService(Ci.nsIIOService);
var outerJarBase = "jar:" + ios.newFileURI(file).spec + "!/";
var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello?ignore%20this%20part!/"; var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello?ignore%20this%20part!/";
var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true}); var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true});
var instr = goodChannel.open(); var instr = goodChannel.open();
@ -34,9 +31,7 @@ add_task(async function() {
add_task(async function() { add_task(async function() {
var file = do_get_file("data/test_bug597702.zip"); var file = do_get_file("data/test_bug597702.zip");
var ios = Cc["@mozilla.org/network/io-service;1"]. var outerJarBase = "jar:" + Services.io.newFileURI(file).spec + "!/";
getService(Ci.nsIIOService);
var outerJarBase = "jar:" + ios.newFileURI(file).spec + "!/";
var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello?ignore#this!/part"; var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello?ignore#this!/part";
var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true}); var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true});
var instr = goodChannel.open(); var instr = goodChannel.open();

View file

@ -1,11 +1,11 @@
// Regression test for bug 278262 - JAR URIs should resolve relative URIs in the base section. // Regression test for bug 278262 - JAR URIs should resolve relative URIs in the base section.
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const path = "data/test_bug333423.zip"; const path = "data/test_bug333423.zip";
function test_relative_sub() { function test_relative_sub() {
var ios = Cc["@mozilla.org/network/io-service;1"]. var ios = Services.io;
getService(Ci.nsIIOService);
var spec = "jar:" + ios.newFileURI(do_get_file(path)).spec + "!/"; var spec = "jar:" + ios.newFileURI(do_get_file(path)).spec + "!/";
var base = ios.newURI(spec); var base = ios.newURI(spec);
var uri = ios.newURI("../modules/libjar", null, base); var uri = ios.newURI("../modules/libjar", null, base);
@ -13,14 +13,12 @@ function test_relative_sub() {
// This is the URI we expect to see. // This is the URI we expect to see.
var expected = "jar:" + ios.newFileURI(do_get_file(path)).spec + var expected = "jar:" + ios.newFileURI(do_get_file(path)).spec +
"!/modules/libjar"; "!/modules/libjar";
Assert.equal(uri.spec, expected); Assert.equal(uri.spec, expected);
} }
function test_relative_base() { function test_relative_base() {
var ios = Cc["@mozilla.org/network/io-service;1"]. var ios = Services.io;
getService(Ci.nsIIOService);
var base = ios.newFileURI(do_get_file("data/empty")); var base = ios.newFileURI(do_get_file("data/empty"));
var uri = ios.newURI("jar:../" + path + "!/", null, base); var uri = ios.newURI("jar:../" + path + "!/", null, base);

View file

@ -4,7 +4,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Regression test for bug 333423 - crash enumerating entries of a // Regression test for bug 333423 - crash enumerating entries of a
// closed nsIZipReader // closed nsIZipReader
function run_test() { function run_test() {
// the build script have created the zip we can test on in the current dir. // the build script have created the zip we can test on in the current dir.
@ -14,6 +14,6 @@ function run_test() {
createInstance(Ci.nsIZipReader); createInstance(Ci.nsIZipReader);
zipreader.open(file); zipreader.open(file);
zipreader.close(); zipreader.close();
var entries = zipreader.findEntries('*.*'); var entries = zipreader.findEntries("*.*");
Assert.ok(!entries.hasMore()); // this shouldn't crash Assert.ok(!entries.hasMore()); // this shouldn't crash
} }

View file

@ -1,13 +1,12 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Regression test for bug 370103 - crash when passing a null listener to // Regression test for bug 370103 - crash when passing a null listener to
// nsIChannel.asyncOpen // nsIChannel.asyncOpen
function run_test() { function run_test() {
// Compose the jar: url // Compose the jar: url
var ioService = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
var file = do_get_file("data/test_bug370103.jar"); var file = do_get_file("data/test_bug370103.jar");
var url = ioService.newFileURI(file).spec; var url = Services.io.newFileURI(file).spec;
url = "jar:" + url + "!/test_bug370103"; url = "jar:" + url + "!/test_bug370103";
// Try opening channel with null listener // Try opening channel with null listener
@ -16,8 +15,7 @@ function run_test() {
var exception = false; var exception = false;
try { try {
channel.asyncOpen(null); channel.asyncOpen(null);
} } catch (e) {
catch(e) {
exception = true; exception = true;
} }

View file

@ -14,7 +14,7 @@ function run_test() {
createInstance(Ci.nsIZipReader); createInstance(Ci.nsIZipReader);
zipReader.open(file); zipReader.open(file);
var entry = zipReader.getEntry(ENTRY_NAME); var entry = zipReader.getEntry(ENTRY_NAME);
var diff = Math.abs(entry.lastModifiedTime - ENTRY_TIME.getTime()*1000); var diff = Math.abs(entry.lastModifiedTime - ENTRY_TIME.getTime() * 1000);
zipReader.close(); zipReader.close();
if (diff >= MAX_TIME_DIFF) if (diff >= MAX_TIME_DIFF)
do_throw(diff); do_throw(diff);

View file

@ -1,18 +1,16 @@
// Make sure we behave appropriately when asking for content-disposition // Make sure we behave appropriately when asking for content-disposition
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const path = "data/test_bug589292.zip"; const path = "data/test_bug589292.zip";
function run_test() { function run_test() {
var ios = Cc["@mozilla.org/network/io-service;1"]. var spec = "jar:" + Services.io.newFileURI(do_get_file(path)).spec + "!/foo.txt";
getService(Ci.nsIIOService);
var spec = "jar:" + ios.newFileURI(do_get_file(path)).spec + "!/foo.txt";
var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true}); var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true});
instr = channel.open(); channel.open();
var val;
try { try {
val = channel.contentDisposition; channel.contentDisposition;
Assert.ok(false, "The channel has content disposition?!"); Assert.ok(false, "The channel has content disposition?!");
} catch (e) { } catch (e) {
// This is what we want to happen - there's no underlying channel, so no // This is what we want to happen - there's no underlying channel, so no

View file

@ -2,31 +2,29 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Check that reading non existant inner jars results in the right error // Check that reading non existant inner jars results in the right error
function run_test() { function run_test() {
var file = do_get_file("data/test_bug597702.zip"); var file = do_get_file("data/test_bug597702.zip");
var ios = Cc["@mozilla.org/network/io-service;1"]. var outerJarBase = "jar:" + Services.io.newFileURI(file).spec + "!/";
getService(Ci.nsIIOService);
var outerJarBase = "jar:" + ios.newFileURI(file).spec + "!/";
var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello"; var goodSpec = "jar:" + outerJarBase + "inner.jar!/hello";
var badSpec = "jar:" + outerJarBase + "jar_that_isnt_in_the.jar!/hello"; var badSpec = "jar:" + outerJarBase + "jar_that_isnt_in_the.jar!/hello";
var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true}); var goodChannel = NetUtil.newChannel({uri: goodSpec, loadUsingSystemPrincipal: true});
var badChannel = NetUtil.newChannel({uri: badSpec, loadUsingSystemPrincipal: true}); var badChannel = NetUtil.newChannel({uri: badSpec, loadUsingSystemPrincipal: true});
try { try {
instr = goodChannel.open(); goodChannel.open();
} catch (e) { } catch (e) {
do_throw("Failed to open file in inner jar"); do_throw("Failed to open file in inner jar");
} }
try { try {
instr = badChannel.open(); badChannel.open();
do_throw("Failed to report that file doesn't exist"); do_throw("Failed to report that file doesn't exist");
} catch (e) { } catch (e) {
Assert.ok(e.name == "NS_ERROR_FILE_NOT_FOUND"); Assert.ok(e.name == "NS_ERROR_FILE_NOT_FOUND");
} }
} }

View file

@ -2,25 +2,23 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Check that the zip cache can expire entries from nested jars // Check that the zip cache can expire entries from nested jars
var ios = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
function open_inner_zip(base, idx) { function open_inner_zip(base, idx) {
var spec = "jar:" + base + "inner" + idx + ".zip!/foo"; var spec = "jar:" + base + "inner" + idx + ".zip!/foo";
var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true}); var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true});
var stream = channel.open(); channel.open();
} }
function run_test() { function run_test() {
var file = do_get_file("data/test_bug637286.zip"); var file = do_get_file("data/test_bug637286.zip");
var outerJarBase = "jar:" + ios.newFileURI(file).spec + "!/"; var outerJarBase = "jar:" + Services.io.newFileURI(file).spec + "!/";
for (var i = 0; i < 40; i++) { for (var i = 0; i < 40; i++) {
open_inner_zip(outerJarBase, i); open_inner_zip(outerJarBase, i);
gc(); gc();
} }
} }

View file

@ -2,19 +2,18 @@
* http://creativecommons.org/publicdomain/zero/1.0/ * http://creativecommons.org/publicdomain/zero/1.0/
*/ */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
// Check that we don't crash on reading a directory entry signature // Check that we don't crash on reading a directory entry signature
var ios = Cc["@mozilla.org/network/io-service;1"].
getService(Ci.nsIIOService);
function run_test() { function run_test() {
var file = do_get_file("data/test_bug658093.zip"); var file = do_get_file("data/test_bug658093.zip");
var spec = "jar:" + ios.newFileURI(file).spec + "!/0000"; var spec = "jar:" + Services.io.newFileURI(file).spec + "!/0000";
var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true}); var channel = NetUtil.newChannel({uri: spec, loadUsingSystemPrincipal: true});
var failed = false; var failed = false;
try { try {
var stream = channel.open(); channel.open();
} catch (e) { } catch (e) {
failed = true; failed = true;
} }

View file

@ -8,15 +8,15 @@ function run_test() {
var file = do_get_file("data/test_corrupt3.zip"); var file = do_get_file("data/test_corrupt3.zip");
var zipreader = Cc["@mozilla.org/libjar/zip-reader;1"]. var zipreader = Cc["@mozilla.org/libjar/zip-reader;1"].
createInstance(Ci.nsIZipReader); createInstance(Ci.nsIZipReader);
zipreader.open(file); zipreader.open(file);
var failed = false; var failed = false;
for (let entryPath of zipreader.findEntries('*')) { for (let entryPath of zipreader.findEntries("*")) {
let entry = zipreader.getEntry(entryPath); let entry = zipreader.getEntry(entryPath);
if (!entry.isDirectory) { if (!entry.isDirectory) {
try { try {
let inputStream = zipreader.getInputStream(entryPath); zipreader.getInputStream(entryPath);
} catch (e) { } catch (e) {
failed = true; failed = true;
} }

View file

@ -2,8 +2,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function wrapInputStream(input) function wrapInputStream(input) {
{
var nsIScriptableInputStream = Ci.nsIScriptableInputStream; var nsIScriptableInputStream = Ci.nsIScriptableInputStream;
var factory = Cc["@mozilla.org/scriptableinputstream;1"]; var factory = Cc["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream); var wrapper = factory.createInstance(nsIScriptableInputStream);

View file

@ -4,8 +4,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function wrapInputStream(input) function wrapInputStream(input) {
{
let nsIScriptableInputStream = Ci.nsIScriptableInputStream; let nsIScriptableInputStream = Ci.nsIScriptableInputStream;
let factory = Cc["@mozilla.org/scriptableinputstream;1"]; let factory = Cc["@mozilla.org/scriptableinputstream;1"];
let wrapper = factory.createInstance(nsIScriptableInputStream); let wrapper = factory.createInstance(nsIScriptableInputStream);
@ -20,17 +19,17 @@ function run_test() {
let file = do_get_file("data/test_crx_dummy.crx"); let file = do_get_file("data/test_crx_dummy.crx");
let zipreader = Cc["@mozilla.org/libjar/zip-reader;1"]. let zipreader = Cc["@mozilla.org/libjar/zip-reader;1"].
createInstance(Ci.nsIZipReader); createInstance(Ci.nsIZipReader);
zipreader.open(file); zipreader.open(file);
// do crc stuff // do crc stuff
function check_archive_crc() { function check_archive_crc() {
zipreader.test(null); zipreader.test(null);
return true; return true;
} }
Assert.ok(check_archive_crc()) Assert.ok(check_archive_crc());
let entries = zipreader.findEntries(null); zipreader.findEntries(null);
let stream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/Makefile.in")) let stream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/Makefile.in"));
let dirstream= wrapInputStream(zipreader.getInputStream("modules/libjar/test/")) let dirstream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/"));
zipreader.close(); zipreader.close();
zipreader = null; zipreader = null;
Cu.forceGC(); Cu.forceGC();

View file

@ -7,21 +7,14 @@
*/ */
const {classes: Cc, const {Constructor: ctor} = Components;
interfaces: Ci,
results: Cr,
utils: Cu,
Constructor: ctor
} = Components;
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const ios = Cc["@mozilla.org/network/io-service;1"]. const ios = Services.io;
getService(Ci.nsIIOService); const dirSvc = Services.dirsvc;
const dirSvc = Cc["@mozilla.org/file/directory_service;1"]. const obs = Services.obs;
getService(Ci.nsIProperties);
const obs = Cc["@mozilla.org/observer-service;1"].
getService(Ci.nsIObserverService);
const nsIBinaryInputStream = ctor("@mozilla.org/binaryinputstream;1", const nsIBinaryInputStream = ctor("@mozilla.org/binaryinputstream;1",
"nsIBinaryInputStream", "nsIBinaryInputStream",
@ -40,33 +33,27 @@ Listener.prototype = {
gotStartRequest: false, gotStartRequest: false,
available: -1, available: -1,
gotStopRequest: false, gotStopRequest: false,
QueryInterface: function(iid) { QueryInterface: ChromeUtils.generateQI(["nsIRequestObserver"]),
if (iid.equals(Ci.nsISupports) || onDataAvailable(request, ctx, stream, offset, count) {
iid.equals(Ci.nsIRequestObserver))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
},
onDataAvailable: function(request, ctx, stream, offset, count) {
try { try {
this.available = stream.available(); this.available = stream.available();
Assert.equal(this.available, count); Assert.equal(this.available, count);
// Need to consume stream to avoid assertion // Need to consume stream to avoid assertion
new nsIBinaryInputStream(stream).readBytes(count); new nsIBinaryInputStream(stream).readBytes(count);
} } catch (ex) {
catch (ex) {
do_throw(ex); do_throw(ex);
} }
}, },
onStartRequest: function(request, ctx) { onStartRequest(request, ctx) {
this.gotStartRequest = true; this.gotStartRequest = true;
}, },
onStopRequest: function(request, ctx, status) { onStopRequest(request, ctx, status) {
this.gotStopRequest = true; this.gotStopRequest = true;
Assert.equal(status, 0); Assert.equal(status, 0);
if (this._callback) { if (this._callback) {
this._callback.call(null, this); this._callback.call(null, this);
} }
} },
}; };
/** /**
@ -74,7 +61,7 @@ Listener.prototype = {
*/ */
function testAsync() { function testAsync() {
var uri = jarBase + "/inner40.zip"; var uri = jarBase + "/inner40.zip";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
Assert.ok(chan.contentLength < 0); Assert.ok(chan.contentLength < 0);
chan.asyncOpen(new Listener(function(l) { chan.asyncOpen(new Listener(function(l) {
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
@ -94,13 +81,13 @@ add_test(testAsync);
* Basic test for nsIZipReader. * Basic test for nsIZipReader.
*/ */
function testZipEntry() { function testZipEntry() {
var uri = jarBase + "/inner40.zip"; var uri = jarBase + "/inner40.zip";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}) var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true})
.QueryInterface(Ci.nsIJARChannel); .QueryInterface(Ci.nsIJARChannel);
var entry = chan.zipEntry; var entry = chan.zipEntry;
Assert.ok(entry.CRC32 == 0x8b635486); Assert.ok(entry.CRC32 == 0x8b635486);
Assert.ok(entry.realSize == 184); Assert.ok(entry.realSize == 184);
run_next_test(); run_next_test();
} }
add_test(testZipEntry); add_test(testZipEntry);
@ -111,7 +98,7 @@ add_test(testZipEntry);
*/ */
add_test(function testSync() { add_test(function testSync() {
var uri = jarBase + "/inner40.zip"; var uri = jarBase + "/inner40.zip";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
var stream = chan.open(); var stream = chan.open();
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
Assert.equal(stream.available(), chan.contentLength); Assert.equal(stream.available(), chan.contentLength);
@ -127,7 +114,7 @@ add_test(function testSync() {
*/ */
add_test(function testSyncNested() { add_test(function testSyncNested() {
var uri = "jar:" + jarBase + "/inner40.zip!/foo"; var uri = "jar:" + jarBase + "/inner40.zip!/foo";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
var stream = chan.open(); var stream = chan.open();
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
Assert.equal(stream.available(), chan.contentLength); Assert.equal(stream.available(), chan.contentLength);
@ -142,7 +129,7 @@ add_test(function testSyncNested() {
*/ */
add_test(function testAsyncNested(next) { add_test(function testAsyncNested(next) {
var uri = "jar:" + jarBase + "/inner40.zip!/foo"; var uri = "jar:" + jarBase + "/inner40.zip!/foo";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
chan.asyncOpen(new Listener(function(l) { chan.asyncOpen(new Listener(function(l) {
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
Assert.ok(l.gotStartRequest); Assert.ok(l.gotStartRequest);
@ -162,7 +149,7 @@ add_test(function testSyncCloseUnlocks() {
copy.append(fileBase); copy.append(fileBase);
file.copyTo(copy.parent, copy.leafName); file.copyTo(copy.parent, copy.leafName);
var uri = "jar:" + ios.newFileURI(copy).spec + "!/inner40.zip"; var uri = "jar:" + ios.newFileURI(copy).spec + "!/inner40.zip";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
var stream = chan.open(); var stream = chan.open();
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
stream.close(); stream.close();
@ -172,8 +159,7 @@ add_test(function testSyncCloseUnlocks() {
try { try {
copy.remove(false); copy.remove(false);
} } catch (ex) {
catch (ex) {
do_throw(ex); do_throw(ex);
} }
@ -190,9 +176,9 @@ add_test(function testAsyncCloseUnlocks() {
file.copyTo(copy.parent, copy.leafName); file.copyTo(copy.parent, copy.leafName);
var uri = "jar:" + ios.newFileURI(copy).spec + "!/inner40.zip"; var uri = "jar:" + ios.newFileURI(copy).spec + "!/inner40.zip";
var chan = NetUtil.newChannel({uri: uri, loadUsingSystemPrincipal: true}); var chan = NetUtil.newChannel({uri, loadUsingSystemPrincipal: true});
chan.asyncOpen(new Listener(function (l) { chan.asyncOpen(new Listener(function(l) {
Assert.ok(chan.contentLength > 0); Assert.ok(chan.contentLength > 0);
// Drop any jar caches // Drop any jar caches
@ -200,8 +186,7 @@ add_test(function testAsyncCloseUnlocks() {
try { try {
copy.remove(false); copy.remove(false);
} } catch (ex) {
catch (ex) {
do_throw(ex); do_throw(ex);
} }

View file

@ -4,8 +4,7 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function wrapInputStream(input) function wrapInputStream(input) {
{
var nsIScriptableInputStream = Ci.nsIScriptableInputStream; var nsIScriptableInputStream = Ci.nsIScriptableInputStream;
var factory = Cc["@mozilla.org/scriptableinputstream;1"]; var factory = Cc["@mozilla.org/scriptableinputstream;1"];
var wrapper = factory.createInstance(nsIScriptableInputStream); var wrapper = factory.createInstance(nsIScriptableInputStream);
@ -19,17 +18,17 @@ function run_test() {
var file = do_get_file("data/test_bug333423.zip"); var file = do_get_file("data/test_bug333423.zip");
var zipreader = Cc["@mozilla.org/libjar/zip-reader;1"]. var zipreader = Cc["@mozilla.org/libjar/zip-reader;1"].
createInstance(Ci.nsIZipReader); createInstance(Ci.nsIZipReader);
zipreader.open(file); zipreader.open(file);
// do crc stuff // do crc stuff
function check_archive_crc() { function check_archive_crc() {
zipreader.test(null); zipreader.test(null);
return true; return true;
} }
Assert.ok(check_archive_crc()) Assert.ok(check_archive_crc());
var entries = zipreader.findEntries(null); zipreader.findEntries(null);
var stream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/Makefile.in")) var stream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/Makefile.in"));
var dirstream= wrapInputStream(zipreader.getInputStream("modules/libjar/test/")) var dirstream = wrapInputStream(zipreader.getInputStream("modules/libjar/test/"));
zipreader.close(); zipreader.close();
zipreader = null; zipreader = null;
Cu.forceGC(); Cu.forceGC();

View file

@ -1,20 +1,19 @@
// Should report file not found on non-existent files // Should report file not found on non-existent files
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm"); const {NetUtil} = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
const path = "data/test_bug333423.zip"; const path = "data/test_bug333423.zip";
function run_test() { function run_test() {
var ios = Cc["@mozilla.org/network/io-service;1"]. var spec = "jar:" + Services.io.newFileURI(do_get_file(path)).spec + "!/";
getService(Ci.nsIIOService);
var spec = "jar:" + ios.newFileURI(do_get_file(path)).spec + "!/";
var channel = NetUtil.newChannel({ var channel = NetUtil.newChannel({
uri: spec + "file_that_isnt_in.archive", uri: spec + "file_that_isnt_in.archive",
loadUsingSystemPrincipal: true loadUsingSystemPrincipal: true,
}); });
try { try {
instr = channel.open(); channel.open();
do_throw("Failed to report that file doesn't exist") do_throw("Failed to report that file doesn't exist");
} catch (e) { } catch (e) {
Assert.ok(e.name == "NS_ERROR_FILE_NOT_FOUND") Assert.ok(e.name == "NS_ERROR_FILE_NOT_FOUND");
} }
} }

View file

@ -1,7 +1,7 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function run_test() { function run_test() {
var dirService = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties); var tmpDir = Services.dirsvc.get("TmpD", Ci.nsIFile);
var tmpDir = dirService.get("TmpD", Ci.nsIFile);
var zipfile = do_get_file("data/test_umlaute.zip"); var zipfile = do_get_file("data/test_umlaute.zip");
@ -15,7 +15,7 @@ function run_test() {
zipreader.open(zipfile); zipreader.open(zipfile);
var entries = zipreader.findEntries(null); var entries = zipreader.findEntries(null);
Assert.ok(entries.hasMore()); Assert.ok(entries.hasMore());
var entryName = entries.getNext(); var entryName = entries.getNext();
Assert.equal(entryName, "test_\u00FC.txt"); Assert.equal(entryName, "test_\u00FC.txt");

View file

@ -5,20 +5,20 @@
const NS_ERROR_IN_PROGRESS = 2152398863; const NS_ERROR_IN_PROGRESS = 2152398863;
const PR_RDONLY = 0x01 const PR_RDONLY = 0x01;
const PR_WRONLY = 0x02 const PR_WRONLY = 0x02;
const PR_RDWR = 0x04 const PR_RDWR = 0x04;
const PR_CREATE_FILE = 0x08 const PR_CREATE_FILE = 0x08;
const PR_APPEND = 0x10 const PR_APPEND = 0x10;
const PR_TRUNCATE = 0x20 const PR_TRUNCATE = 0x20;
const PR_SYNC = 0x40 const PR_SYNC = 0x40;
const PR_EXCL = 0x80 const PR_EXCL = 0x80;
const ZIP_EOCDR_HEADER_SIZE = 22; const ZIP_EOCDR_HEADER_SIZE = 22;
const ZIP_FILE_HEADER_SIZE = 30; const ZIP_FILE_HEADER_SIZE = 30;
const ZIP_CDS_HEADER_SIZE = 46; const ZIP_CDS_HEADER_SIZE = 46;
const ZIP_METHOD_STORE = 0 const ZIP_METHOD_STORE = 0;
const ZIP_METHOD_DEFLATE = 8 const ZIP_METHOD_DEFLATE = 8;
const ZIP_EXTENDED_TIMESTAMP_SIZE = 9; const ZIP_EXTENDED_TIMESTAMP_SIZE = 9;
const PR_USEC_PER_MSEC = 1000; const PR_USEC_PER_MSEC = 1000;
@ -27,13 +27,13 @@ const PR_MSEC_PER_SEC = 1000;
const DATA_DIR = "data/"; const DATA_DIR = "data/";
var ioSvc = Cc["@mozilla.org/network/io-service;1"] const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
.getService(Ci.nsIIOService); var ioSvc = Services.io;
var ZipWriter = Components.Constructor("@mozilla.org/zipwriter;1", var ZipWriter = Components.Constructor("@mozilla.org/zipwriter;1",
"nsIZipWriter"); "nsIZipWriter");
var ZipReader = Components.Constructor("@mozilla.org/libjar/zip-reader;1", var ZipReader = Components.Constructor("@mozilla.org/libjar/zip-reader;1",
"nsIZipReader", "open"); "nsIZipReader", "open");
var tmpDir = do_get_profile(); var tmpDir = do_get_profile();
var tmpFile = tmpDir.clone(); var tmpFile = tmpDir.clone();

View file

@ -11,44 +11,40 @@ const time = 1199145600000; // Jan 1st 2008
var TESTS = [ var TESTS = [
{ {
name: "test.txt", name: "test.txt",
compression: Ci.nsIZipWriter.COMPRESSION_DEFAULT compression: Ci.nsIZipWriter.COMPRESSION_DEFAULT,
}, },
{ {
name: "test.png", name: "test.png",
compression: Ci.nsIZipWriter.COMPRESSION_NONE compression: Ci.nsIZipWriter.COMPRESSION_NONE,
} },
]; ];
function swap16(n) function swap16(n) {
{ return (((n >> 8) & 0xFF) << 0) |
return (((n >> 8) & 0xFF) << 0) | (((n >> 0) & 0xFF) << 8);
(((n >> 0) & 0xFF) << 8);
} }
function swap32(n) function swap32(n) {
{ return (((n >> 24) & 0xFF) << 0) |
return (((n >> 24) & 0xFF) << 0) | (((n >> 16) & 0xFF) << 8) |
(((n >> 16) & 0xFF) << 8) | (((n >> 8) & 0xFF) << 16) |
(((n >> 8) & 0xFF) << 16) | (((n >> 0) & 0xFF) << 24);
(((n >> 0) & 0xFF) << 24);
} }
function move_to_data(bis, offset) function move_to_data(bis, offset) {
{
bis.readBytes(18); // Move to compressed size bis.readBytes(18); // Move to compressed size
var size = swap32(bis.read32()); var size = swap32(bis.read32());
bis.readBytes(4); bis.readBytes(4);
var file_len = swap16(bis.read16()); var file_len = swap16(bis.read16());
var extra_len = swap16(bis.read16()); var extra_len = swap16(bis.read16());
var file = bis.readBytes(file_len); bis.readBytes(file_len);
bis.readBytes(extra_len); bis.readBytes(extra_len);
offset += ZIP_FILE_HEADER_SIZE + file_len + extra_len; offset += ZIP_FILE_HEADER_SIZE + file_len + extra_len;
return {offset: offset, size: size}; return {offset, size};
} }
function test_alignment(align_size) function test_alignment(align_size) {
{
// Create zip for testing. // Create zip for testing.
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
for (var i = 0; i < TESTS.length; i++) { for (var i = 0; i < TESTS.length; i++) {
@ -56,17 +52,17 @@ function test_alignment(align_size)
zipW.addEntryFile(TESTS[i].name, TESTS[i].compression, source, false); zipW.addEntryFile(TESTS[i].name, TESTS[i].compression, source, false);
} }
var stream = Cc["@mozilla.org/io/string-input-stream;1"] var stream = Cc["@mozilla.org/io/string-input-stream;1"]
.createInstance(Ci.nsIStringInputStream); .createInstance(Ci.nsIStringInputStream);
stream.setData(DATA, DATA.length); stream.setData(DATA, DATA.length);
zipW.addEntryStream(FILENAME, time * PR_USEC_PER_MSEC, zipW.addEntryStream(FILENAME, time * PR_USEC_PER_MSEC,
Ci.nsIZipWriter.COMPRESSION_NONE, stream, false); Ci.nsIZipWriter.COMPRESSION_NONE, stream, false);
zipW.alignStoredFiles(align_size); zipW.alignStoredFiles(align_size);
zipW.close(); zipW.close();
// Check data can be decompressed. // Check data can be decompressed.
var zipR = new ZipReader(tmpFile); var zipR = new ZipReader(tmpFile);
var stream = Cc["@mozilla.org/scriptableinputstream;1"] stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream); .createInstance(Ci.nsIScriptableInputStream);
stream.init(zipR.getInputStream(FILENAME)); stream.init(zipR.getInputStream(FILENAME));
var result = stream.read(DATA.length); var result = stream.read(DATA.length);
Assert.equal(result, DATA); Assert.equal(result, DATA);
@ -75,10 +71,10 @@ function test_alignment(align_size)
// Check data is correct and aligned. // Check data is correct and aligned.
var fis = Cc["@mozilla.org/network/file-input-stream;1"] var fis = Cc["@mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream); .createInstance(Ci.nsIFileInputStream);
fis.init(tmpFile, -1, -1, null); fis.init(tmpFile, -1, -1, null);
let bis = Cc["@mozilla.org/binaryinputstream;1"] let bis = Cc["@mozilla.org/binaryinputstream;1"]
.createInstance(Ci.nsIBinaryInputStream); .createInstance(Ci.nsIBinaryInputStream);
bis.setInputStream(fis); bis.setInputStream(fis);
var offset = 0; var offset = 0;
@ -95,7 +91,7 @@ function test_alignment(align_size)
ret = move_to_data(bis, offset); // "test_data.txt" ret = move_to_data(bis, offset); // "test_data.txt"
offset = ret.offset; offset = ret.offset;
var result = bis.readBytes(DATA.length); result = bis.readBytes(DATA.length);
Assert.equal(result, DATA); Assert.equal(result, DATA);
Assert.equal(offset % align_size, 0); Assert.equal(offset % align_size, 0);
@ -103,8 +99,7 @@ function test_alignment(align_size)
bis.close(); bis.close();
} }
function run_test() function run_test() {
{
test_alignment(2); test_alignment(2);
test_alignment(4); test_alignment(4);
test_alignment(16); test_alignment(16);

View file

@ -10,24 +10,22 @@ var TESTS = [
{ {
name: "test.txt", name: "test.txt",
size: 232, size: 232,
crc: 0x0373ac26 crc: 0x0373ac26,
}, },
{ {
name: "test.png", name: "test.png",
size: 3402, size: 3402,
crc: 0x504a5c30 crc: 0x504a5c30,
} },
]; ];
var size = 0; var size = 0;
var observer = { var observer = {
onStartRequest: function(request, context) onStartRequest(request, context) {
{
}, },
onStopRequest: function(request, context, status) onStopRequest(request, context, status) {
{
Assert.equal(status, Cr.NS_OK); Assert.equal(status, Cr.NS_OK);
zipW.close(); zipW.close();
@ -57,47 +55,43 @@ var observer = {
zipR.close(); zipR.close();
do_test_finished(); do_test_finished();
} },
}; };
var methods = { var methods = {
file: function method_file(entry, source) file: function method_file(entry, source) {
{
zipW.addEntryFile(entry, Ci.nsIZipWriter.COMPRESSION_NONE, source, zipW.addEntryFile(entry, Ci.nsIZipWriter.COMPRESSION_NONE, source,
true); true);
}, },
channel: function method_channel(entry, source) channel: function method_channel(entry, source) {
{
zipW.addEntryChannel(entry, source.lastModifiedTime * PR_MSEC_PER_SEC, zipW.addEntryChannel(entry, source.lastModifiedTime * PR_MSEC_PER_SEC,
Ci.nsIZipWriter.COMPRESSION_NONE, Ci.nsIZipWriter.COMPRESSION_NONE,
NetUtil.newChannel({ NetUtil.newChannel({
uri: ioSvc.newFileURI(source), uri: ioSvc.newFileURI(source),
loadUsingSystemPrincipal: true loadUsingSystemPrincipal: true,
}), true); }), true);
}, },
stream: function method_stream(entry, source) stream: function method_stream(entry, source) {
{
zipW.addEntryStream(entry, source.lastModifiedTime * PR_MSEC_PER_SEC, zipW.addEntryStream(entry, source.lastModifiedTime * PR_MSEC_PER_SEC,
Ci.nsIZipWriter.COMPRESSION_NONE, Ci.nsIZipWriter.COMPRESSION_NONE,
NetUtil.newChannel({ NetUtil.newChannel({
uri: ioSvc.newFileURI(source), uri: ioSvc.newFileURI(source),
loadUsingSystemPrincipal: true loadUsingSystemPrincipal: true,
}).open(), true); }).open(), true);
} },
} };
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
for (var i = 0; i < TESTS.length; i++) { for (var i = 0; i < TESTS.length; i++) {
var source = do_get_file(DATA_DIR+TESTS[i].name); var source = do_get_file(DATA_DIR + TESTS[i].name);
for (let method in methods) { for (let method in methods) {
var entry = method + "/" + TESTS[i].name; var entry = method + "/" + TESTS[i].name;
methods[method](entry, source); methods[method](entry, source);
size += ZIP_FILE_HEADER_SIZE + ZIP_CDS_HEADER_SIZE + size += ZIP_FILE_HEADER_SIZE + ZIP_CDS_HEADER_SIZE +
(ZIP_EXTENDED_TIMESTAMP_SIZE * 2) + (ZIP_EXTENDED_TIMESTAMP_SIZE * 2) +
(entry.length*2) + TESTS[i].size; (entry.length * 2) + TESTS[i].size;
} }
} }
do_test_pending(); do_test_pending();

View file

@ -6,21 +6,18 @@
const FILENAME = "missing.txt"; const FILENAME = "missing.txt";
var observer = { var observer = {
onStartRequest: function(request, context) onStartRequest(request, context) {
{
}, },
onStopRequest: function(request, context, status) onStopRequest(request, context, status) {
{
Assert.equal(status, Cr.NS_ERROR_FILE_NOT_FOUND); Assert.equal(status, Cr.NS_ERROR_FILE_NOT_FOUND);
zipW.close(); zipW.close();
Assert.equal(ZIP_EOCDR_HEADER_SIZE, tmpFile.fileSize); Assert.equal(ZIP_EOCDR_HEADER_SIZE, tmpFile.fileSize);
do_test_finished(); do_test_finished();
} },
}; };
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
var source = tmpDir.clone(); var source = tmpDir.clone();

View file

@ -6,21 +6,18 @@
const FILENAME = "missing.txt"; const FILENAME = "missing.txt";
var observer = { var observer = {
onStartRequest: function(request, context) onStartRequest(request, context) {
{
}, },
onStopRequest: function(request, context, status) onStopRequest(request, context, status) {
{
Assert.equal(status, Cr.NS_ERROR_FILE_NOT_FOUND); Assert.equal(status, Cr.NS_ERROR_FILE_NOT_FOUND);
zipW.close(); zipW.close();
Assert.equal(ZIP_EOCDR_HEADER_SIZE, tmpFile.fileSize); Assert.equal(ZIP_EOCDR_HEADER_SIZE, tmpFile.fileSize);
do_test_finished(); do_test_finished();
} },
}; };
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
zipW.removeEntry(FILENAME, true); zipW.removeEntry(FILENAME, true);
do_test_pending(); do_test_pending();

View file

@ -5,16 +5,14 @@
var TESTS = [ var TESTS = [
"test.txt", "test.txt",
"test.png" "test.png",
]; ];
var observer = { var observer = {
onStartRequest: function(request, context) onStartRequest(request, context) {
{
}, },
onStopRequest: function(request, context, status) onStopRequest(request, context, status) {
{
Assert.equal(status, Cr.NS_OK); Assert.equal(status, Cr.NS_OK);
zipW.close(); zipW.close();
@ -23,11 +21,10 @@ var observer = {
var newTmpFile = tmpFile.clone(); var newTmpFile = tmpFile.clone();
Assert.equal(newTmpFile.fileSize, ZIP_EOCDR_HEADER_SIZE); Assert.equal(newTmpFile.fileSize, ZIP_EOCDR_HEADER_SIZE);
do_test_finished(); do_test_finished();
} },
}; };
function run_test() function run_test() {
{
// Copy our test zip to the tmp dir so we can modify it // Copy our test zip to the tmp dir so we can modify it
var testzip = do_get_file(DATA_DIR + "test.zip"); var testzip = do_get_file(DATA_DIR + "test.zip");
testzip.copyTo(tmpDir, tmpFile.leafName); testzip.copyTo(tmpDir, tmpFile.leafName);

View file

@ -21,17 +21,17 @@ BinaryComparer.prototype = {
length: null, length: null,
callback: null, callback: null,
onStartRequest: function(aRequest, aContext) { onStartRequest(aRequest, aContext) {
}, },
onStopRequest: function(aRequest, aContext, aStatusCode) { onStopRequest(aRequest, aContext, aStatusCode) {
this.fileStream.close(); this.fileStream.close();
Assert.equal(aStatusCode, Cr.NS_OK); Assert.equal(aStatusCode, Cr.NS_OK);
Assert.equal(this.offset, this.length); Assert.equal(this.offset, this.length);
this.callback(); this.callback();
}, },
onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) { onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount) {
var stream = Cc["@mozilla.org/binaryinputstream;1"]. var stream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream); createInstance(Ci.nsIBinaryInputStream);
stream.setInputStream(aInputStream); stream.setInputStream(aInputStream);
@ -39,34 +39,30 @@ BinaryComparer.prototype = {
for (var i = 0; i < aCount; i++) { for (var i = 0; i < aCount; i++) {
try { try {
source = this.fileStream.read8(); source = this.fileStream.read8();
} } catch (e) {
catch (e) {
do_throw("Unable to read from file at offset " + this.offset + " " + e); do_throw("Unable to read from file at offset " + this.offset + " " + e);
} }
try { try {
actual = stream.read8(); actual = stream.read8();
} } catch (e) {
catch (e) {
do_throw("Unable to read from converted stream at offset " + this.offset + " " + e); do_throw("Unable to read from converted stream at offset " + this.offset + " " + e);
} }
if (source != actual) if (source != actual)
do_throw("Invalid value " + actual + " at offset " + this.offset + ", should have been " + source); do_throw("Invalid value " + actual + " at offset " + this.offset + ", should have been " + source);
this.offset++; this.offset++;
} }
} },
} };
function comparer_callback() function comparer_callback() {
{
do_test_finished(); do_test_finished();
} }
function run_test() function run_test() {
{
var source = do_get_file(DATA_DIR + "test_bug399727.html"); var source = do_get_file(DATA_DIR + "test_bug399727.html");
var comparer = new BinaryComparer(do_get_file(DATA_DIR + "test_bug399727.zlib"), var comparer = new BinaryComparer(do_get_file(DATA_DIR + "test_bug399727.zlib"),
comparer_callback); comparer_callback);
// Prepare the stream converter // Prepare the stream converter
var scs = Cc["@mozilla.org/streamConverters;1"]. var scs = Cc["@mozilla.org/streamConverters;1"].
getService(Ci.nsIStreamConverterService); getService(Ci.nsIStreamConverterService);

View file

@ -9,8 +9,7 @@ const CRC = 0x00000000;
// XXX Must use a constant time here away from DST changes. See bug 402434. // XXX Must use a constant time here away from DST changes. See bug 402434.
const time = 1199145600000; // Jan 1st 2008 const time = 1199145600000; // Jan 1st 2008
function testpass(source) function testpass(source) {
{
// Should exist. // Should exist.
Assert.ok(source.hasEntry(FILENAME)); Assert.ok(source.hasEntry(FILENAME));
@ -31,8 +30,7 @@ function testpass(source)
Assert.equal(entry.CRC32, CRC); Assert.equal(entry.CRC32, CRC);
} }
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
// Shouldn't be there to start with. // Shouldn't be there to start with.
@ -41,10 +39,10 @@ function run_test()
Assert.ok(!zipW.inQueue); Assert.ok(!zipW.inQueue);
var stream = Cc["@mozilla.org/io/string-input-stream;1"] var stream = Cc["@mozilla.org/io/string-input-stream;1"]
.createInstance(Ci.nsIStringInputStream); .createInstance(Ci.nsIStringInputStream);
stream.setData(DATA, DATA.length); stream.setData(DATA, DATA.length);
zipW.addEntryStream(FILENAME, time * PR_USEC_PER_MSEC, zipW.addEntryStream(FILENAME, time * PR_USEC_PER_MSEC,
Ci.nsIZipWriter.COMPRESSION_BEST, stream, false); Ci.nsIZipWriter.COMPRESSION_BEST, stream, false);
// Check that zip state is right at this stage. // Check that zip state is right at this stage.
testpass(zipW); testpass(zipW);
@ -59,8 +57,8 @@ function run_test()
var zipR = new ZipReader(tmpFile); var zipR = new ZipReader(tmpFile);
testpass(zipR); testpass(zipR);
zipR.test(FILENAME); zipR.test(FILENAME);
var stream = Cc["@mozilla.org/scriptableinputstream;1"] stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream); .createInstance(Ci.nsIScriptableInputStream);
stream.init(zipR.getInputStream(FILENAME)); stream.init(zipR.getInputStream(FILENAME));
var result = stream.read(DATA.length); var result = stream.read(DATA.length);
stream.close(); stream.close();

View file

@ -8,8 +8,7 @@ const FILENAME = "test.txt";
const CRC = 0x00000000; const CRC = 0x00000000;
const time = Date.now(); const time = Date.now();
function testpass(source) function testpass(source) {
{
// Should exist. // Should exist.
Assert.ok(source.hasEntry(FILENAME)); Assert.ok(source.hasEntry(FILENAME));
@ -28,8 +27,7 @@ function testpass(source)
Assert.equal(entry.CRC32, CRC); Assert.equal(entry.CRC32, CRC);
} }
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
// Shouldn't be there to start with. // Shouldn't be there to start with.

View file

@ -6,8 +6,7 @@
const DIRNAME = "test/"; const DIRNAME = "test/";
const time = Date.now(); const time = Date.now();
function run_test() function run_test() {
{
// Copy in the test file. // Copy in the test file.
var source = do_get_file("data/test.zip"); var source = do_get_file("data/test.zip");
source.copyTo(tmpFile.parent, tmpFile.leafName); source.copyTo(tmpFile.parent, tmpFile.leafName);

View file

@ -3,71 +3,61 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
function run_test() function run_test() {
{
var test;
// zipW is an uninitialised zipwriter at this point. // zipW is an uninitialised zipwriter at this point.
try { try {
test = zipW.file; zipW.file;
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
test = zipW.comment; zipW.comment;
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.comment = "test"; zipW.comment = "test";
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.addEntryDirectory("test", 0, false); zipW.addEntryDirectory("test", 0, false);
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.addEntryFile("test", Ci.nsIZipWriter.COMPRESSION_DEFAULT, tmpDir, false); zipW.addEntryFile("test", Ci.nsIZipWriter.COMPRESSION_DEFAULT, tmpDir, false);
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.removeEntry("test", false); zipW.removeEntry("test", false);
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.processQueue(null, null); zipW.processQueue(null, null);
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
try { try {
zipW.close(); zipW.close();
do_throw("Should have thrown uninitialized error."); do_throw("Should have thrown uninitialized error.");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED); Assert.equal(e.result, Cr.NS_ERROR_NOT_INITIALIZED);
} }
} }

View file

@ -5,17 +5,16 @@ function run_test() {
} }
// Add |file| to the zip. |path| is the current path for the file. // Add |file| to the zip. |path| is the current path for the file.
function AddToZip(zipWriter, path, file) function AddToZip(zipWriter, path, file) {
{
var currentPath = path + file.leafName; var currentPath = path + file.leafName;
if (file.isDirectory()) { if (file.isDirectory()) {
currentPath += "/"; currentPath += "/";
} }
// THIS IS WHERE THE ERROR OCCURS, FOR THE FILE "st14-1.tiff" IN "test_bug446708" // THIS IS WHERE THE ERROR OCCURS, FOR THE FILE "st14-1.tiff" IN "test_bug446708"
zipWriter.addEntryFile(currentPath, Ci.nsIZipWriter.COMPRESSION_DEFAULT, file, false); zipWriter.addEntryFile(currentPath, Ci.nsIZipWriter.COMPRESSION_DEFAULT, file, false);
// if it's a dir, continue adding its contents recursively... // if it's a dir, continue adding its contents recursively...
if (file.isDirectory()) { if (file.isDirectory()) {
var entries = file.QueryInterface(Ci.nsIFile).directoryEntries; var entries = file.QueryInterface(Ci.nsIFile).directoryEntries;
@ -24,14 +23,13 @@ function AddToZip(zipWriter, path, file)
AddToZip(zipWriter, currentPath, entry); AddToZip(zipWriter, currentPath, entry);
} }
} }
// ...otherwise, we're done // ...otherwise, we're done
} }
function RecursivelyZipDirectory(bundle) function RecursivelyZipDirectory(bundle) {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
AddToZip(zipW, "", bundle); AddToZip(zipW, "", bundle);
zipW.close(); zipW.close();
} }

View file

@ -3,8 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
function run_test() function run_test() {
{
// In this test we try to open some files that aren't archives: // In this test we try to open some files that aren't archives:
// - An empty file, that is certainly not an archive. // - An empty file, that is certainly not an archive.
// - A file that couldn't be mistaken for archive, since it is too small. // - A file that couldn't be mistaken for archive, since it is too small.

View file

@ -4,11 +4,11 @@
function BinaryComparer(file, callback) { function BinaryComparer(file, callback) {
var fstream = Cc["@mozilla.org/network/file-input-stream;1"]. var fstream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream); createInstance(Ci.nsIFileInputStream);
fstream.init(file, -1, 0, 0); fstream.init(file, -1, 0, 0);
this.length = file.fileSize; this.length = file.fileSize;
this.fileStream = Cc["@mozilla.org/binaryinputstream;1"]. this.fileStream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream); createInstance(Ci.nsIBinaryInputStream);
this.fileStream.setInputStream(fstream); this.fileStream.setInputStream(fstream);
this.offset = 0; this.offset = 0;
this.callback = callback; this.callback = callback;
@ -20,72 +20,69 @@ BinaryComparer.prototype = {
length: null, length: null,
callback: null, callback: null,
onStartRequest: function(aRequest, aContext) { onStartRequest(aRequest, aContext) {
}, },
onStopRequest: function(aRequest, aContext, aStatusCode) { onStopRequest(aRequest, aContext, aStatusCode) {
this.fileStream.close(); this.fileStream.close();
Assert.equal(aStatusCode, Cr.NS_OK); Assert.equal(aStatusCode, Cr.NS_OK);
Assert.equal(this.offset, this.length); Assert.equal(this.offset, this.length);
this.callback(); this.callback();
}, },
onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) { onDataAvailable(aRequest, aContext, aInputStream, aOffset, aCount) {
var stream = Cc["@mozilla.org/binaryinputstream;1"]. var stream = Cc["@mozilla.org/binaryinputstream;1"].
createInstance(Ci.nsIBinaryInputStream); createInstance(Ci.nsIBinaryInputStream);
stream.setInputStream(aInputStream); stream.setInputStream(aInputStream);
var source, actual; var source, actual;
for (var i = 0; i < aCount; i++) { for (var i = 0; i < aCount; i++) {
try { try {
source = this.fileStream.read8(); source = this.fileStream.read8();
} } catch (e) {
catch (e) {
do_throw("Unable to read from file at offset " + this.offset + " " + e); do_throw("Unable to read from file at offset " + this.offset + " " + e);
} }
try { try {
actual = stream.read8(); actual = stream.read8();
} } catch (e) {
catch (e) { do_throw("Unable to read from converted stream at offset " +
do_throw("Unable to read from converted stream at offset " + this.offset + " " + e); this.offset + " " + e);
} }
// The byte at offset 9 is the OS byte (see RFC 1952, section 2.3), which // The byte at offset 9 is the OS byte (see RFC 1952, section 2.3), which
// can legitimately differ when the source is compressed on different // can legitimately differ when the source is compressed on different
// operating systems. The actual .gz for this test was created on a Unix // operating systems. The actual .gz for this test was created on a Unix
// system, but we want the test to work correctly everywhere. So ignore // system, but we want the test to work correctly everywhere. So ignore
// the byte at offset 9. // the byte at offset 9.
if (this.offset == 9) if (this.offset != 9 && source != actual) {
; do_throw("Invalid value " + actual + " at offset " +
else if (source != actual) this.offset + ", should have been " + source);
do_throw("Invalid value " + actual + " at offset " + this.offset + ", should have been " + source); }
this.offset++; this.offset++;
} }
} },
} };
function comparer_callback() function comparer_callback() {
{
do_test_finished(); do_test_finished();
} }
function run_test() function run_test() {
{
var source = do_get_file(DATA_DIR + "test_bug717061.html"); var source = do_get_file(DATA_DIR + "test_bug717061.html");
var comparer = new BinaryComparer(do_get_file(DATA_DIR + "test_bug717061.gz"), var comparer = new BinaryComparer(do_get_file(DATA_DIR + "test_bug717061.gz"),
comparer_callback); comparer_callback);
// Prepare the stream converter // Prepare the stream converter
var scs = Cc["@mozilla.org/streamConverters;1"]. var scs = Cc["@mozilla.org/streamConverters;1"].
getService(Ci.nsIStreamConverterService); getService(Ci.nsIStreamConverterService);
var converter = scs.asyncConvertData("uncompressed", "gzip", comparer, null); var converter = scs.asyncConvertData("uncompressed", "gzip", comparer, null);
// Open the expected output file // Open the expected output file
var fstream = Cc["@mozilla.org/network/file-input-stream;1"]. var fstream = Cc["@mozilla.org/network/file-input-stream;1"].
createInstance(Ci.nsIFileInputStream); createInstance(Ci.nsIFileInputStream);
fstream.init(source, -1, 0, 0); fstream.init(source, -1, 0, 0);
// Set up a pump to push data from the file to the stream converter // Set up a pump to push data from the file to the stream converter
var pump = Cc["@mozilla.org/network/input-stream-pump;1"]. var pump = Cc["@mozilla.org/network/input-stream-pump;1"].
createInstance(Ci.nsIInputStreamPump); createInstance(Ci.nsIInputStreamPump);
pump.init(fstream, 0, 0, true); pump.init(fstream, 0, 0, true);
pump.asyncRead(converter, null); pump.asyncRead(converter, null);
do_test_pending(); do_test_pending();

View file

@ -3,8 +3,7 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/ */
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
zipW.close(); zipW.close();

View file

@ -9,8 +9,7 @@ const CRC = 0xe6164331;
// XXX Must use a constant time here away from DST changes. See bug 402434. // XXX Must use a constant time here away from DST changes. See bug 402434.
const time = 1199145600000; // Jan 1st 2008 const time = 1199145600000; // Jan 1st 2008
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
// Shouldn't be there to start with. // Shouldn't be there to start with.
@ -42,7 +41,7 @@ function run_test()
zipR.test(FILENAME); zipR.test(FILENAME);
var stream = Cc["@mozilla.org/scriptableinputstream;1"] stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream); .createInstance(Ci.nsIScriptableInputStream);
stream.init(zipR.getInputStream(FILENAME)); stream.init(zipR.getInputStream(FILENAME));
var result = stream.read(DATA.length); var result = stream.read(DATA.length);

View file

@ -8,8 +8,7 @@ const DIRNAME1_CORRECT = "test/";
const DIRNAME2 = "test2/"; const DIRNAME2 = "test2/";
const time = Date.now(); const time = Date.now();
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
zipW.addEntryDirectory(DIRNAME1, time * PR_USEC_PER_MSEC, false); zipW.addEntryDirectory(DIRNAME1, time * PR_USEC_PER_MSEC, false);

View file

@ -9,19 +9,18 @@ var TESTS = [
name: "test.txt", name: "test.txt",
size: 232, size: 232,
crc: 0x0373ac26, crc: 0x0373ac26,
time: Date.UTC(2007, 4, 1, 20, 44, 55) time: Date.UTC(2007, 4, 1, 20, 44, 55),
}, },
{ {
name: "test.png", name: "test.png",
size: 3402, size: 3402,
crc: 0x504a5c30, crc: 0x504a5c30,
time: Date.UTC(2007, 4, 1, 20, 49, 39) time: Date.UTC(2007, 4, 1, 20, 49, 39),
} },
]; ];
var BADENTRY = "unknown.txt"; var BADENTRY = "unknown.txt";
function run_test() function run_test() {
{
// Copy our test zip to the tmp dir so we can modify it // Copy our test zip to the tmp dir so we can modify it
var testzip = do_get_file(DATA_DIR + "test.zip"); var testzip = do_get_file(DATA_DIR + "test.zip");
testzip.copyTo(tmpDir, tmpFile.leafName); testzip.copyTo(tmpDir, tmpFile.leafName);
@ -30,7 +29,7 @@ function run_test()
zipW.open(tmpFile, PR_RDWR); zipW.open(tmpFile, PR_RDWR);
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
Assert.ok(zipW.hasEntry(TESTS[i].name)); Assert.ok(zipW.hasEntry(TESTS[i].name));
var entry = zipW.getEntry(TESTS[i].name); var entry = zipW.getEntry(TESTS[i].name);
Assert.ok(entry != null); Assert.ok(entry != null);
@ -43,12 +42,11 @@ function run_test()
try { try {
zipW.removeEntry(BADENTRY, false); zipW.removeEntry(BADENTRY, false);
do_throw("shouldn't be able to remove an entry that doesn't exist"); do_throw("shouldn't be able to remove an entry that doesn't exist");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_FILE_NOT_FOUND); Assert.equal(e.result, Cr.NS_ERROR_FILE_NOT_FOUND);
} }
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
zipW.removeEntry(TESTS[i].name, false); zipW.removeEntry(TESTS[i].name, false);
} }

View file

@ -10,8 +10,7 @@ const CRC = 0xe6164331;
// XXX Must use a constant time here away from DST changes. See bug 402434. // XXX Must use a constant time here away from DST changes. See bug 402434.
const time = 1199145600000; // Jan 1st 2008 const time = 1199145600000; // Jan 1st 2008
function testpass(source) function testpass(source) {
{
// Should exist. // Should exist.
Assert.ok(source.hasEntry(FILENAME)); Assert.ok(source.hasEntry(FILENAME));
@ -34,8 +33,7 @@ function testpass(source)
Assert.equal(entry.CRC32, CRC); Assert.equal(entry.CRC32, CRC);
} }
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
// Shouldn't be there to start with. // Shouldn't be there to start with.
@ -67,7 +65,7 @@ function run_test()
var zipR = new ZipReader(tmpFile); var zipR = new ZipReader(tmpFile);
testpass(zipR); testpass(zipR);
zipR.test(FILENAME); zipR.test(FILENAME);
var stream = Cc["@mozilla.org/scriptableinputstream;1"] stream = Cc["@mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream); .createInstance(Ci.nsIScriptableInputStream);
stream.init(zipR.getInputStream(FILENAME)); stream.init(zipR.getInputStream(FILENAME));
var result = stream.read(DATA.length); var result = stream.read(DATA.length);

View file

@ -8,27 +8,26 @@ var TESTS = [
{ {
name: "test.txt", name: "test.txt",
size: 232, size: 232,
crc: 0x0373ac26 crc: 0x0373ac26,
}, },
{ {
name: "test.png", name: "test.png",
size: 3402, size: 3402,
crc: 0x504a5c30 crc: 0x504a5c30,
} },
]; ];
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
var size = 0; var size = 0;
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
var source = do_get_file(DATA_DIR + TESTS[i].name); let source = do_get_file(DATA_DIR + TESTS[i].name);
zipW.addEntryFile(TESTS[i].name, Ci.nsIZipWriter.COMPRESSION_NONE, source, zipW.addEntryFile(TESTS[i].name, Ci.nsIZipWriter.COMPRESSION_NONE, source,
false); false);
size += ZIP_FILE_HEADER_SIZE + ZIP_CDS_HEADER_SIZE + size += ZIP_FILE_HEADER_SIZE + ZIP_CDS_HEADER_SIZE +
(ZIP_EXTENDED_TIMESTAMP_SIZE * 2) + (ZIP_EXTENDED_TIMESTAMP_SIZE * 2) +
(TESTS[i].name.length*2) + TESTS[i].size; (TESTS[i].name.length * 2) + TESTS[i].size;
} }
zipW.close(); zipW.close();
@ -39,8 +38,8 @@ function run_test()
// Test the stored data with the zipreader // Test the stored data with the zipreader
var zipR = new ZipReader(tmpFile); var zipR = new ZipReader(tmpFile);
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
var source = do_get_file(DATA_DIR + TESTS[i].name); let source = do_get_file(DATA_DIR + TESTS[i].name);
Assert.ok(zipR.hasEntry(TESTS[i].name)); Assert.ok(zipR.hasEntry(TESTS[i].name));
var entry = zipR.getEntry(TESTS[i].name); var entry = zipR.getEntry(TESTS[i].name);

View file

@ -6,31 +6,29 @@
// Values taken from using zipinfo to list the test.zip contents // Values taken from using zipinfo to list the test.zip contents
var TESTS = [ var TESTS = [
"test.txt", "test.txt",
"test.png" "test.png",
]; ];
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
var source = do_get_file(DATA_DIR + TESTS[i]); let source = do_get_file(DATA_DIR + TESTS[i]);
zipW.addEntryFile(TESTS[i], Ci.nsIZipWriter.COMPRESSION_NONE, source, zipW.addEntryFile(TESTS[i], Ci.nsIZipWriter.COMPRESSION_NONE, source,
false); false);
} }
try { try {
var source = do_get_file(DATA_DIR + TESTS[0]); let source = do_get_file(DATA_DIR + TESTS[0]);
zipW.addEntryFile(TESTS[0], Ci.nsIZipWriter.COMPRESSION_NONE, source, zipW.addEntryFile(TESTS[0], Ci.nsIZipWriter.COMPRESSION_NONE, source,
false); false);
do_throw("Should not be able to add the same file twice"); do_throw("Should not be able to add the same file twice");
} } catch (e) {
catch (e) {
Assert.equal(e.result, Cr.NS_ERROR_FILE_ALREADY_EXISTS); Assert.equal(e.result, Cr.NS_ERROR_FILE_ALREADY_EXISTS);
} }
// Remove all the tests and see if we are left with an empty zip // Remove all the tests and see if we are left with an empty zip
for (var i = 0; i < TESTS.length; i++) { for (let i = 0; i < TESTS.length; i++) {
zipW.removeEntry(TESTS[i], false); zipW.removeEntry(TESTS[i], false);
} }

View file

@ -6,8 +6,7 @@
const DATA = "ZIP WRITER TEST COMMENT"; const DATA = "ZIP WRITER TEST COMMENT";
const DATA2 = "ANOTHER ONE"; const DATA2 = "ANOTHER ONE";
function run_test() function run_test() {
{
zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE); zipW.open(tmpFile, PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE);
zipW.comment = DATA; zipW.comment = DATA;
zipW.close(); zipW.close();

View file

@ -16,7 +16,7 @@ function build_tests() {
for (let o = 0; o <= 7; o++) { for (let o = 0; o <= 7; o++) {
TESTS[id] = { TESTS[id] = {
name: "test" + u + g + o, name: "test" + u + g + o,
permission: (u << 6) + (g << 3) + o permission: (u << 6) + (g << 3) + o,
}; };
id++; id++;
} }

View file

@ -2,7 +2,6 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() { function run_test() {
/** /**
* Creates MAR from the passed files, compares it to the reference MAR. * Creates MAR from the passed files, compares it to the reference MAR.
* *
@ -102,7 +101,7 @@ function run_test() {
if (outMAR.exists()) { if (outMAR.exists()) {
outMAR.remove(false); outMAR.remove(false);
} }
} },
}; };
// Run all the tests // Run all the tests

View file

@ -2,7 +2,6 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() { function run_test() {
/** /**
* Extracts a MAR and makes sure each file matches the reference files. * Extracts a MAR and makes sure each file matches the reference files.
* *
@ -114,7 +113,7 @@ function run_test() {
return extract_and_fail("manipulated_frontend_collision.mar"); return extract_and_fail("manipulated_frontend_collision.mar");
}, },
// Test collision detection where file B ends in file A's indexes // Test collision detection where file B ends in file A's indexes
test_collsion_b_onto_a: function test_collsion_b_onto_a() { test_collsion_b_onto_a: function test_collsion_b_onto_a() {
return extract_and_fail("manipulated_backend_collision.mar"); return extract_and_fail("manipulated_backend_collision.mar");
}, },
// Test collision detection where file C shares indexes with both file A & B // Test collision detection where file C shares indexes with both file A & B
@ -137,7 +136,7 @@ function run_test() {
if (outDir.exists()) { if (outDir.exists()) {
outDir.remove(true); outDir.remove(true);
} }
} },
}; };
// Run all the tests // Run all the tests

View file

@ -2,7 +2,6 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
function run_test() { function run_test() {
/** /**
* Signs a MAR file. * Signs a MAR file.
* *
@ -568,7 +567,7 @@ function run_test() {
}, },
// Between each test make sure the out MAR does not exist. // Between each test make sure the out MAR does not exist.
cleanup_per_test: function _cleanup_per_test() { cleanup_per_test: function _cleanup_per_test() {
} },
}; };
cleanup(); cleanup();

View file

@ -2375,7 +2375,6 @@ pref("network.proxy.failover_timeout", 1800); // 30 minutes
pref("network.online", true); //online/offline pref("network.online", true); //online/offline
pref("network.cookie.thirdparty.sessionOnly", false); pref("network.cookie.thirdparty.sessionOnly", false);
pref("network.cookie.thirdparty.nonsecureSessionOnly", false); pref("network.cookie.thirdparty.nonsecureSessionOnly", false);
pref("network.cookie.leave-secure-alone", true);
pref("network.cookie.same-site.enabled", true); // Honor the SameSite cookie attribute pref("network.cookie.same-site.enabled", true); // Honor the SameSite cookie attribute
// Cookie lifetime policy. Possible values: // Cookie lifetime policy. Possible values:

View file

@ -4,8 +4,7 @@
const NS_APP_USER_PROFILE_50_DIR = "ProfD"; const NS_APP_USER_PROFILE_50_DIR = "ProfD";
function do_check_throws(f, result, stack) function do_check_throws(f, result, stack) {
{
if (!stack) if (!stack)
stack = Components.stack.caller; stack = Components.stack.caller;
@ -18,22 +17,16 @@ function do_check_throws(f, result, stack)
ok(false, "expected result " + result + ", none thrown"); ok(false, "expected result " + result + ", none thrown");
} }
var dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
// Register current test directory as provider for the profile directory. // Register current test directory as provider for the profile directory.
var provider = { var provider = {
getFile: function(prop, persistent) { getFile(prop, persistent) {
persistent.value = true; persistent.value = true;
if (prop == NS_APP_USER_PROFILE_50_DIR) if (prop == NS_APP_USER_PROFILE_50_DIR)
return dirSvc.get("CurProcD", Ci.nsIFile); return Services.dirsvc.get("CurProcD", Ci.nsIFile);
throw Components.Exception("Tried to get test directory '" + prop + "'", Cr.NS_ERROR_FAILURE); throw Components.Exception("Tried to get test directory '" + prop + "'", Cr.NS_ERROR_FAILURE);
}, },
QueryInterface: function(iid) { QueryInterface: ChromeUtils.generateQI(["nsIDirectoryServiceProvider"]),
if (iid.equals(Ci.nsIDirectoryServiceProvider) ||
iid.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_ERROR_NO_INTERFACE;
}
}; };
dirSvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider); Services.dirsvc.QueryInterface(Ci.nsIDirectoryService).registerProvider(provider);

View file

@ -9,15 +9,13 @@ function run_test() {
const FLOAT = 9.674; const FLOAT = 9.674;
const FUDGE = 0.001; const FUDGE = 0.001;
let ps = Cc["@mozilla.org/preferences-service;1"] let prefs = Services.prefs.getDefaultBranch(null);
.getService(Ci.nsIPrefService);
let prefs = ps.getDefaultBranch(null);
/* Test with a non-default branch */ /* Test with a non-default branch */
prefs.setCharPref(FULL_PREF_NAME, FLOAT); prefs.setCharPref(FULL_PREF_NAME, FLOAT);
let pb = ps.getBranch(BRANCH); let pb = Services.prefs.getBranch(BRANCH);
let floatPref = pb.getFloatPref(PREF_NAME); let floatPref = pb.getFloatPref(PREF_NAME);
Assert.ok(FLOAT+FUDGE >= floatPref); Assert.ok(FLOAT + FUDGE >= floatPref);
Assert.ok(FLOAT-FUDGE <= floatPref); Assert.ok(FLOAT - FUDGE <= floatPref);
} }

View file

@ -1,32 +1,25 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/ */ * http://creativecommons.org/licenses/publicdomain/ */
// Regression test for bug 345529 - crash removing an observer during an // Regression test for bug 345529 - crash removing an observer during an
// nsPref:changed notification. // nsPref:changed notification.
function run_test() { function run_test() {
const PREF_NAME = "testPref"; const PREF_NAME = "testPref";
var prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefBranch);
var observer = { var observer = {
QueryInterface: function QueryInterface(aIID) { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_NOINTERFACE;
},
observe: function observe(aSubject, aTopic, aState) { observe: function observe(aSubject, aTopic, aState) {
prefs.removeObserver(PREF_NAME, observer); Services.prefs.removeObserver(PREF_NAME, observer);
} },
} };
prefs.addObserver(PREF_NAME, observer); Services.prefs.addObserver(PREF_NAME, observer);
prefs.setCharPref(PREF_NAME, "test0") Services.prefs.setCharPref(PREF_NAME, "test0");
// This second call isn't needed on a clean profile: it makes sure // This second call isn't needed on a clean profile: it makes sure
// the observer gets called even if the pref already had the value // the observer gets called even if the pref already had the value
// "test0" before this test. // "test0" before this test.
prefs.setCharPref(PREF_NAME, "test1") Services.prefs.setCharPref(PREF_NAME, "test1");
Assert.ok(true); Assert.ok(true);
} }

View file

@ -4,10 +4,8 @@
function run_test() { function run_test() {
const PREF_NAME = "testPref"; const PREF_NAME = "testPref";
var ps = Cc["@mozilla.org/preferences-service;1"] var prefs = Services.prefs.getDefaultBranch(null);
.getService(Ci.nsIPrefService); var userprefs = Services.prefs.getBranch(null);
var prefs = ps.getDefaultBranch(null);
var userprefs = ps.getBranch(null);
prefs.setCharPref(PREF_NAME, "test0"); prefs.setCharPref(PREF_NAME, "test0");
prefs.lockPref(PREF_NAME); prefs.lockPref(PREF_NAME);
@ -16,11 +14,11 @@ function run_test() {
var file = do_get_profile(); var file = do_get_profile();
file.append("prefs.js"); file.append("prefs.js");
ps.savePrefFile(file); Services.prefs.savePrefFile(file);
prefs.unlockPref(PREF_NAME); prefs.unlockPref(PREF_NAME);
prefs.setCharPref(PREF_NAME, "test1"); prefs.setCharPref(PREF_NAME, "test1");
ps.readUserPrefsFromFile(file); Services.prefs.readUserPrefsFromFile(file);
Assert.equal("test1", userprefs.getCharPref(PREF_NAME)); Assert.equal("test1", userprefs.getCharPref(PREF_NAME));
Assert.equal(false, userprefs.prefHasUserValue(PREF_NAME)); Assert.equal(false, userprefs.prefHasUserValue(PREF_NAME));

View file

@ -3,26 +3,15 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
function run_test() { function run_test() {
var ps = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
var pb = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
var observer = { var observer = {
QueryInterface: function QueryInterface(aIID) { QueryInterface: ChromeUtils.generateQI(["nsIObserver"]),
if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_NOINTERFACE;
},
observe: function observe(aSubject, aTopic, aState) { observe: function observe(aSubject, aTopic, aState) {
// Don't do anything. // Don't do anything.
} },
} };
/* Set the same pref twice. This shouldn't leak. */ /* Set the same pref twice. This shouldn't leak. */
pb.addObserver("UserPref.nonexistent.setIntPref", observer); Services.prefs.addObserver("UserPref.nonexistent.setIntPref", observer);
pb.addObserver("UserPref.nonexistent.setIntPref", observer); Services.prefs.addObserver("UserPref.nonexistent.setIntPref", observer);
} }

View file

@ -4,10 +4,8 @@
function run_test() { function run_test() {
const PREF_NAME = "testPref"; const PREF_NAME = "testPref";
var ps = Cc["@mozilla.org/preferences-service;1"] var prefs = Services.prefs.getDefaultBranch(null);
.getService(Ci.nsIPrefService); var userprefs = Services.prefs.getBranch(null);
var prefs = ps.getDefaultBranch(null);
var userprefs = ps.getBranch(null);
/* First, test to make sure we can parse a float from a string properly. */ /* First, test to make sure we can parse a float from a string properly. */
prefs.setCharPref(PREF_NAME, "9.674"); prefs.setCharPref(PREF_NAME, "9.674");
@ -15,8 +13,8 @@ function run_test() {
var myFloat = 9.674; var myFloat = 9.674;
var fudge = 0.001; var fudge = 0.001;
var floatPref = userprefs.getFloatPref(PREF_NAME); var floatPref = userprefs.getFloatPref(PREF_NAME);
Assert.ok(myFloat+fudge >= floatPref); Assert.ok(myFloat + fudge >= floatPref);
Assert.ok(myFloat-fudge <= floatPref); Assert.ok(myFloat - fudge <= floatPref);
/* Now test some failure conditions. */ /* Now test some failure conditions. */
prefs.unlockPref(PREF_NAME); prefs.unlockPref(PREF_NAME);

View file

@ -10,9 +10,7 @@ const PREF_INT = 64;
const PREF_STRING = 32; const PREF_STRING = 32;
function run_test() { function run_test() {
var ps = Services.prefs;
var ps = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
let defaultBranch = ps.getDefaultBranch(""); let defaultBranch = ps.getDefaultBranch("");
let userBranch = ps.getBranch(""); let userBranch = ps.getBranch("");
@ -39,11 +37,11 @@ function run_test() {
// Prefs that have both a default and a user value -- we can't change their // Prefs that have both a default and a user value -- we can't change their
// type. // type.
defaultBranch.setBoolPref("TypeTest.both.bool", true); defaultBranch.setBoolPref("TypeTest.both.bool", true);
userBranch.setBoolPref("TypeTest.both.bool", false); userBranch.setBoolPref("TypeTest.both.bool", false);
defaultBranch.setIntPref("TypeTest.both.int", 25); defaultBranch.setIntPref("TypeTest.both.int", 25);
userBranch.setIntPref("TypeTest.both.int", 26); userBranch.setIntPref("TypeTest.both.int", 26);
defaultBranch.setCharPref("TypeTest.both.char", "yo"); defaultBranch.setCharPref("TypeTest.both.char", "yo");
userBranch.setCharPref("TypeTest.both.char", "ya"); userBranch.setCharPref("TypeTest.both.char", "ya");
Assert.equal(userBranch.getBoolPref("TypeTest.both.bool"), false); Assert.equal(userBranch.getBoolPref("TypeTest.both.bool"), false);
Assert.equal(userBranch.getIntPref("TypeTest.both.int"), 26); Assert.equal(userBranch.getIntPref("TypeTest.both.int"), 26);
@ -52,47 +50,65 @@ function run_test() {
// We only have a default value, and we try to set a default value of a // We only have a default value, and we try to set a default value of a
// different type --> fails. // different type --> fails.
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.default.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.default.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.default.bool", 5); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.default.bool", 5);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.default.int", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.default.int", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.default.int", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.default.int", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.default.char", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.default.char", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.default.char", 6); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.default.char", 6);
}, Cr.NS_ERROR_UNEXPECTED);
// We only have a default value, and we try to set a user value of a // We only have a default value, and we try to set a user value of a
// different type --> fails. // different type --> fails.
do_check_throws(function() { do_check_throws(function() {
userBranch.setCharPref("TypeTest.default.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setCharPref("TypeTest.default.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setIntPref("TypeTest.default.bool", 5); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setIntPref("TypeTest.default.bool", 5);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setCharPref("TypeTest.default.int", "boo"); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setCharPref("TypeTest.default.int", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setBoolPref("TypeTest.default.int", true); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setBoolPref("TypeTest.default.int", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setBoolPref("TypeTest.default.char", true); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setBoolPref("TypeTest.default.char", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setIntPref("TypeTest.default.char", 6); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setIntPref("TypeTest.default.char", 6);
}, Cr.NS_ERROR_UNEXPECTED);
// We only have a user value, and we try to set a default value of a // We only have a user value, and we try to set a default value of a
// different type --> fails. // different type --> fails.
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.user.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.user.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.user.bool", 5); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.user.bool", 5);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.user.int", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.user.int", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.user.int", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.user.int", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.user.char", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.user.char", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.user.char", 6); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.user.char", 6);
}, Cr.NS_ERROR_UNEXPECTED);
// We only have a user value, and we try to set a user value of a // We only have a user value, and we try to set a user value of a
// different type --> SUCCEEDS. // different type --> SUCCEEDS.
@ -112,30 +128,42 @@ function run_test() {
// We have both a default value and user value, and we try to set a default // We have both a default value and user value, and we try to set a default
// value of a different type --> fails. // value of a different type --> fails.
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.both.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.both.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.both.bool", 5); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.both.bool", 5);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setCharPref("TypeTest.both.int", "boo"); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setCharPref("TypeTest.both.int", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.both.int", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.both.int", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setBoolPref("TypeTest.both.char", true); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setBoolPref("TypeTest.both.char", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
defaultBranch.setIntPref("TypeTest.both.char", 6); }, Cr.NS_ERROR_UNEXPECTED); defaultBranch.setIntPref("TypeTest.both.char", 6);
}, Cr.NS_ERROR_UNEXPECTED);
// We have both a default value and user value, and we try to set a user // We have both a default value and user value, and we try to set a user
// value of a different type --> fails. // value of a different type --> fails.
do_check_throws(function() { do_check_throws(function() {
userBranch.setCharPref("TypeTest.both.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setCharPref("TypeTest.both.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setIntPref("TypeTest.both.bool", 5); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setIntPref("TypeTest.both.bool", 5);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setCharPref("TypeTest.both.int", "boo"); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setCharPref("TypeTest.both.int", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setBoolPref("TypeTest.both.int", true); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setBoolPref("TypeTest.both.int", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setBoolPref("TypeTest.both.char", true); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setBoolPref("TypeTest.both.char", true);
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
userBranch.setIntPref("TypeTest.both.char", 6); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setIntPref("TypeTest.both.char", 6);
}, Cr.NS_ERROR_UNEXPECTED);
} }

View file

@ -5,10 +5,7 @@
/* Tests for providing a default value to get{Bool,Char,Float,Int}Pref */ /* Tests for providing a default value to get{Bool,Char,Float,Int}Pref */
function run_test() { function run_test() {
var ps = Cc["@mozilla.org/preferences-service;1"] const ps = Services.prefs;
.getService(Ci.nsIPrefService)
.QueryInterface(Ci.nsIPrefBranch);
let prefName = "test.default.values.bool"; let prefName = "test.default.values.bool";
do_check_throws(function() { ps.getBoolPref(prefName); }, do_check_throws(function() { ps.getBoolPref(prefName); },
Cr.NS_ERROR_UNEXPECTED); Cr.NS_ERROR_UNEXPECTED);

View file

@ -10,9 +10,7 @@ const PREF_INT = 64;
const PREF_STRING = 32; const PREF_STRING = 32;
function run_test() { function run_test() {
const ps = Services.prefs;
var ps = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
let defaultBranch = ps.getDefaultBranch(""); let defaultBranch = ps.getDefaultBranch("");
let userBranch = ps.getBranch(""); let userBranch = ps.getBranch("");
@ -20,7 +18,7 @@ function run_test() {
let prefFile = do_get_profile(); let prefFile = do_get_profile();
prefFile.append("prefs.js"); prefFile.append("prefs.js");
//**************************************************************************// //* *************************************************************************//
// prefs are not dirty after a write // prefs are not dirty after a write
ps.savePrefFile(null); ps.savePrefFile(null);
Assert.ok(!ps.dirty); Assert.ok(!ps.dirty);
@ -58,7 +56,8 @@ function run_test() {
Assert.ok(!ps.dirty); Assert.ok(!ps.dirty);
// Fail to change type of a pref with default value -> not dirty // Fail to change type of a pref with default value -> not dirty
do_check_throws(function() { do_check_throws(function() {
userBranch.setCharPref("DirtyTest.existing.bool", "boo"); }, Cr.NS_ERROR_UNEXPECTED); userBranch.setCharPref("DirtyTest.existing.bool", "boo");
}, Cr.NS_ERROR_UNEXPECTED);
Assert.ok(!ps.dirty); Assert.ok(!ps.dirty);
// Set user value same as default, not dirty // Set user value same as default, not dirty

View file

@ -9,153 +9,163 @@ const PREF_STRING = 32;
const MAX_PREF_LENGTH = 1 * 1024 * 1024; const MAX_PREF_LENGTH = 1 * 1024 * 1024;
function makeList(a) function makeList(a) {
{
var o = {}; var o = {};
for(var i=0; i<a.length; i++) for (var i = 0; i < a.length; i++) {
{ o[a[i]] = "";
o[a[i]] = '';
} }
return o; return o;
} }
function run_test() { function run_test() {
const ps = Services.prefs;
var ps = Cc["@mozilla.org/preferences-service;1"]. //* *************************************************************************//
getService(Ci.nsIPrefService);
var pb2= Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
var pb = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefBranch);
//**************************************************************************//
// Nullsafety // Nullsafety
do_check_throws(function() { do_check_throws(function() {
pb.getPrefType(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getPrefType(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.getBoolPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getBoolPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.setBoolPref(null, false); }, Cr.NS_ERROR_INVALID_ARG); ps.setBoolPref(null, false);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.getIntPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getIntPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.setIntPref(null, 0); }, Cr.NS_ERROR_INVALID_ARG); ps.setIntPref(null, 0);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.getCharPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getCharPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.setCharPref(null, null); }, Cr.NS_ERROR_INVALID_ARG); ps.setCharPref(null, null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.getStringPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getStringPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.setStringPref(null, null); }, Cr.NS_ERROR_INVALID_ARG); ps.setStringPref(null, null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.clearUserPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.clearUserPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.prefHasUserValue(null); }, Cr.NS_ERROR_INVALID_ARG); ps.prefHasUserValue(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.lockPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.lockPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.prefIsLocked(null); }, Cr.NS_ERROR_INVALID_ARG); ps.prefIsLocked(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.unlockPref(null); }, Cr.NS_ERROR_INVALID_ARG); ps.unlockPref(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.deleteBranch(null); }, Cr.NS_ERROR_INVALID_ARG); ps.deleteBranch(null);
}, Cr.NS_ERROR_INVALID_ARG);
do_check_throws(function() { do_check_throws(function() {
pb.getChildList(null); }, Cr.NS_ERROR_INVALID_ARG); ps.getChildList(null);
}, Cr.NS_ERROR_INVALID_ARG);
//**************************************************************************// //* *************************************************************************//
// Nonexisting user preferences // Nonexisting user preferences
Assert.equal(pb.prefHasUserValue("UserPref.nonexistent.hasUserValue"), false); Assert.equal(ps.prefHasUserValue("UserPref.nonexistent.hasUserValue"), false);
pb.clearUserPref("UserPref.nonexistent.clearUserPref"); // shouldn't throw ps.clearUserPref("UserPref.nonexistent.clearUserPref"); // shouldn't throw
Assert.equal(pb.getPrefType("UserPref.nonexistent.getPrefType"), PREF_INVALID); Assert.equal(ps.getPrefType("UserPref.nonexistent.getPrefType"), PREF_INVALID);
Assert.equal(pb.root, ""); Assert.equal(ps.root, "");
// bool... // bool...
do_check_throws(function() { do_check_throws(function() {
pb.getBoolPref("UserPref.nonexistent.getBoolPref");}, Cr.NS_ERROR_UNEXPECTED); ps.getBoolPref("UserPref.nonexistent.getBoolPref");
pb.setBoolPref("UserPref.nonexistent.setBoolPref", false); }, Cr.NS_ERROR_UNEXPECTED);
Assert.equal(pb.getBoolPref("UserPref.nonexistent.setBoolPref"), false); ps.setBoolPref("UserPref.nonexistent.setBoolPref", false);
Assert.equal(ps.getBoolPref("UserPref.nonexistent.setBoolPref"), false);
// int... // int...
do_check_throws(function() { do_check_throws(function() {
pb.getIntPref("UserPref.nonexistent.getIntPref");}, Cr.NS_ERROR_UNEXPECTED); ps.getIntPref("UserPref.nonexistent.getIntPref");
pb.setIntPref("UserPref.nonexistent.setIntPref", 5); }, Cr.NS_ERROR_UNEXPECTED);
Assert.equal(pb.getIntPref("UserPref.nonexistent.setIntPref"), 5); ps.setIntPref("UserPref.nonexistent.setIntPref", 5);
Assert.equal(ps.getIntPref("UserPref.nonexistent.setIntPref"), 5);
// char // char
do_check_throws(function() { do_check_throws(function() {
pb.getCharPref("UserPref.nonexistent.getCharPref");}, Cr.NS_ERROR_UNEXPECTED); ps.getCharPref("UserPref.nonexistent.getCharPref");
pb.setCharPref("UserPref.nonexistent.setCharPref", "_test"); }, Cr.NS_ERROR_UNEXPECTED);
Assert.equal(pb.getCharPref("UserPref.nonexistent.setCharPref"), "_test"); ps.setCharPref("UserPref.nonexistent.setCharPref", "_test");
Assert.equal(ps.getCharPref("UserPref.nonexistent.setCharPref"), "_test");
//**************************************************************************// //* *************************************************************************//
// Existing user Prefs and data integrity test (round-trip match) // Existing user Prefs and data integrity test (round-trip match)
pb.setBoolPref("UserPref.existing.bool", true); ps.setBoolPref("UserPref.existing.bool", true);
pb.setIntPref("UserPref.existing.int", 23); ps.setIntPref("UserPref.existing.int", 23);
pb.setCharPref("UserPref.existing.char", "hey"); ps.setCharPref("UserPref.existing.char", "hey");
// getPref should return the pref value // getPref should return the pref value
Assert.equal(pb.getBoolPref("UserPref.existing.bool"), true); Assert.equal(ps.getBoolPref("UserPref.existing.bool"), true);
Assert.equal(pb.getIntPref("UserPref.existing.int"), 23); Assert.equal(ps.getIntPref("UserPref.existing.int"), 23);
Assert.equal(pb.getCharPref("UserPref.existing.char"), "hey"); Assert.equal(ps.getCharPref("UserPref.existing.char"), "hey");
// setPref should not complain and should change the value of the pref // setPref should not complain and should change the value of the pref
pb.setBoolPref("UserPref.existing.bool", false); ps.setBoolPref("UserPref.existing.bool", false);
Assert.equal(pb.getBoolPref("UserPref.existing.bool"), false); Assert.equal(ps.getBoolPref("UserPref.existing.bool"), false);
pb.setIntPref("UserPref.existing.int", 24); ps.setIntPref("UserPref.existing.int", 24);
Assert.equal(pb.getIntPref("UserPref.existing.int"), 24); Assert.equal(ps.getIntPref("UserPref.existing.int"), 24);
pb.setCharPref("UserPref.existing.char", "hej då!"); ps.setCharPref("UserPref.existing.char", "hej då!");
Assert.equal(pb.getCharPref("UserPref.existing.char"), "hej då!"); Assert.equal(ps.getCharPref("UserPref.existing.char"), "hej då!");
// prefHasUserValue should return true now // prefHasUserValue should return true now
Assert.ok(pb.prefHasUserValue("UserPref.existing.bool")); Assert.ok(ps.prefHasUserValue("UserPref.existing.bool"));
Assert.ok(pb.prefHasUserValue("UserPref.existing.int")); Assert.ok(ps.prefHasUserValue("UserPref.existing.int"));
Assert.ok(pb.prefHasUserValue("UserPref.existing.char")); Assert.ok(ps.prefHasUserValue("UserPref.existing.char"));
// clearUserPref should remove the pref // clearUserPref should remove the pref
pb.clearUserPref("UserPref.existing.bool"); ps.clearUserPref("UserPref.existing.bool");
Assert.ok(!pb.prefHasUserValue("UserPref.existing.bool")); Assert.ok(!ps.prefHasUserValue("UserPref.existing.bool"));
pb.clearUserPref("UserPref.existing.int"); ps.clearUserPref("UserPref.existing.int");
Assert.ok(!pb.prefHasUserValue("UserPref.existing.int")); Assert.ok(!ps.prefHasUserValue("UserPref.existing.int"));
pb.clearUserPref("UserPref.existing.char"); ps.clearUserPref("UserPref.existing.char");
Assert.ok(!pb.prefHasUserValue("UserPref.existing.char")); Assert.ok(!ps.prefHasUserValue("UserPref.existing.char"));
//**************************************************************************// //* *************************************************************************//
// Large value test // Large value test
let largeStr = new Array(MAX_PREF_LENGTH + 1).join('x'); let largeStr = new Array(MAX_PREF_LENGTH + 1).join("x");
pb.setCharPref("UserPref.large.char", largeStr); ps.setCharPref("UserPref.large.char", largeStr);
largeStr += 'x'; largeStr += "x";
do_check_throws(function() { do_check_throws(function() {
pb.setCharPref("UserPref.large.char", largeStr); }, Cr.NS_ERROR_ILLEGAL_VALUE); ps.setCharPref("UserPref.large.char", largeStr);
}, Cr.NS_ERROR_ILLEGAL_VALUE);
//**************************************************************************// //* *************************************************************************//
// getPrefType test // getPrefType test
// bool... // bool...
pb.setBoolPref("UserPref.getPrefType.bool", true); ps.setBoolPref("UserPref.getPrefType.bool", true);
Assert.equal(pb.getPrefType("UserPref.getPrefType.bool"), PREF_BOOL); Assert.equal(ps.getPrefType("UserPref.getPrefType.bool"), PREF_BOOL);
// int... // int...
pb.setIntPref("UserPref.getPrefType.int", -234); ps.setIntPref("UserPref.getPrefType.int", -234);
Assert.equal(pb.getPrefType("UserPref.getPrefType.int"), PREF_INT); Assert.equal(ps.getPrefType("UserPref.getPrefType.int"), PREF_INT);
// char... // char...
pb.setCharPref("UserPref.getPrefType.char", "testing1..2"); ps.setCharPref("UserPref.getPrefType.char", "testing1..2");
Assert.equal(pb.getPrefType("UserPref.getPrefType.char"), PREF_STRING); Assert.equal(ps.getPrefType("UserPref.getPrefType.char"), PREF_STRING);
//**************************************************************************// //* *************************************************************************//
// getBranch tests // getBranch tests
Assert.equal(ps.root, ""); Assert.equal(ps.root, "");
// bool ... // bool ...
pb.setBoolPref("UserPref.root.boolPref", true); ps.setBoolPref("UserPref.root.boolPref", true);
let pb_1 = ps.getBranch("UserPref.root."); let pb_1 = ps.getBranch("UserPref.root.");
Assert.equal(pb_1.getBoolPref("boolPref"), true); Assert.equal(pb_1.getBoolPref("boolPref"), true);
let pb_2 = ps.getBranch("UserPref.root.boolPref"); let pb_2 = ps.getBranch("UserPref.root.boolPref");
@ -165,7 +175,7 @@ function run_test() {
Assert.equal(pb_3.getBoolPref("f.anotherPref"), false); Assert.equal(pb_3.getBoolPref("f.anotherPref"), false);
// int ... // int ...
pb.setIntPref("UserPref.root.intPref", 23); ps.setIntPref("UserPref.root.intPref", 23);
pb_1 = ps.getBranch("UserPref.root."); pb_1 = ps.getBranch("UserPref.root.");
Assert.equal(pb_1.getIntPref("intPref"), 23); Assert.equal(pb_1.getIntPref("intPref"), 23);
pb_2 = ps.getBranch("UserPref.root.intPref"); pb_2 = ps.getBranch("UserPref.root.intPref");
@ -175,7 +185,7 @@ function run_test() {
Assert.equal(pb_3.getIntPref("f.anotherPref"), 69); Assert.equal(pb_3.getIntPref("f.anotherPref"), 69);
// char... // char...
pb.setCharPref("UserPref.root.charPref", "_char"); ps.setCharPref("UserPref.root.charPref", "_char");
pb_1 = ps.getBranch("UserPref.root."); pb_1 = ps.getBranch("UserPref.root.");
Assert.equal(pb_1.getCharPref("charPref"), "_char"); Assert.equal(pb_1.getCharPref("charPref"), "_char");
pb_2 = ps.getBranch("UserPref.root.charPref"); pb_2 = ps.getBranch("UserPref.root.charPref");
@ -184,11 +194,11 @@ function run_test() {
pb_3 = ps.getBranch("UserPref.root.charPre"); pb_3 = ps.getBranch("UserPref.root.charPre");
Assert.equal(pb_3.getCharPref("f.anotherPref"), "_another"); Assert.equal(pb_3.getCharPref("f.anotherPref"), "_another");
//**************************************************************************// //* *************************************************************************//
// getChildlist tests // getChildlist tests
// get an already set prefBranch // get an already set prefBranch
pb1 = ps.getBranch("UserPref.root."); let pb1 = ps.getBranch("UserPref.root.");
let prefList = pb1.getChildList(""); let prefList = pb1.getChildList("");
Assert.equal(prefList.length, 6); Assert.equal(prefList.length, 6);
@ -200,54 +210,56 @@ function run_test() {
Assert.ok("intPref.anotherPref" in makeList(prefList)); Assert.ok("intPref.anotherPref" in makeList(prefList));
Assert.ok("charPref.anotherPref" in makeList(prefList)); Assert.ok("charPref.anotherPref" in makeList(prefList));
//**************************************************************************// //* *************************************************************************//
// Default branch tests // Default branch tests
// bool... // bool...
pb1 = ps.getDefaultBranch(""); pb1 = ps.getDefaultBranch("");
pb1.setBoolPref("DefaultPref.bool", true); pb1.setBoolPref("DefaultPref.bool", true);
Assert.equal(pb1.getBoolPref("DefaultPref.bool"), true); Assert.equal(pb1.getBoolPref("DefaultPref.bool"), true);
Assert.ok(!pb1.prefHasUserValue("DefaultPref.bool")); Assert.ok(!pb1.prefHasUserValue("DefaultPref.bool"));
ps.setBoolPref("DefaultPref.bool", false); ps.setBoolPref("DefaultPref.bool", false);
Assert.ok(pb1.prefHasUserValue("DefaultPref.bool")); Assert.ok(pb1.prefHasUserValue("DefaultPref.bool"));
Assert.equal(ps.getBoolPref("DefaultPref.bool"), false); Assert.equal(ps.getBoolPref("DefaultPref.bool"), false);
// int... // int...
pb1 = ps.getDefaultBranch(""); pb1 = ps.getDefaultBranch("");
pb1.setIntPref("DefaultPref.int", 100); pb1.setIntPref("DefaultPref.int", 100);
Assert.equal(pb1.getIntPref("DefaultPref.int"), 100); Assert.equal(pb1.getIntPref("DefaultPref.int"), 100);
Assert.ok(!pb1.prefHasUserValue("DefaultPref.int")); Assert.ok(!pb1.prefHasUserValue("DefaultPref.int"));
ps.setIntPref("DefaultPref.int", 50); ps.setIntPref("DefaultPref.int", 50);
Assert.ok(pb1.prefHasUserValue("DefaultPref.int")); Assert.ok(pb1.prefHasUserValue("DefaultPref.int"));
Assert.equal(ps.getIntPref("DefaultPref.int"), 50); Assert.equal(ps.getIntPref("DefaultPref.int"), 50);
// char... // char...
pb1 = ps.getDefaultBranch(""); pb1 = ps.getDefaultBranch("");
pb1.setCharPref("DefaultPref.char", "_default"); pb1.setCharPref("DefaultPref.char", "_default");
Assert.equal(pb1.getCharPref("DefaultPref.char"), "_default"); Assert.equal(pb1.getCharPref("DefaultPref.char"), "_default");
Assert.ok(!pb1.prefHasUserValue("DefaultPref.char")); Assert.ok(!pb1.prefHasUserValue("DefaultPref.char"));
ps.setCharPref("DefaultPref.char", "_user"); ps.setCharPref("DefaultPref.char", "_user");
Assert.ok(pb1.prefHasUserValue("DefaultPref.char")); Assert.ok(pb1.prefHasUserValue("DefaultPref.char"));
Assert.equal(ps.getCharPref("DefaultPref.char"), "_user"); Assert.equal(ps.getCharPref("DefaultPref.char"), "_user");
//**************************************************************************// //* *************************************************************************//
// pref Locking/Unlocking tests // pref Locking/Unlocking tests
// locking and unlocking a nonexistent pref should throw // locking and unlocking a nonexistent pref should throw
do_check_throws(function() { do_check_throws(function() {
ps.lockPref("DefaultPref.nonexistent");}, Cr.NS_ERROR_ILLEGAL_VALUE); ps.lockPref("DefaultPref.nonexistent");
}, Cr.NS_ERROR_ILLEGAL_VALUE);
do_check_throws(function() { do_check_throws(function() {
ps.unlockPref("DefaultPref.nonexistent");}, Cr.NS_ERROR_ILLEGAL_VALUE); ps.unlockPref("DefaultPref.nonexistent");
}, Cr.NS_ERROR_ILLEGAL_VALUE);
// getting a locked pref branch should return the "default" value // getting a locked pref branch should return the "default" value
Assert.ok(!ps.prefIsLocked("DefaultPref.char")); Assert.ok(!ps.prefIsLocked("DefaultPref.char"));
ps.lockPref("DefaultPref.char"); ps.lockPref("DefaultPref.char");
Assert.equal(ps.getCharPref("DefaultPref.char"), "_default"); Assert.equal(ps.getCharPref("DefaultPref.char"), "_default");
Assert.ok(ps.prefIsLocked("DefaultPref.char")); Assert.ok(ps.prefIsLocked("DefaultPref.char"));
// getting an unlocked pref branch should return the "user" value // getting an unlocked pref branch should return the "user" value
ps.unlockPref("DefaultPref.char"); ps.unlockPref("DefaultPref.char");
Assert.equal(ps.getCharPref("DefaultPref.char"), "_user"); Assert.equal(ps.getCharPref("DefaultPref.char"), "_user");
Assert.ok(!ps.prefIsLocked("DefaultPref.char")); Assert.ok(!ps.prefIsLocked("DefaultPref.char"));
// setting the "default" value to a user pref branch should // setting the "default" value to a user pref branch should
@ -260,17 +272,17 @@ function run_test() {
ps.lockPref("DefaultPref.char"); ps.lockPref("DefaultPref.char");
ps.lockPref("DefaultPref.char"); ps.lockPref("DefaultPref.char");
//**************************************************************************// //* *************************************************************************//
// resetBranch test // resetBranch test
// NOT IMPLEMENTED YET in module/libpref. So we're not testing ! // NOT IMPLEMENTED YET in module/libpref. So we're not testing !
// uncomment the following if resetBranch ever gets implemented. // uncomment the following if resetBranch ever gets implemented.
/*ps.resetBranch("DefaultPref"); /* ps.resetBranch("DefaultPref");
do_check_eq(ps.getBoolPref("DefaultPref.bool"), true); do_check_eq(ps.getBoolPref("DefaultPref.bool"), true);
do_check_eq(ps.getIntPref("DefaultPref.int"), 100); do_check_eq(ps.getIntPref("DefaultPref.int"), 100);
do_check_eq(ps.getCharPref("DefaultPref.char"), "_default");*/ do_check_eq(ps.getCharPref("DefaultPref.char"), "_default");*/
//**************************************************************************// //* *************************************************************************//
// deleteBranch tests // deleteBranch tests
// TODO : Really, this should throw!, by documentation. // TODO : Really, this should throw!, by documentation.
@ -278,26 +290,32 @@ function run_test() {
// ps.deleteBranch("UserPref.nonexistent.deleteBranch");}, Cr.NS_ERROR_UNEXPECTED); // ps.deleteBranch("UserPref.nonexistent.deleteBranch");}, Cr.NS_ERROR_UNEXPECTED);
ps.deleteBranch("DefaultPref"); ps.deleteBranch("DefaultPref");
pb = ps.getBranch("DefaultPref"); let pb = ps.getBranch("DefaultPref");
pb1 = ps.getDefaultBranch("DefaultPref"); pb1 = ps.getDefaultBranch("DefaultPref");
// getting prefs on deleted user branches should throw // getting prefs on deleted user branches should throw
do_check_throws(function() { do_check_throws(function() {
pb.getBoolPref("DefaultPref.bool");}, Cr.NS_ERROR_UNEXPECTED); pb.getBoolPref("DefaultPref.bool");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb.getIntPref("DefaultPref.int");}, Cr.NS_ERROR_UNEXPECTED); pb.getIntPref("DefaultPref.int");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb.getCharPref("DefaultPref.char");}, Cr.NS_ERROR_UNEXPECTED); pb.getCharPref("DefaultPref.char");
}, Cr.NS_ERROR_UNEXPECTED);
// getting prefs on deleted default branches should throw // getting prefs on deleted default branches should throw
do_check_throws(function() { do_check_throws(function() {
pb1.getBoolPref("DefaultPref.bool");}, Cr.NS_ERROR_UNEXPECTED); pb1.getBoolPref("DefaultPref.bool");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb1.getIntPref("DefaultPref.int");}, Cr.NS_ERROR_UNEXPECTED); pb1.getIntPref("DefaultPref.int");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb1.getCharPref("DefaultPref.char");}, Cr.NS_ERROR_UNEXPECTED); pb1.getCharPref("DefaultPref.char");
}, Cr.NS_ERROR_UNEXPECTED);
//**************************************************************************// //* *************************************************************************//
// savePrefFile & readPrefFile tests // savePrefFile & readPrefFile tests
// set some prefs // set some prefs
@ -322,11 +340,14 @@ function run_test() {
// former prefs should have been replaced/lost // former prefs should have been replaced/lost
do_check_throws(function() { do_check_throws(function() {
pb.getBoolPref("ReadPref.bool");}, Cr.NS_ERROR_UNEXPECTED); pb.getBoolPref("ReadPref.bool");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb.getIntPref("ReadPref.int");}, Cr.NS_ERROR_UNEXPECTED); pb.getIntPref("ReadPref.int");
}, Cr.NS_ERROR_UNEXPECTED);
do_check_throws(function() { do_check_throws(function() {
pb.getCharPref("ReadPref.char");}, Cr.NS_ERROR_UNEXPECTED); pb.getCharPref("ReadPref.char");
}, Cr.NS_ERROR_UNEXPECTED);
// loaded prefs should read ok. // loaded prefs should read ok.
pb = ps.getBranch("testPref."); pb = ps.getBranch("testPref.");
@ -355,7 +376,7 @@ function run_test() {
Assert.equal(pb.getBoolPref("bool2"), false); Assert.equal(pb.getBoolPref("bool2"), false);
Assert.equal(pb.getIntPref("int1"), 23); Assert.equal(pb.getIntPref("int1"), 23);
//**************************************************************************// //* *************************************************************************//
// preference Observers // preference Observers
class PrefObserver { class PrefObserver {
@ -377,7 +398,7 @@ function run_test() {
QueryInterface(aIID) { QueryInterface(aIID) {
if (aIID.equals(Ci.nsIObserver) || if (aIID.equals(Ci.nsIObserver) ||
aIID.equals(Ci.nsISupports)) aIID.equals(Ci.nsISupports))
return this; return this;
throw Cr.NS_NOINTERFACE; throw Cr.NS_NOINTERFACE;
} }
@ -390,7 +411,7 @@ function run_test() {
// notification received, we may go on... // notification received, we may go on...
do_test_finished(); do_test_finished();
} }
}; }
// Indicate that we'll have 3 more async tests pending so that they all // Indicate that we'll have 3 more async tests pending so that they all
// actually get a chance to run. // actually get a chance to run.
@ -398,15 +419,15 @@ function run_test() {
do_test_pending(); do_test_pending();
do_test_pending(); do_test_pending();
let observer = new PrefObserver(pb2, "ReadPref.int", 76); let observer = new PrefObserver(ps, "ReadPref.int", 76);
ps.setIntPref("ReadPref.int", 76); ps.setIntPref("ReadPref.int", 76);
// removed observer should not fire // removed observer should not fire
pb2.removeObserver("ReadPref.int", observer); ps.removeObserver("ReadPref.int", observer);
ps.setIntPref("ReadPref.int", 32); ps.setIntPref("ReadPref.int", 32);
// let's test observers once more with a non-root prefbranch // let's test observers once more with a non-root prefbranch
pb = pb2.getBranch("ReadPref."); pb = ps.getBranch("ReadPref.");
observer = new PrefObserver(pb, "int", 76); observer = new PrefObserver(pb, "int", 76);
ps.setIntPref("ReadPref.int", 76); ps.setIntPref("ReadPref.int", 76);

View file

@ -3,9 +3,6 @@
// This file tests the `locked` attribute in default pref files. // This file tests the `locked` attribute in default pref files.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
const ps = Services.prefs; const ps = Services.prefs;
add_test(function notChangedFromAPI() { add_test(function notChangedFromAPI() {

View file

@ -2,15 +2,10 @@
* http://creativecommons.org/licenses/publicdomain/ */ * http://creativecommons.org/licenses/publicdomain/ */
function run_test() { function run_test() {
const PREF_NAME = "testPref"; const ps = Services.prefs;
var ps = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService);
var defaultPrefs = ps.getDefaultBranch(null);
var prefs = ps.getBranch(null);
ps.resetPrefs(); ps.resetPrefs();
ps.readDefaultPrefsFromFile(do_get_file('data/testParser.js')); ps.readDefaultPrefsFromFile(do_get_file("data/testParser.js"));
Assert.equal(ps.getBoolPref("comment1"), true); Assert.equal(ps.getBoolPref("comment1"), true);
Assert.equal(ps.getBoolPref("comment2"), true); Assert.equal(ps.getBoolPref("comment2"), true);
@ -35,7 +30,7 @@ function run_test() {
Assert.equal(ps.getIntPref("int.+ 345"), 345); Assert.equal(ps.getIntPref("int.+ 345"), 345);
Assert.equal(ps.getIntPref("int.-0"), -0); Assert.equal(ps.getIntPref("int.-0"), -0);
Assert.equal(ps.getIntPref("int.-1"), -1); Assert.equal(ps.getIntPref("int.-1"), -1);
Assert.equal(ps.getIntPref("int.- /* hmm */ 456"), -456); Assert.equal(ps.getIntPref("int.- /* hmm */\t456"), -456);
Assert.equal(ps.getIntPref("int.-\n567"), -567); Assert.equal(ps.getIntPref("int.-\n567"), -567);
Assert.equal(ps.getIntPref("int.INT_MAX-1"), 2147483646); Assert.equal(ps.getIntPref("int.INT_MAX-1"), 2147483646);
Assert.equal(ps.getIntPref("int.INT_MAX"), 2147483647); Assert.equal(ps.getIntPref("int.INT_MAX"), 2147483647);
@ -46,10 +41,10 @@ function run_test() {
Assert.equal(ps.getCharPref("string.empty"), ""); Assert.equal(ps.getCharPref("string.empty"), "");
Assert.equal(ps.getCharPref("string.abc"), "abc"); Assert.equal(ps.getCharPref("string.abc"), "abc");
Assert.equal(ps.getCharPref("string.long"), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); Assert.equal(ps.getCharPref("string.long"), "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Assert.equal(ps.getCharPref('string.single-quotes'), '"abc"'); Assert.equal(ps.getCharPref("string.single-quotes"), '"abc"');
Assert.equal(ps.getCharPref("string.double-quotes"), "'abc'"); Assert.equal(ps.getCharPref("string.double-quotes"), "'abc'");
Assert.equal(ps.getCharPref("string.weird-chars"), Assert.equal(ps.getCharPref("string.weird-chars"),
"\x0d \x09 \x0b \x0c \x06 \x16"); "\x0d \x09 \x0b \x0c \x06 \x16");
Assert.equal(ps.getCharPref("string.escapes"), "\" \' \\ \n \r"); Assert.equal(ps.getCharPref("string.escapes"), "\" \' \\ \n \r");
// This one is ASCII, so we can use getCharPref() and getStringPref // This one is ASCII, so we can use getCharPref() and getStringPref

View file

@ -1,8 +1,6 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/ */ * http://creativecommons.org/licenses/publicdomain/ */
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const ps = Services.prefs; const ps = Services.prefs;
// A little helper to reset the service and load one pref file. // A little helper to reset the service and load one pref file.
@ -37,10 +35,6 @@ function saveAndReload() {
ps.readUserPrefsFromFile(file); ps.readUserPrefsFromFile(file);
} }
function run_test() {
run_next_test();
}
// A sticky pref should not be written if the value is unchanged. // A sticky pref should not be written if the value is unchanged.
add_test(function notWrittenWhenUnchanged() { add_test(function notWrittenWhenUnchanged() {
resetAndLoadDefaults(); resetAndLoadDefaults();

View file

@ -2,14 +2,8 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var cs = Cc["@mozilla.org/consoleservice;1"].
getService(Ci.nsIConsoleService);
var ps = Cc["@mozilla.org/preferences-service;1"].
getService(Ci.nsIPrefService);
function makeBuffer(length) { function makeBuffer(length) {
return new Array(length + 1).join('x'); return new Array(length + 1).join("x");
} }
/** /**
@ -20,7 +14,7 @@ function checkWarning(pref, buffer) {
return new Promise(resolve => { return new Promise(resolve => {
let complete = false; let complete = false;
let listener = { let listener = {
observe: function(event) { observe(event) {
let message = event.message; let message = event.message;
if (!(message.startsWith("Warning: attempting to write") if (!(message.startsWith("Warning: attempting to write")
&& message.includes(pref))) { && message.includes(pref))) {
@ -31,9 +25,9 @@ function checkWarning(pref, buffer) {
} }
complete = true; complete = true;
info("Warning while setting " + pref); info("Warning while setting " + pref);
cs.unregisterListener(listener); Services.console.unregisterListener(listener);
resolve(true); resolve(true);
} },
}; };
do_timeout(1000, function() { do_timeout(1000, function() {
if (complete) { if (complete) {
@ -41,18 +35,14 @@ function checkWarning(pref, buffer) {
} }
complete = true; complete = true;
info("No warning while setting " + pref); info("No warning while setting " + pref);
cs.unregisterListener(listener); Services.console.unregisterListener(listener);
resolve(false); resolve(false);
}); });
cs.registerListener(listener); Services.console.registerListener(listener);
ps.setCharPref(pref, buffer); Services.prefs.setCharPref(pref, buffer);
}); });
} }
function run_test() {
run_next_test();
}
add_task(async function() { add_task(async function() {
// Simple change, shouldn't cause a warning // Simple change, shouldn't cause a warning
info("Checking that a simple change doesn't cause a warning"); info("Checking that a simple change doesn't cause a warning");

View file

@ -1,18 +1,19 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; let appInfo = Cc["@mozilla.org/xre/app-info;1"];
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT); return (!appInfo || Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function run_test() { function run_test() {
if (isParentProcess() == false) { if (!isParentProcess()) {
do_load_child_test_harness(); do_load_child_test_harness();
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); var pb = Services.prefs;
pb.setBoolPref("Test.IPC.bool.new", true); pb.setBoolPref("Test.IPC.bool.new", true);
pb.setIntPref("Test.IPC.int.new", 23); pb.setIntPref("Test.IPC.int.new", 23);
pb.setCharPref("Test.IPC.char.new", "hey"); pb.setCharPref("Test.IPC.char.new", "hey");
run_test_in_child("test_observed_prefs.js"); run_test_in_child("test_observed_prefs.js");
} }
} }

View file

@ -1,15 +1,16 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; return (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function run_test() { function run_test() {
if (isParentProcess() == false) { if (!isParentProcess()) {
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); const pb = Services.prefs;
pb.setBoolPref("Test.IPC.bool", true); pb.setBoolPref("Test.IPC.bool", true);
pb.setIntPref("Test.IPC.int", 23); pb.setIntPref("Test.IPC.int", 23);
pb.setCharPref("Test.IPC.char", "hey"); pb.setCharPref("Test.IPC.char", "hey");
run_test_in_child("test_existing_prefs.js"); run_test_in_child("test_existing_prefs.js");
} }
} }

View file

@ -5,21 +5,22 @@
// Large preferences should not be set in the child process. // Large preferences should not be set in the child process.
// Non-string preferences are not tested here, because their behavior // Non-string preferences are not tested here, because their behavior
// should not be affected by this filtering. // should not be affected by this filtering.
//
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; return (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function makeBuffer(length) { function makeBuffer(length) {
let string = "x"; let string = "x";
while (string.length < length) { while (string.length < length) {
string = string + string; string = string + string;
} }
if (string.length > length) { if (string.length > length) {
string = string.substring(length - string.length); string = string.substring(length - string.length);
} }
return string; return string;
} }
// from prefapi.h // from prefapi.h
@ -46,9 +47,8 @@ function expectedPrefValue(def, user) {
} }
function run_test() { function run_test() {
let pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); const pb = Services.prefs;
let ps = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService); let defaultBranch = pb.getDefaultBranch("");
let defaultBranch = ps.getDefaultBranch("");
let isParent = isParentProcess(); let isParent = isParentProcess();
if (isParent) { if (isParent) {
@ -92,11 +92,11 @@ function run_test() {
try { try {
let val = pb.getCharPref(pref_name); let val = pb.getCharPref(pref_name);
prefExists = val.length > 128; prefExists = val.length > 128;
} catch(e) { } catch (e) {
prefExists = false; prefExists = false;
} }
ok(!prefExists, ok(!prefExists,
"Pref " + pref_name + " should not be set in the child"); "Pref " + pref_name + " should not be set in the child");
} }
} }
} }

View file

@ -4,13 +4,14 @@
// Locked status should be communicated to children. // Locked status should be communicated to children.
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; return (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function run_test() { function run_test() {
let pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); const pb = Services.prefs;
let bprefname = "Test.IPC.locked.bool"; let bprefname = "Test.IPC.locked.bool";
let iprefname = "Test.IPC.locked.int"; let iprefname = "Test.IPC.locked.int";

View file

@ -1,13 +1,14 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; return (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function run_test() { function run_test() {
if (isParentProcess() == false) { if (!isParentProcess()) {
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); const pb = Services.prefs;
Assert.equal(pb.getBoolPref("Test.IPC.bool.new"), true); Assert.equal(pb.getBoolPref("Test.IPC.bool.new"), true);
Assert.equal(pb.getIntPref("Test.IPC.int.new"), 23); Assert.equal(pb.getIntPref("Test.IPC.int.new"), 23);
Assert.equal(pb.getCharPref("Test.IPC.char.new"), "hey"); Assert.equal(pb.getCharPref("Test.IPC.char.new"), "hey");
} }
} }

View file

@ -152,7 +152,6 @@ const PREFS = [
for (let {type, values} of PREFS) { for (let {type, values} of PREFS) {
let set = `set${type}Pref`; let set = `set${type}Pref`;
let get = `get${type}Pref`;
function prefTest(opts) { function prefTest(opts) {
function check(pref, proc, val, {expectedVal, defaultVal = undefined, expectedDefault = defaultVal, expectedFlags = {}}) { function check(pref, proc, val, {expectedVal, defaultVal = undefined, expectedDefault = defaultVal, expectedFlags = {}}) {
@ -179,14 +178,14 @@ for (let {type, values} of PREFS) {
return { return {
beforeContent(PREF) { beforeContent(PREF) {
updatePref(PREF, opts.initial) updatePref(PREF, opts.initial);
check(PREF, "parent", getPref(PREF), opts.initial); check(PREF, "parent", getPref(PREF), opts.initial);
}, },
contentStartup(PREF, contentVal) { contentStartup(PREF, contentVal) {
check(PREF, "content", contentVal, opts.initial); check(PREF, "content", contentVal, opts.initial);
check(PREF, "parent", getPref(PREF), opts.initial); check(PREF, "parent", getPref(PREF), opts.initial);
updatePref(PREF, opts.change1) updatePref(PREF, opts.change1);
check(PREF, "parent", getPref(PREF), opts.change1); check(PREF, "parent", getPref(PREF), opts.change1);
}, },
contentUpdate1(PREF, contentVal) { contentUpdate1(PREF, contentVal) {
@ -194,7 +193,7 @@ for (let {type, values} of PREFS) {
check(PREF, "parent", getPref(PREF), opts.change1); check(PREF, "parent", getPref(PREF), opts.change1);
if (opts.change2) { if (opts.change2) {
updatePref(PREF, opts.change2) updatePref(PREF, opts.change2);
check(PREF, "parent", getPref(PREF), opts.change2); check(PREF, "parent", getPref(PREF), opts.change2);
} }
}, },

View file

@ -22,7 +22,7 @@
const PREF1_NAME = "dom.webcomponents.shadowdom.report_usage"; const PREF1_NAME = "dom.webcomponents.shadowdom.report_usage";
const PREF1_VALUE = false; const PREF1_VALUE = false;
const PREF2_NAME = "dom.mutation-events.cssom.disabled" const PREF2_NAME = "dom.mutation-events.cssom.disabled";
const PREF2_VALUE = true; const PREF2_VALUE = true;
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
@ -30,8 +30,6 @@ const {ExtensionTestUtils} = ChromeUtils.import("resource://testing-common/Exten
ExtensionTestUtils.init(this); ExtensionTestUtils.init(this);
let contentPage;
const {prefs} = Services; const {prefs} = Services;
const defaultPrefs = prefs.getDefaultBranch(""); const defaultPrefs = prefs.getDefaultBranch("");
@ -52,14 +50,15 @@ add_task(async function test_sharedMap_var_caches() {
let contentPage = await ExtensionTestUtils.loadContentPage("about:blank", {remote: true}); let contentPage = await ExtensionTestUtils.loadContentPage("about:blank", {remote: true});
registerCleanupFunction(() => contentPage.close()); registerCleanupFunction(() => contentPage.close());
/* eslint-disable no-shadow */
let values = await contentPage.spawn([PREF1_NAME, PREF2_NAME], (prefs) => { let values = await contentPage.spawn([PREF1_NAME, PREF2_NAME], (prefs) => {
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
return prefs.map(pref => Services.prefs.getBoolPref(pref)); return prefs.map(pref => Services.prefs.getBoolPref(pref));
}) });
/* eslint-enable no-shadow */
equal(values[0], !PREF1_VALUE, equal(values[0], !PREF1_VALUE,
`Expected content value for ${PREF1_NAME}`); `Expected content value for ${PREF1_NAME}`);
equal(values[1], !PREF2_VALUE, equal(values[1], !PREF2_VALUE,
`Expected content value for ${PREF2_NAME}`); `Expected content value for ${PREF2_NAME}`);
}); });

View file

@ -1,14 +1,14 @@
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
function isParentProcess() { function isParentProcess() {
let appInfo = Cc["@mozilla.org/xre/app-info;1"]; return Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT;
return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
} }
function run_test() { function run_test() {
if (isParentProcess()) { if (isParentProcess()) {
do_load_child_test_harness(); do_load_child_test_harness();
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); var pb = Services.prefs;
// these prefs are set after the child has been created. // these prefs are set after the child has been created.
pb.setBoolPref("Test.IPC.bool.new", true); pb.setBoolPref("Test.IPC.bool.new", true);
@ -20,11 +20,11 @@ function run_test() {
} }
function testPrefClear() { function testPrefClear() {
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); var pb = Services.prefs;
pb.clearUserPref("Test.IPC.bool.new"); pb.clearUserPref("Test.IPC.bool.new");
sendCommand( sendCommand(
'var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);\n'+ 'var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);\n' +
'pb.prefHasUserValue("Test.IPC.bool.new");\n', 'pb.prefHasUserValue("Test.IPC.bool.new");\n',
checkWasCleared); checkWasCleared);
} }

View file

@ -1,67 +1,68 @@
var pb = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch); const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const pb = Services.prefs;
// This pref is chosen somewhat arbitrarily --- we just need one // This pref is chosen somewhat arbitrarily --- we just need one
// that's guaranteed to have a default value. // that's guaranteed to have a default value.
const kPrefName = 'intl.accept_languages'; // of type char, which we const kPrefName = "intl.accept_languages"; // of type char, which we
// assume below // assume below
var initialValue = null; var initialValue = null;
function check_child_pref_info_eq(continuation) { function check_child_pref_info_eq(continuation) {
sendCommand( sendCommand(
'var pb = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);\n'+ 'var pb = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);\n' +
// Returns concatenation "[value],[isUser]" // Returns concatenation "[value],[isUser]"
'pb.getCharPref("'+ kPrefName +'")+ "," +'+ 'pb.getCharPref("' + kPrefName + '")+ "," +' +
'pb.prefHasUserValue("'+ kPrefName +'");', 'pb.prefHasUserValue("' + kPrefName + '");',
function (info) { function(info) {
let [ value, isUser ] = info.split(','); let [ value, isUser ] = info.split(",");
Assert.equal(pb.getCharPref(kPrefName), value); Assert.equal(pb.getCharPref(kPrefName), value);
Assert.equal(pb.prefHasUserValue(kPrefName), isUser == "true"); Assert.equal(pb.prefHasUserValue(kPrefName), isUser == "true");
continuation(); continuation();
}); });
} }
function run_test() { function run_test() {
// We finish in clean_up() // We finish in clean_up()
do_test_pending(); do_test_pending();
initialValue = pb.getCharPref(kPrefName); initialValue = pb.getCharPref(kPrefName);
test_user_setting(); test_user_setting();
} }
function test_user_setting() { function test_user_setting() {
// We rely on setting this before the content process starts up. // We rely on setting this before the content process starts up.
// When it starts up, it should recognize this as a user pref, not // When it starts up, it should recognize this as a user pref, not
// a default pref. // a default pref.
pb.setCharPref(kPrefName, 'i-imaginarylanguage'); pb.setCharPref(kPrefName, "i-imaginarylanguage");
// NB: processing of the value-change notification in the child // NB: processing of the value-change notification in the child
// process triggered by the above set happens-before the remaining // process triggered by the above set happens-before the remaining
// code here // code here
check_child_pref_info_eq(function () { check_child_pref_info_eq(function() {
Assert.equal(pb.prefHasUserValue(kPrefName), true); Assert.equal(pb.prefHasUserValue(kPrefName), true);
test_cleared_is_default(); test_cleared_is_default();
}); });
} }
function test_cleared_is_default() { function test_cleared_is_default() {
pb.clearUserPref(kPrefName); pb.clearUserPref(kPrefName);
// NB: processing of the value-change notification in the child // NB: processing of the value-change notification in the child
// process triggered by the above set happens-before the remaining // process triggered by the above set happens-before the remaining
// code here // code here
check_child_pref_info_eq(function () { check_child_pref_info_eq(function() {
Assert.equal(pb.prefHasUserValue(kPrefName), false); Assert.equal(pb.prefHasUserValue(kPrefName), false);
clean_up(); clean_up();
}); });
} }
function clean_up() { function clean_up() {
pb.setCharPref(kPrefName, initialValue); pb.setCharPref(kPrefName, initialValue);
// NB: processing of the value-change notification in the child // NB: processing of the value-change notification in the child
// process triggered by the above set happens-before the remaining // process triggered by the above set happens-before the remaining
// code here // code here
check_child_pref_info_eq(function () { check_child_pref_info_eq(function() {
do_test_finished(); do_test_finished();
}); });
} }

View file

@ -40,8 +40,6 @@ static const char kPrefThirdPartySession[] =
"network.cookie.thirdparty.sessionOnly"; "network.cookie.thirdparty.sessionOnly";
static const char kPrefThirdPartyNonsecureSession[] = static const char kPrefThirdPartyNonsecureSession[] =
"network.cookie.thirdparty.nonsecureSessionOnly"; "network.cookie.thirdparty.nonsecureSessionOnly";
static const char kCookieLeaveSecurityAlone[] =
"network.cookie.leave-secure-alone";
static const char kCookieMoveIntervalSecs[] = static const char kCookieMoveIntervalSecs[] =
"network.cookie.move.interval_sec"; "network.cookie.move.interval_sec";
@ -64,7 +62,6 @@ CookieServiceChild::CookieServiceChild()
: mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT), : mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT),
mThirdPartySession(false), mThirdPartySession(false),
mThirdPartyNonsecureSession(false), mThirdPartyNonsecureSession(false),
mLeaveSecureAlone(true),
mIPCOpen(false) { mIPCOpen(false) {
NS_ASSERTION(IsNeckoChild(), "not a child process"); NS_ASSERTION(IsNeckoChild(), "not a child process");
@ -94,7 +91,6 @@ CookieServiceChild::CookieServiceChild()
prefBranch->AddObserver(kPrefCookieBehavior, this, true); prefBranch->AddObserver(kPrefCookieBehavior, this, true);
prefBranch->AddObserver(kPrefThirdPartySession, this, true); prefBranch->AddObserver(kPrefThirdPartySession, this, true);
prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true); prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true);
prefBranch->AddObserver(kCookieLeaveSecurityAlone, this, true);
prefBranch->AddObserver(kCookieMoveIntervalSecs, this, true); prefBranch->AddObserver(kCookieMoveIntervalSecs, this, true);
PrefChanged(prefBranch); PrefChanged(prefBranch);
} }
@ -271,10 +267,6 @@ void CookieServiceChild::PrefChanged(nsIPrefBranch *aPrefBranch) {
aPrefBranch->GetBoolPref(kPrefThirdPartyNonsecureSession, &boolval))) aPrefBranch->GetBoolPref(kPrefThirdPartyNonsecureSession, &boolval)))
mThirdPartyNonsecureSession = boolval; mThirdPartyNonsecureSession = boolval;
if (NS_SUCCEEDED(
aPrefBranch->GetBoolPref(kCookieLeaveSecurityAlone, &boolval)))
mLeaveSecureAlone = !!boolval;
if (!mThirdPartyUtil && RequireThirdPartyCheck()) { if (!mThirdPartyUtil && RequireThirdPartyCheck()) {
mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID); mThirdPartyUtil = do_GetService(THIRDPARTYUTIL_CONTRACTID);
NS_ASSERTION(mThirdPartyUtil, "require ThirdPartyUtil service"); NS_ASSERTION(mThirdPartyUtil, "require ThirdPartyUtil service");
@ -607,8 +599,8 @@ nsresult CookieServiceChild::SetCookieStringInternal(nsIURI *aHostURI,
bool canSetCookie = false; bool canSetCookie = false;
moreCookies = nsCookieService::CanSetCookie( moreCookies = nsCookieService::CanSetCookie(
aHostURI, key, cookieAttributes, requireHostMatch, cookieStatus, aHostURI, key, cookieAttributes, requireHostMatch, cookieStatus,
cookieString, serverTime, aFromHttp, aChannel, mLeaveSecureAlone, cookieString, serverTime, aFromHttp, aChannel, canSetCookie,
canSetCookie, mThirdPartyUtil); mThirdPartyUtil);
// We need to see if the cookie we're setting would overwrite an httponly // We need to see if the cookie we're setting would overwrite an httponly
// one. This would not affect anything we send over the net (those come from // one. This would not affect anything we send over the net (those come from

View file

@ -110,7 +110,6 @@ class CookieServiceChild : public PCookieServiceChild,
uint8_t mCookieBehavior; uint8_t mCookieBehavior;
bool mThirdPartySession; bool mThirdPartySession;
bool mThirdPartyNonsecureSession; bool mThirdPartyNonsecureSession;
bool mLeaveSecureAlone;
bool mIPCOpen; bool mIPCOpen;
}; };

View file

@ -134,19 +134,6 @@ static const char kPrefThirdPartySession[] =
"network.cookie.thirdparty.sessionOnly"; "network.cookie.thirdparty.sessionOnly";
static const char kPrefThirdPartyNonsecureSession[] = static const char kPrefThirdPartyNonsecureSession[] =
"network.cookie.thirdparty.nonsecureSessionOnly"; "network.cookie.thirdparty.nonsecureSessionOnly";
static const char kCookieLeaveSecurityAlone[] =
"network.cookie.leave-secure-alone";
// For telemetry COOKIE_LEAVE_SECURE_ALONE
#define BLOCKED_SECURE_SET_FROM_HTTP 0
#define BLOCKED_DOWNGRADE_SECURE_INEXACT 1
#define DOWNGRADE_SECURE_FROM_SECURE_INEXACT 2
#define EVICTED_NEWER_INSECURE 3
#define EVICTED_OLDEST_COOKIE 4
#define EVICTED_PREFERRED_COOKIE 5
#define EVICTING_SECURE_BLOCKED 6
#define BLOCKED_DOWNGRADE_SECURE_EXACT 7
#define DOWNGRADE_SECURE_FROM_SECURE_EXACT 8
static void bindCookieParameters(mozIStorageBindingParamsArray *aParamsArray, static void bindCookieParameters(mozIStorageBindingParamsArray *aParamsArray,
const nsCookieKey &aKey, const nsCookieKey &aKey,
@ -601,7 +588,6 @@ nsCookieService::nsCookieService()
mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT), mCookieBehavior(nsICookieService::BEHAVIOR_ACCEPT),
mThirdPartySession(false), mThirdPartySession(false),
mThirdPartyNonsecureSession(false), mThirdPartyNonsecureSession(false),
mLeaveSecureAlone(true),
mMaxNumberOfCookies(kMaxNumberOfCookies), mMaxNumberOfCookies(kMaxNumberOfCookies),
mMaxCookiesPerHost(kMaxCookiesPerHost), mMaxCookiesPerHost(kMaxCookiesPerHost),
mCookieQuotaPerHost(kCookieQuotaPerHost), mCookieQuotaPerHost(kCookieQuotaPerHost),
@ -631,7 +617,6 @@ nsresult nsCookieService::Init() {
prefBranch->AddObserver(kPrefCookiePurgeAge, this, true); prefBranch->AddObserver(kPrefCookiePurgeAge, this, true);
prefBranch->AddObserver(kPrefThirdPartySession, this, true); prefBranch->AddObserver(kPrefThirdPartySession, this, true);
prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true); prefBranch->AddObserver(kPrefThirdPartyNonsecureSession, this, true);
prefBranch->AddObserver(kCookieLeaveSecurityAlone, this, true);
PrefChanged(prefBranch); PrefChanged(prefBranch);
} }
@ -2403,10 +2388,6 @@ void nsCookieService::PrefChanged(nsIPrefBranch *aPrefBranch) {
if (NS_SUCCEEDED( if (NS_SUCCEEDED(
aPrefBranch->GetBoolPref(kPrefThirdPartyNonsecureSession, &boolval))) aPrefBranch->GetBoolPref(kPrefThirdPartyNonsecureSession, &boolval)))
mThirdPartyNonsecureSession = boolval; mThirdPartyNonsecureSession = boolval;
if (NS_SUCCEEDED(
aPrefBranch->GetBoolPref(kCookieLeaveSecurityAlone, &boolval)))
mLeaveSecureAlone = boolval;
} }
/****************************************************************************** /******************************************************************************
@ -3239,8 +3220,7 @@ bool nsCookieService::CanSetCookie(nsIURI *aHostURI, const nsCookieKey &aKey,
bool aRequireHostMatch, CookieStatus aStatus, bool aRequireHostMatch, CookieStatus aStatus,
nsDependentCString &aCookieHeader, nsDependentCString &aCookieHeader,
int64_t aServerTime, bool aFromHttp, int64_t aServerTime, bool aFromHttp,
nsIChannel *aChannel, bool aLeaveSecureAlone, nsIChannel *aChannel, bool &aSetCookie,
bool &aSetCookie,
mozIThirdPartyUtil *aThirdPartyUtil) { mozIThirdPartyUtil *aThirdPartyUtil) {
NS_ASSERTION(aHostURI, "null host!"); NS_ASSERTION(aHostURI, "null host!");
@ -3373,11 +3353,9 @@ bool nsCookieService::CanSetCookie(nsIURI *aHostURI, const nsCookieKey &aKey,
// If the new cookie is non-https and wants to set secure flag, // If the new cookie is non-https and wants to set secure flag,
// browser have to ignore this new cookie. // browser have to ignore this new cookie.
// (draft-ietf-httpbis-cookie-alone section 3.1) // (draft-ietf-httpbis-cookie-alone section 3.1)
if (aLeaveSecureAlone && aCookieAttributes.isSecure && !isSecure) { if (aCookieAttributes.isSecure && !isSecure) {
COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader, COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
"non-https cookie can't set secure flag"); "non-https cookie can't set secure flag");
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
BLOCKED_SECURE_SET_FROM_HTTP);
return newCookie; return newCookie;
} }
@ -3427,7 +3405,7 @@ bool nsCookieService::SetCookieInternal(nsIURI *aHostURI,
bool newCookie = bool newCookie =
CanSetCookie(aHostURI, aKey, cookieAttributes, aRequireHostMatch, aStatus, CanSetCookie(aHostURI, aKey, cookieAttributes, aRequireHostMatch, aStatus,
aCookieHeader, aServerTime, aFromHttp, aChannel, aCookieHeader, aServerTime, aFromHttp, aChannel,
mLeaveSecureAlone, canSetCookie, mThirdPartyUtil); canSetCookie, mThirdPartyUtil);
if (!canSetCookie) { if (!canSetCookie) {
return newCookie; return newCookie;
@ -3498,42 +3476,22 @@ void nsCookieService::AddInternal(const nsCookieKey &aKey, nsCookie *aCookie,
isSecure = false; isSecure = false;
} }
bool oldCookieIsSession = false; bool oldCookieIsSession = false;
if (mLeaveSecureAlone) { // Step1, call FindSecureCookie(). FindSecureCookie() would
// Step1, call FindSecureCookie(). FindSecureCookie() would // find the existing cookie with the security flag and has
// find the existing cookie with the security flag and has // the same name, host and path of the new cookie, if there is any.
// the same name, host and path of the new cookie, if there is any. // Step2, Confirm new cookie's security setting. If any targeted
// Step2, Confirm new cookie's security setting. If any targeted // cookie had been found in Step1, then confirm whether the
// cookie had been found in Step1, then confirm whether the // new cookie could modify it. If the new created cookies
// new cookie could modify it. If the new created cookies // "secure-only-flag" is not set, and the "scheme" component
// "secure-only-flag" is not set, and the "scheme" component // of the "request-uri" does not denote a "secure" protocol,
// of the "request-uri" does not denote a "secure" protocol, // then ignore the new cookie.
// then ignore the new cookie. // (draft-ietf-httpbis-cookie-alone section 3.2)
// (draft-ietf-httpbis-cookie-alone section 3.2) if (!aCookie->IsSecure() &&
if (!aCookie->IsSecure() && (foundSecureExact || FindSecureCookie(aKey, aCookie)) && !isSecure) {
(foundSecureExact || FindSecureCookie(aKey, aCookie))) { COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader,
if (!isSecure) { "cookie can't save because older cookie is secure "
COOKIE_LOGFAILURE(SET_COOKIE, aHostURI, aCookieHeader, "cookie but newer cookie is non-secure cookie");
"cookie can't save because older cookie is secure " return;
"cookie but newer cookie is non-secure cookie");
if (foundSecureExact) {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
BLOCKED_DOWNGRADE_SECURE_EXACT);
} else {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
BLOCKED_DOWNGRADE_SECURE_INEXACT);
}
return;
}
// A secure site is allowed to downgrade a secure cookie
// but we want to measure anyway.
if (foundSecureExact) {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
DOWNGRADE_SECURE_FROM_SECURE_EXACT);
} else {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
DOWNGRADE_SECURE_FROM_SECURE_INEXACT);
}
}
} }
RefPtr<nsCookie> oldCookie; RefPtr<nsCookie> oldCookie;
@ -3624,19 +3582,13 @@ void nsCookieService::AddInternal(const nsCookieKey &aKey, nsCookie *aCookie,
nsTArray<nsListIter> removedIterList; nsTArray<nsListIter> removedIterList;
// Prioritize evicting insecure cookies. // Prioritize evicting insecure cookies.
// (draft-ietf-httpbis-cookie-alone section 3.3) // (draft-ietf-httpbis-cookie-alone section 3.3)
mozilla::Maybe<bool> optionalSecurity =
mLeaveSecureAlone ? Some(false) : Nothing();
uint32_t limit = mMaxCookiesPerHost - mCookieQuotaPerHost; uint32_t limit = mMaxCookiesPerHost - mCookieQuotaPerHost;
FindStaleCookies(entry, currentTime, optionalSecurity, removedIterList, FindStaleCookies(entry, currentTime, false, removedIterList, limit);
limit);
if (removedIterList.Length() == 0) { if (removedIterList.Length() == 0) {
if (aCookie->IsSecure()) { if (aCookie->IsSecure()) {
// It's valid to evict a secure cookie for another secure cookie. // It's valid to evict a secure cookie for another secure cookie.
FindStaleCookies(entry, currentTime, Some(true), removedIterList, FindStaleCookies(entry, currentTime, true, removedIterList, limit);
limit);
} else { } else {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
EVICTING_SECURE_BLOCKED);
COOKIE_LOGEVICTED(aCookie, COOKIE_LOGEVICTED(aCookie,
"Too many cookies for this domain and the new " "Too many cookies for this domain and the new "
"cookie is not a secure cookie"); "cookie is not a secure cookie");
@ -3651,10 +3603,6 @@ void nsCookieService::AddInternal(const nsCookieKey &aKey, nsCookie *aCookie,
for (auto it = removedIterList.rbegin(); it != removedIterList.rend(); for (auto it = removedIterList.rbegin(); it != removedIterList.rend();
it++) { it++) {
RefPtr<nsCookie> evictedCookie = (*it).Cookie(); RefPtr<nsCookie> evictedCookie = (*it).Cookie();
if (mLeaveSecureAlone && evictedCookie->Expiry() <= currentTime) {
TelemetryForEvictingStaleCookie(evictedCookie,
evictedCookie->LastAccessed());
}
COOKIE_LOGEVICTED(evictedCookie, "Too many cookies for this domain"); COOKIE_LOGEVICTED(evictedCookie, "Too many cookies for this domain");
RemoveCookieFromList(*it); RemoveCookieFromList(*it);
CreateOrUpdatePurgeList(getter_AddRefs(purgedList), evictedCookie); CreateOrUpdatePurgeList(getter_AddRefs(purgedList), evictedCookie);
@ -4571,8 +4519,7 @@ class CookieIterComparator {
// Given the output iter array and the count limit, find cookies // Given the output iter array and the count limit, find cookies
// sort by expiry and lastAccessed time. // sort by expiry and lastAccessed time.
void nsCookieService::FindStaleCookies(nsCookieEntry *aEntry, void nsCookieService::FindStaleCookies(nsCookieEntry *aEntry,
int64_t aCurrentTime, int64_t aCurrentTime, bool aIsSecure,
const mozilla::Maybe<bool> &aIsSecure,
nsTArray<nsListIter> &aOutput, nsTArray<nsListIter> &aOutput,
uint32_t aLimit) { uint32_t aLimit) {
MOZ_ASSERT(aLimit); MOZ_ASSERT(aLimit);
@ -4591,7 +4538,7 @@ void nsCookieService::FindStaleCookies(nsCookieEntry *aEntry,
continue; continue;
} }
if (aIsSecure.isSome() && !aIsSecure.value()) { if (!aIsSecure) {
// We want to look for the non-secure cookie first time through, // We want to look for the non-secure cookie first time through,
// then find the secure cookie the second time this function is called. // then find the secure cookie the second time this function is called.
if (cookie->IsSecure()) { if (cookie->IsSecure()) {
@ -4609,23 +4556,6 @@ void nsCookieService::FindStaleCookies(nsCookieEntry *aEntry,
} }
} }
void nsCookieService::TelemetryForEvictingStaleCookie(
nsCookie *aEvicted, int64_t oldestCookieTime) {
// We need to record the evicting cookie to telemetry.
if (!aEvicted->IsSecure()) {
if (aEvicted->LastAccessed() > oldestCookieTime) {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
EVICTED_NEWER_INSECURE);
} else {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
EVICTED_OLDEST_COOKIE);
}
} else {
Telemetry::Accumulate(Telemetry::COOKIE_LEAVE_SECURE_ALONE,
EVICTED_PREFERRED_COOKIE);
}
}
// count the number of cookies stored by a particular host. this is provided by // count the number of cookies stored by a particular host. this is provided by
// the nsICookieManager interface. // the nsICookieManager interface.
NS_IMETHODIMP NS_IMETHODIMP

View file

@ -255,8 +255,7 @@ class nsCookieService final : public nsICookieService,
bool aRequireHostMatch, CookieStatus aStatus, bool aRequireHostMatch, CookieStatus aStatus,
nsDependentCString &aCookieHeader, nsDependentCString &aCookieHeader,
int64_t aServerTime, bool aFromHttp, int64_t aServerTime, bool aFromHttp,
nsIChannel *aChannel, bool aLeaveSercureAlone, nsIChannel *aChannel, bool &aSetCookie,
bool &aSetCookie,
mozIThirdPartyUtil *aThirdPartyUtil); mozIThirdPartyUtil *aThirdPartyUtil);
static CookieStatus CheckPrefs( static CookieStatus CheckPrefs(
nsICookiePermission *aPermissionServices, uint8_t aCookieBehavior, nsICookiePermission *aPermissionServices, uint8_t aCookieBehavior,
@ -353,10 +352,8 @@ class nsCookieService final : public nsICookieService,
nsListIter &aIter); nsListIter &aIter);
bool FindSecureCookie(const nsCookieKey &aKey, nsCookie *aCookie); bool FindSecureCookie(const nsCookieKey &aKey, nsCookie *aCookie);
void FindStaleCookies(nsCookieEntry *aEntry, int64_t aCurrentTime, void FindStaleCookies(nsCookieEntry *aEntry, int64_t aCurrentTime,
const mozilla::Maybe<bool> &aIsSecure, bool aIsSecure, nsTArray<nsListIter> &aOutput,
nsTArray<nsListIter> &aOutput, uint32_t aLimit); uint32_t aLimit);
void TelemetryForEvictingStaleCookie(nsCookie *aEvicted,
int64_t oldestCookieTime);
void NotifyAccepted(nsIChannel *aChannel); void NotifyAccepted(nsIChannel *aChannel);
void NotifyRejected(nsIURI *aHostURI, nsIChannel *aChannel, void NotifyRejected(nsIURI *aHostURI, nsIChannel *aChannel,
uint32_t aRejectedReason, CookieOperation aOperation); uint32_t aRejectedReason, CookieOperation aOperation);
@ -406,7 +403,6 @@ class nsCookieService final : public nsICookieService,
// LIMITFOREIGN} // LIMITFOREIGN}
bool mThirdPartySession; bool mThirdPartySession;
bool mThirdPartyNonsecureSession; bool mThirdPartyNonsecureSession;
bool mLeaveSecureAlone;
uint16_t mMaxNumberOfCookies; uint16_t mMaxNumberOfCookies;
uint16_t mMaxCookiesPerHost; uint16_t mMaxCookiesPerHost;
uint16_t mCookieQuotaPerHost; uint16_t mCookieQuotaPerHost;

View file

@ -32,8 +32,6 @@ static NS_DEFINE_CID(kPrefServiceCID, NS_PREFSERVICE_CID);
static const char kCookiesPermissions[] = "network.cookie.cookieBehavior"; static const char kCookiesPermissions[] = "network.cookie.cookieBehavior";
static const char kPrefCookieQuotaPerHost[] = "network.cookie.quotaPerHost"; static const char kPrefCookieQuotaPerHost[] = "network.cookie.quotaPerHost";
static const char kCookiesMaxPerHost[] = "network.cookie.maxPerHost"; static const char kCookiesMaxPerHost[] = "network.cookie.maxPerHost";
static const char kCookieLeaveSecurityAlone[] =
"network.cookie.leave-secure-alone";
#define OFFSET_ONE_WEEK int64_t(604800) * PR_USEC_PER_SEC #define OFFSET_ONE_WEEK int64_t(604800) * PR_USEC_PER_SEC
#define OFFSET_ONE_DAY int64_t(86400) * PR_USEC_PER_SEC #define OFFSET_ONE_DAY int64_t(86400) * PR_USEC_PER_SEC
@ -176,7 +174,6 @@ void InitPrefs(nsIPrefBranch *aPrefBranch) {
// we use the most restrictive set of prefs we can; // we use the most restrictive set of prefs we can;
// however, we don't test third party blocking here. // however, we don't test third party blocking here.
aPrefBranch->SetIntPref(kCookiesPermissions, 0); // accept all aPrefBranch->SetIntPref(kCookiesPermissions, 0); // accept all
aPrefBranch->SetBoolPref(kCookieLeaveSecurityAlone, true);
// Set quotaPerHost to maxPerHost - 1, so there is only one cookie // Set quotaPerHost to maxPerHost - 1, so there is only one cookie
// will be evicted everytime. // will be evicted everytime.
aPrefBranch->SetIntPref(kPrefCookieQuotaPerHost, 49); aPrefBranch->SetIntPref(kPrefCookieQuotaPerHost, 49);
@ -980,8 +977,6 @@ TEST(TestCookie, TestCookieMain) {
GetACookie(cookieService, "http://creation.ordering.tests/", nullptr, cookie); GetACookie(cookieService, "http://creation.ordering.tests/", nullptr, cookie);
EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, expected.get())); EXPECT_TRUE(CheckResult(cookie.get(), MUST_EQUAL, expected.get()));
// *** eviction and creation ordering tests after enable
// network.cookie.leave-secure-alone reset cookie
cookieMgr->RemoveAll(); cookieMgr->RemoveAll();
for (int32_t i = 0; i < 60; ++i) { for (int32_t i = 0; i < 60; ++i) {

View file

@ -45,6 +45,15 @@ __all__ = [
] ]
def path_starts_with(path, prefix):
if os.altsep:
prefix = prefix.replace(os.altsep, os.sep)
path = path.replace(os.altsep, os.sep)
prefix = [os.path.normcase(p) for p in prefix.split(os.sep)]
path = [os.path.normcase(p) for p in path.split(os.sep)]
return path[:len(prefix)] == prefix
class Expression: class Expression:
def __init__(self, expression_string): def __init__(self, expression_string):
""" """
@ -280,6 +289,15 @@ class Preprocessor:
'LINE': 0, 'LINE': 0,
'DIRECTORY': os.path.abspath('.')}.iteritems(): 'DIRECTORY': os.path.abspath('.')}.iteritems():
self.context[k] = v self.context[k] = v
try:
# Can import globally because of bootstrapping issues.
from buildconfig import topsrcdir, topobjdir
except ImportError:
# Allow this script to still work independently of a configured objdir.
topsrcdir = topobjdir = None
self.topsrcdir = topsrcdir
self.topobjdir = topobjdir
self.curdir = '.'
self.actionLevel = 0 self.actionLevel = 0
self.disableLevel = 0 self.disableLevel = 0
# ifStates can be # ifStates can be
@ -747,7 +765,7 @@ class Preprocessor:
if filters: if filters:
args = self.applyFilters(args) args = self.applyFilters(args)
if not os.path.isabs(args): if not os.path.isabs(args):
args = os.path.join(self.context['DIRECTORY'], args) args = os.path.join(self.curdir, args)
args = open(args, 'rU') args = open(args, 'rU')
except Preprocessor.Error: except Preprocessor.Error:
raise raise
@ -757,15 +775,22 @@ class Preprocessor:
oldFile = self.context['FILE'] oldFile = self.context['FILE']
oldLine = self.context['LINE'] oldLine = self.context['LINE']
oldDir = self.context['DIRECTORY'] oldDir = self.context['DIRECTORY']
oldCurdir = self.curdir
self.noteLineInfo() self.noteLineInfo()
if args.isatty(): if args.isatty():
# we're stdin, use '-' and '' for file and dir # we're stdin, use '-' and '' for file and dir
self.context['FILE'] = '-' self.context['FILE'] = '-'
self.context['DIRECTORY'] = '' self.context['DIRECTORY'] = ''
self.curdir = '.'
else: else:
abspath = os.path.abspath(args.name) abspath = os.path.abspath(args.name)
self.curdir = os.path.dirname(abspath)
self.includes.add(abspath) self.includes.add(abspath)
if self.topobjdir and path_starts_with(abspath, self.topobjdir):
abspath = '$OBJDIR' + abspath[len(self.topobjdir):]
elif self.topsrcdir and path_starts_with(abspath, self.topsrcdir):
abspath = '$SRCDIR' + abspath[len(self.topsrcdir):]
self.context['FILE'] = abspath self.context['FILE'] = abspath
self.context['DIRECTORY'] = os.path.dirname(abspath) self.context['DIRECTORY'] = os.path.dirname(abspath)
self.context['LINE'] = 0 self.context['LINE'] = 0
@ -780,6 +805,7 @@ class Preprocessor:
self.checkLineNumbers = oldCheckLineNumbers self.checkLineNumbers = oldCheckLineNumbers
self.context['LINE'] = oldLine self.context['LINE'] = oldLine
self.context['DIRECTORY'] = oldDir self.context['DIRECTORY'] = oldDir
self.curdir = oldCurdir
def do_includesubst(self, args): def do_includesubst(self, args):
args = self.filter_substitution(args) args = self.filter_substitution(args)
self.do_include(args) self.do_include(args)

View file

@ -148,8 +148,8 @@ class TestBuild(unittest.TestCase):
def validate(self, config): def validate(self, config):
self.maxDiff = None self.maxDiff = None
test_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), test_path = os.sep.join(('$SRCDIR', 'python', 'mozbuild', 'mozbuild',
'data', 'build') + os.sep 'test', 'backend', 'data', 'build')) + os.sep
# We want unicode instances out of the files, because having plain str # We want unicode instances out of the files, because having plain str
# makes assertEqual diff output in case of error extra verbose because # makes assertEqual diff output in case of error extra verbose because

View file

@ -567,53 +567,67 @@ class TestPreprocessor(unittest.TestCase):
def test_include_line(self): def test_include_line(self):
files = { files = {
'test.js': '\n'.join([ 'srcdir/test.js': '\n'.join([
'#define foo foobarbaz', '#define foo foobarbaz',
'#include @inc@', '#include @inc@',
'@bar@', '@bar@',
'', '',
]), ]),
'bar.js': '\n'.join([ 'srcdir/bar.js': '\n'.join([
'#define bar barfoobaz', '#define bar barfoobaz',
'@foo@', '@foo@',
'', '',
]), ]),
'foo.js': '\n'.join([ 'srcdir/foo.js': '\n'.join([
'bazfoobar', 'bazfoobar',
'#include bar.js', '#include bar.js',
'bazbarfoo', 'bazbarfoo',
'', '',
]), ]),
'baz.js': 'baz\n', 'objdir/baz.js': 'baz\n',
'f.js': '\n'.join([ 'srcdir/f.js': '\n'.join([
'#include foo.js', '#include foo.js',
'#filter substitution', '#filter substitution',
'#define inc bar.js', '#define inc bar.js',
'#include test.js', '#include test.js',
'#include baz.js', '#include ../objdir/baz.js',
'fin', 'fin',
'', '',
]), ]),
} }
preprocessed = ('//@line 1 "$SRCDIR/foo.js"\n'
'bazfoobar\n'
'//@line 2 "$SRCDIR/bar.js"\n'
'@foo@\n'
'//@line 3 "$SRCDIR/foo.js"\n'
'bazbarfoo\n'
'//@line 2 "$SRCDIR/bar.js"\n'
'foobarbaz\n'
'//@line 3 "$SRCDIR/test.js"\n'
'barfoobaz\n'
'//@line 1 "$OBJDIR/baz.js"\n'
'baz\n'
'//@line 6 "$SRCDIR/f.js"\n'
'fin\n').replace('DIR/', 'DIR' + os.sep)
# Try with separate srcdir/objdir
with MockedOpen(files): with MockedOpen(files):
self.pp.do_include('f.js') self.pp.topsrcdir = os.path.abspath('srcdir')
self.assertEqual(self.pp.out.getvalue(), self.pp.topobjdir = os.path.abspath('objdir')
('//@line 1 "CWD/foo.js"\n' self.pp.do_include('srcdir/f.js')
'bazfoobar\n' self.assertEqual(self.pp.out.getvalue(), preprocessed)
'//@line 2 "CWD/bar.js"\n'
'@foo@\n' # Try again with relative objdir
'//@line 3 "CWD/foo.js"\n' self.setUp()
'bazbarfoo\n' files['srcdir/objdir/baz.js'] = files['objdir/baz.js']
'//@line 2 "CWD/bar.js"\n' del files['objdir/baz.js']
'foobarbaz\n' files['srcdir/f.js'] = files['srcdir/f.js'].replace('../', '')
'//@line 3 "CWD/test.js"\n' with MockedOpen(files):
'barfoobaz\n' self.pp.topsrcdir = os.path.abspath('srcdir')
'//@line 1 "CWD/baz.js"\n' self.pp.topobjdir = os.path.abspath('srcdir/objdir')
'baz\n' self.pp.do_include('srcdir/f.js')
'//@line 6 "CWD/f.js"\n' self.assertEqual(self.pp.out.getvalue(), preprocessed)
'fin\n').replace('CWD/',
os.getcwd() + os.path.sep))
def test_include_missing_file(self): def test_include_missing_file(self):
with MockedOpen({'f': '#include foo\n'}): with MockedOpen({'f': '#include foo\n'}):

View file

@ -188,8 +188,7 @@ class PreprocessorOutputWrapper(object):
self._pp = preprocessor self._pp = preprocessor
def write(self, str): def write(self, str):
file = os.path.normpath(os.path.abspath(self._pp.context['FILE'])) with errors.context(self._pp.context['FILE'], self._pp.context['LINE']):
with errors.context(file, self._pp.context['LINE']):
self._parser.handle_line(str) self._parser.handle_line(str)

View file

@ -5,6 +5,7 @@
import unittest import unittest
import mozunit import mozunit
import os import os
from buildconfig import topobjdir
from mozpack.packager import ( from mozpack.packager import (
preprocess_manifest, preprocess_manifest,
CallDeque, CallDeque,
@ -43,7 +44,7 @@ baz@SUFFIX@
class TestPreprocessManifest(unittest.TestCase): class TestPreprocessManifest(unittest.TestCase):
MANIFEST_PATH = os.path.join(os.path.abspath(os.curdir), 'manifest') MANIFEST_PATH = os.path.join('$OBJDIR', 'manifest')
EXPECTED_LOG = [ EXPECTED_LOG = [
((MANIFEST_PATH, 2), 'add', '', 'bar/*'), ((MANIFEST_PATH, 2), 'add', '', 'bar/*'),
@ -68,6 +69,11 @@ class TestPreprocessManifest(unittest.TestCase):
self.log.append(args) self.log.append(args)
self.sink = MockSink() self.sink = MockSink()
self.cwd = os.getcwd()
os.chdir(topobjdir)
def tearDown(self):
os.chdir(self.cwd)
def test_preprocess_manifest(self): def test_preprocess_manifest(self):
with MockedOpen({'manifest': MANIFEST}): with MockedOpen({'manifest': MANIFEST}):

Some files were not shown because too many files have changed in this diff Show more