Bug 440908 - Add support for sticky and locked attributes to default prefs. r=glandium

Sticky prefs are already specifiable with `sticky_pref`, but this is a more
general attribute mechanism. The ability to specify a locked pref in the data
file is new.

The patch also adds nsIPrefService.readDefaultPrefsFromFile, to match the
existing nsIPrefService.readUserPrefsFromFile method, and converts a number of
the existing tests to use it.

MozReview-Commit-ID: 9LLMBJVZfg7

--HG--
extra : rebase_source : fa25bad87c4d9fcba6dc13cd2cc04ea6a2354f51
This commit is contained in:
Nicholas Nethercote 2018-03-02 15:31:40 +11:00
parent 74fea66ce5
commit 038a72de3b
12 changed files with 323 additions and 127 deletions

View File

@ -596,8 +596,9 @@ public:
nsresult SetDefaultValue(PrefType aType,
PrefValue aValue,
bool aFromFile,
bool aIsSticky,
bool aIsLocked,
bool aFromFile,
bool* aValueChanged)
{
// Types must always match when setting the default value.
@ -607,20 +608,25 @@ public:
// Should we set the default value? Only if the pref is not locked, and
// doing so would change the default value.
if (!IsLocked() && !ValueMatches(PrefValueKind::Default, aType, aValue)) {
mDefaultValue.Replace(Type(), aType, aValue);
mHasDefaultValue = true;
if (!aFromFile) {
mHasChangedSinceInit = true;
if (!IsLocked()) {
if (aIsLocked) {
SetIsLocked(true);
}
if (aIsSticky) {
mIsSticky = true;
if (!ValueMatches(PrefValueKind::Default, aType, aValue)) {
mDefaultValue.Replace(Type(), aType, aValue);
mHasDefaultValue = true;
if (!aFromFile) {
mHasChangedSinceInit = true;
}
if (aIsSticky) {
mIsSticky = true;
}
if (!mHasUserValue) {
*aValueChanged = true;
}
// What if we change the default to be the same as the user value?
// Should we clear the user value? Currently we don't.
}
if (!mHasUserValue) {
*aValueChanged = true;
}
// What if we change the default to be the same as the user value?
// Should we clear the user value? Currently we don't.
}
return NS_OK;
}
@ -944,6 +950,7 @@ pref_SetPref(const char* aPrefName,
PrefValueKind aKind,
PrefValue aValue,
bool aIsSticky,
bool aIsLocked,
bool aFromFile)
{
MOZ_ASSERT(NS_IsMainThread());
@ -966,9 +973,10 @@ pref_SetPref(const char* aPrefName,
bool valueChanged = false;
nsresult rv;
if (aKind == PrefValueKind::Default) {
rv =
pref->SetDefaultValue(aType, aValue, aFromFile, aIsSticky, &valueChanged);
rv = pref->SetDefaultValue(
aType, aValue, aIsSticky, aIsLocked, aFromFile, &valueChanged);
} else {
MOZ_ASSERT(!aIsLocked); // `locked` is disallowed in user pref files
rv = pref->SetUserValue(aType, aValue, aFromFile, &valueChanged);
}
if (NS_FAILED(rv)) {
@ -1076,7 +1084,8 @@ typedef void (*PrefsParserPrefFn)(const char* aPrefName,
PrefType aType,
PrefValueKind aKind,
PrefValue aValue,
bool aIsSticky);
bool aIsSticky,
bool aIsLocked);
// Keep this in sync with ErrorFn in prefs_parser/src/lib.rs.
//
@ -1087,6 +1096,7 @@ typedef void (*PrefsParserErrorFn)(const char* aMsg);
// Keep this in sync with prefs_parser_parse() in prefs_parser/src/lib.rs.
bool
prefs_parser_parse(const char* aPath,
PrefValueKind aKind,
const char* aBuf,
size_t aLen,
PrefsParserPrefFn aPrefFn,
@ -1100,13 +1110,14 @@ public:
~Parser() = default;
bool Parse(const nsCString& aName,
PrefValueKind aKind,
const char* aPath,
const TimeStamp& aStartTime,
const nsCString& aBuf)
{
sNumPrefs = 0;
bool ok = prefs_parser_parse(
aPath, aBuf.get(), aBuf.Length(), HandlePref, HandleError);
aPath, aKind, aBuf.get(), aBuf.Length(), HandlePref, HandleError);
if (!ok) {
return false;
}
@ -1128,11 +1139,17 @@ private:
PrefType aType,
PrefValueKind aKind,
PrefValue aValue,
bool aIsSticky)
bool aIsSticky,
bool aIsLocked)
{
sNumPrefs++;
pref_SetPref(
aPrefName, aType, aKind, aValue, aIsSticky, /* fromFile */ true);
pref_SetPref(aPrefName,
aType,
aKind,
aValue,
aIsSticky,
aIsLocked,
/* fromFile */ true);
}
static void HandleError(const char* aMsg)
@ -1164,7 +1181,8 @@ TestParseErrorHandlePref(const char* aPrefName,
PrefType aType,
PrefValueKind aKind,
PrefValue aValue,
bool aIsSticky)
bool aIsSticky,
bool aIsLocked)
{
}
@ -1179,9 +1197,10 @@ TestParseErrorHandleError(const char* aMsg)
// Keep this in sync with the declaration in test/gtest/Parser.cpp.
void
TestParseError(const char* aText, nsCString& aErrorMsg)
TestParseError(PrefValueKind aKind, const char* aText, nsCString& aErrorMsg)
{
prefs_parser_parse("test",
aKind,
aText,
strlen(aText),
TestParseErrorHandlePref,
@ -2449,7 +2468,7 @@ Preferences::HandleDirty()
}
static nsresult
openPrefFile(nsIFile* aFile);
openPrefFile(nsIFile* aFile, PrefValueKind aKind);
static const char kTelemetryPref[] = "toolkit.telemetry.enabled";
static const char kChannelPref[] = "app.update.channel";
@ -3156,6 +3175,19 @@ Preferences::Observe(nsISupports* aSubject,
return rv;
}
NS_IMETHODIMP
Preferences::ReadDefaultPrefsFromFile(nsIFile* aFile)
{
ENSURE_PARENT_PROCESS("Preferences::ReadDefaultPrefsFromFile", "all prefs");
if (!aFile) {
NS_ERROR("ReadDefaultPrefsFromFile requires a parameter");
return NS_ERROR_INVALID_ARG;
}
return openPrefFile(aFile, PrefValueKind::Default);
}
NS_IMETHODIMP
Preferences::ReadUserPrefsFromFile(nsIFile* aFile)
{
@ -3166,7 +3198,7 @@ Preferences::ReadUserPrefsFromFile(nsIFile* aFile)
return NS_ERROR_INVALID_ARG;
}
return openPrefFile(aFile);
return openPrefFile(aFile, PrefValueKind::User);
}
NS_IMETHODIMP
@ -3413,7 +3445,7 @@ Preferences::ReadSavedPrefs()
return nullptr;
}
rv = openPrefFile(file);
rv = openPrefFile(file, PrefValueKind::User);
if (rv == NS_ERROR_FILE_NOT_FOUND) {
// This is a normal case for new users.
Telemetry::ScalarSet(
@ -3442,7 +3474,7 @@ Preferences::ReadUserOverridePrefs()
}
aFile->AppendNative(NS_LITERAL_CSTRING("user.js"));
rv = openPrefFile(aFile);
rv = openPrefFile(aFile, PrefValueKind::User);
if (rv != NS_ERROR_FILE_NOT_FOUND) {
// If the file exists and was at least partially read, record that in
// telemetry as it may be a sign of pref injection.
@ -3584,7 +3616,7 @@ Preferences::WritePrefFile(nsIFile* aFile, SaveMethod aSaveMethod)
}
static nsresult
openPrefFile(nsIFile* aFile)
openPrefFile(nsIFile* aFile, PrefValueKind aKind)
{
TimeStamp startTime = TimeStamp::Now();
@ -3600,7 +3632,7 @@ openPrefFile(nsIFile* aFile)
Parser parser;
if (!parser.Parse(
filename, NS_ConvertUTF16toUTF8(path).get(), startTime, data)) {
filename, aKind, NS_ConvertUTF16toUTF8(path).get(), startTime, data)) {
return NS_ERROR_FILE_CORRUPTED;
}
@ -3701,7 +3733,7 @@ pref_LoadPrefsInDir(nsIFile* aDir,
uint32_t arrayCount = prefFiles.Count();
uint32_t i;
for (i = 0; i < arrayCount; ++i) {
rv2 = openPrefFile(prefFiles[i]);
rv2 = openPrefFile(prefFiles[i], PrefValueKind::Default);
if (NS_FAILED(rv2)) {
NS_ERROR("Default pref file not parsed successfully.");
rv = rv2;
@ -3713,7 +3745,7 @@ pref_LoadPrefsInDir(nsIFile* aDir,
// This may be a sparse array; test before parsing.
nsIFile* file = specialFiles[i];
if (file) {
rv2 = openPrefFile(file);
rv2 = openPrefFile(file, PrefValueKind::Default);
if (NS_FAILED(rv2)) {
NS_ERROR("Special default pref file not parsed successfully.");
rv = rv2;
@ -3734,7 +3766,11 @@ pref_ReadPrefFromJar(nsZipArchive* aJarReader, const char* aName)
URLPreloader::ReadZip(aJarReader, nsDependentCString(aName)));
Parser parser;
if (!parser.Parse(nsDependentCString(aName), aName, startTime, manifest)) {
if (!parser.Parse(nsDependentCString(aName),
PrefValueKind::Default,
aName,
startTime,
manifest)) {
return NS_ERROR_FILE_CORRUPTED;
}
@ -3814,7 +3850,7 @@ Preferences::InitInitialObjects()
rv = greprefsFile->AppendNative(NS_LITERAL_CSTRING("greprefs.js"));
NS_ENSURE_SUCCESS(rv, Err("greprefsFile->AppendNative() failed"));
rv = openPrefFile(greprefsFile);
rv = openPrefFile(greprefsFile, PrefValueKind::Default);
if (NS_FAILED(rv)) {
NS_WARNING("Error parsing GRE default preferences. Is this an old-style "
"embedding app?");
@ -3943,15 +3979,14 @@ Preferences::InitInitialObjects()
bool releaseCandidateOnBeta = false;
if (!strcmp(NS_STRINGIFY(MOZ_UPDATE_CHANNEL), "release")) {
nsAutoCString updateChannelPrefValue;
Preferences::GetCString(kChannelPref, updateChannelPrefValue,
PrefValueKind::Default);
Preferences::GetCString(
kChannelPref, updateChannelPrefValue, PrefValueKind::Default);
releaseCandidateOnBeta = updateChannelPrefValue.EqualsLiteral("beta");
}
if (!strcmp(NS_STRINGIFY(MOZ_UPDATE_CHANNEL), "nightly") ||
!strcmp(NS_STRINGIFY(MOZ_UPDATE_CHANNEL), "aurora") ||
!strcmp(NS_STRINGIFY(MOZ_UPDATE_CHANNEL), "beta") ||
developerBuild ||
!strcmp(NS_STRINGIFY(MOZ_UPDATE_CHANNEL), "beta") || developerBuild ||
releaseCandidateOnBeta) {
Preferences::SetBoolInAnyProcess(
kTelemetryPref, true, PrefValueKind::Default);
@ -4101,6 +4136,7 @@ Preferences::SetCStringInAnyProcess(const char* aPrefName,
aKind,
prefValue,
/* isSticky */ false,
/* isLocked */ false,
/* fromFile */ false);
}
@ -4127,6 +4163,7 @@ Preferences::SetBoolInAnyProcess(const char* aPrefName,
aKind,
prefValue,
/* isSticky */ false,
/* isLocked */ false,
/* fromFile */ false);
}
@ -4151,6 +4188,7 @@ Preferences::SetIntInAnyProcess(const char* aPrefName,
aKind,
prefValue,
/* isSticky */ false,
/* isLocked */ false,
/* fromFile */ false);
}

View File

@ -45,7 +45,7 @@ interface nsIPrefService : nsISupports
*
* @throws Error File failed to write.
*
* @see readUserPrefs
* @see readUserPrefsFromFile
* @see nsIFile
*/
void savePrefFile(in nsIFile aFile);
@ -102,14 +102,20 @@ interface nsIPrefService : nsISupports
readonly attribute boolean dirty;
/**
* Read in the preferences specified in a user preference file. This method
* does not clear user preferences that were already set.
* Read in the preferences specified in a default preference file. This
* method does not clear preferences that were already set, but it may
* overwrite existing preferences.
*
* @param aFile The file to be read.
*
* @throws Error File failed to read or contained invalid data.
* @note This method is intended for internal unit testing only!
*/
void readDefaultPrefsFromFile(in nsIFile aFile);
/**
* Like readDefaultPrefsFromFile, but for a user prefs file.
*/
void readUserPrefsFromFile(in nsIFile aFile);
};

View File

@ -4,10 +4,12 @@
//! This crate implements a prefs file parser.
//!
//! Pref files have the following grammar.
//! Pref files have the following grammar. Note that there are slight
//! differences between the grammar for a default prefs files and a user prefs
//! file.
//!
//! <pref-file> = <pref>*
//! <pref> = <pref-spec> "(" <pref-name> "," <pref-value> ")" ";"
//! <pref> = <pref-spec> "(" <pref-name> "," <pref-value> <pref-attrs> ")" ";"
//! <pref-spec> = "user_pref" | "pref" | "sticky_pref"
//! <pref-name> = <string-literal>
//! <pref-value> = <string-literal> | "true" | "false" | <int-value>
@ -21,6 +23,9 @@
//! gives a UTF-16 code unit that is converted to UTF-8 before being copied
//! into an 8-bit string value. \x00 and \u0000 are disallowed because they
//! would cause C++ code handling such strings to misbehave.
//! <pref-attrs> = ("," <pref-attr>)* // in default pref files
//! = <empty> // in user pref files
//! <pref-attr> = "sticky" | "locked" // default pref files only
//!
//! Comments can take three forms:
//! - # Python-style comments
@ -94,7 +99,7 @@ pub enum PrefType {
}
/// Keep this in sync with PrefValueKind in Preferences.h.
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum PrefValueKind {
Default,
@ -112,7 +117,7 @@ pub union PrefValue {
/// Keep this in sync with PrefsParserPrefFn in Preferences.cpp.
type PrefFn = unsafe extern "C" fn(pref_name: *const c_char, pref_type: PrefType,
pref_value_kind: PrefValueKind, pref_value: PrefValue,
is_sticky: bool);
is_sticky: bool, is_locked: bool);
/// Keep this in sync with PrefsParserErrorFn in Preferences.cpp.
type ErrorFn = unsafe extern "C" fn(msg: *const c_char);
@ -129,8 +134,8 @@ type ErrorFn = unsafe extern "C" fn(msg: *const c_char);
/// Keep this in sync with the prefs_parser_parse() declaration in
/// Preferences.cpp.
#[no_mangle]
pub extern "C" fn prefs_parser_parse(path: *const c_char, buf: *const c_char, len: usize,
pref_fn: PrefFn, error_fn: ErrorFn) -> bool {
pub extern "C" fn prefs_parser_parse(path: *const c_char, kind: PrefValueKind, buf: *const c_char,
len: usize, pref_fn: PrefFn, error_fn: ErrorFn) -> bool {
let path = unsafe { std::ffi::CStr::from_ptr(path).to_string_lossy().into_owned() };
// Make sure `buf` ends in a '\0', and include that in the length, because
@ -138,7 +143,7 @@ pub extern "C" fn prefs_parser_parse(path: *const c_char, buf: *const c_char, le
let buf = unsafe { std::slice::from_raw_parts(buf as *const c_uchar, len + 1) };
assert!(buf.last() == Some(&EOF));
let mut parser = Parser::new(&path, &buf, pref_fn, error_fn);
let mut parser = Parser::new(&path, kind, &buf, pref_fn, error_fn);
parser.parse()
}
@ -157,6 +162,8 @@ enum Token {
UserPref, // user_pref
True, // true
False, // false
Sticky, // sticky
Locked, // locked
// String literal, e.g. '"string"'. The value is stored elsewhere.
String,
@ -272,36 +279,41 @@ struct KeywordInfo {
token: Token,
}
const KEYWORD_INFOS: &[KeywordInfo; 5] = &[
const KEYWORD_INFOS: [KeywordInfo; 7] = [
// These are ordered by frequency.
KeywordInfo { string: b"pref", token: Token::Pref },
KeywordInfo { string: b"true", token: Token::True },
KeywordInfo { string: b"false", token: Token::False },
KeywordInfo { string: b"user_pref", token: Token::UserPref },
KeywordInfo { string: b"sticky", token: Token::Sticky },
KeywordInfo { string: b"locked", token: Token::Locked },
KeywordInfo { string: b"sticky_pref", token: Token::StickyPref },
];
struct Parser<'t> {
path: &'t str, // Path to the file being parsed. Used in error messages.
buf: &'t [u8], // Text being parsed.
i: usize, // Index of next char to be read.
line_num: u32, // Current line number within the text.
pref_fn: PrefFn, // Callback for processing each pref.
error_fn: ErrorFn, // Callback for parse errors.
has_errors: bool, // Have we encountered errors?
path: &'t str, // Path to the file being parsed. Used in error messages.
kind: PrefValueKind, // Default prefs file or user prefs file?
buf: &'t [u8], // Text being parsed.
i: usize, // Index of next char to be read.
line_num: u32, // Current line number within the text.
pref_fn: PrefFn, // Callback for processing each pref.
error_fn: ErrorFn, // Callback for parse errors.
has_errors: bool, // Have we encountered errors?
}
// As described above, we use 0 to represent EOF.
const EOF: u8 = b'\0';
impl<'t> Parser<'t> {
fn new(path: &'t str, buf: &'t [u8], pref_fn: PrefFn, error_fn: ErrorFn) -> Parser<'t> {
fn new(path: &'t str, kind: PrefValueKind, buf: &'t [u8], pref_fn: PrefFn, error_fn: ErrorFn)
-> Parser<'t> {
// Make sure these tables take up 1 byte per entry.
assert!(std::mem::size_of_val(&CHAR_KINDS) == 256);
assert!(std::mem::size_of_val(&SPECIAL_STRING_CHARS) == 256);
Parser {
path: path,
kind: kind,
buf: buf,
i: 0,
line_num: 1,
@ -323,7 +335,7 @@ impl<'t> Parser<'t> {
// this will be either the first token of a new pref, or EOF.
loop {
// <pref-spec>
let (pref_value_kind, is_sticky) = match token {
let (pref_value_kind, mut is_sticky) = match token {
Token::Pref => (PrefValueKind::Default, false),
Token::StickyPref => (PrefValueKind::Default, true),
Token::UserPref => (PrefValueKind::User, false),
@ -370,7 +382,6 @@ impl<'t> Parser<'t> {
Token::String => {
(PrefType::String,
PrefValue { string_val: value_str.as_ptr() as *const c_char })
}
Token::Int(u) => {
// Accept u <= 2147483647; anything larger will overflow i32.
@ -425,10 +436,49 @@ impl<'t> Parser<'t> {
}
};
// ("," <pref-attr>)* // default pref files only
let mut is_locked = false;
let mut has_attrs = false;
if self.kind == PrefValueKind::Default {
let ok = loop {
// ","
token = self.get_token(&mut none_str);
if token != Token::SingleChar(b',') {
break true;
}
// <pref-attr>
token = self.get_token(&mut none_str);
match token {
Token::Sticky => is_sticky = true,
Token::Locked => is_locked = true,
_ => {
token =
self.error_and_recover(token, "expected pref attribute after ','");
break false;
}
}
has_attrs = true;
};
if !ok {
continue;
}
} else {
token = self.get_token(&mut none_str);
}
// ")"
token = self.get_token(&mut none_str);
if token != Token::SingleChar(b')') {
token = self.error_and_recover(token, "expected ')' after pref value");
let expected_msg = if self.kind == PrefValueKind::Default {
if has_attrs {
"expected ',' or ')' after pref attribute"
} else {
"expected ',' or ')' after pref value"
}
} else {
"expected ')' after pref value"
};
token = self.error_and_recover(token, expected_msg);
continue;
}
@ -440,7 +490,7 @@ impl<'t> Parser<'t> {
}
unsafe { (self.pref_fn)(pref_name.as_ptr() as *const c_char, pref_type, pref_value_kind,
pref_value, is_sticky) };
pref_value, is_sticky, is_locked) };
token = self.get_token(&mut none_str);
}

View File

@ -6,12 +6,15 @@
#include "gtest/gtest.h"
#include "mozilla/ArrayUtils.h"
#include "Preferences.h"
using namespace mozilla;
// Keep this in sync with the declaration in Preferences.cpp.
//
// It's declared here to avoid polluting Preferences.h with test-only stuff.
void
TestParseError(const char* aText, nsCString& aErrorMsg);
TestParseError(PrefValueKind aKind, const char* aText, nsCString& aErrorMsg);
TEST(PrefsParser, Errors)
{
@ -19,12 +22,18 @@ TEST(PrefsParser, Errors)
// Use a macro rather than a function so that the line number reported by
// gtest on failure is useful.
#define P(text_, expectedErrorMsg_) \
#define P(kind_, text_, expectedErrorMsg_) \
do { \
TestParseError(text_, actualErrorMsg); \
TestParseError(kind_, text_, actualErrorMsg); \
ASSERT_STREQ(expectedErrorMsg_, actualErrorMsg.get()); \
} while (0)
#define DEFAULT(text_, expectedErrorMsg_) \
P(PrefValueKind::Default, text_, expectedErrorMsg_)
#define USER(text_, expectedErrorMsg_) \
P(PrefValueKind::User, text_, expectedErrorMsg_)
// clang-format off
//-------------------------------------------------------------------------
@ -33,7 +42,7 @@ TEST(PrefsParser, Errors)
//-------------------------------------------------------------------------
// Normal prefs.
P(R"(
DEFAULT(R"(
pref("bool", true);
sticky_pref("int", 123);
user_pref("string", "value");
@ -42,12 +51,12 @@ user_pref("string", "value");
);
// Totally empty input.
P("",
DEFAULT("",
""
);
// Whitespace-only input.
P(R"(
DEFAULT(R"(
)" "\v \t \v \f",
""
@ -60,7 +69,7 @@ user_pref("string", "value");
//-------------------------------------------------------------------------
// Integer overflow errors.
P(R"(
DEFAULT(R"(
pref("int.ok", 2147483647);
pref("int.overflow", 2147483648);
pref("int.ok", +2147483647);
@ -84,7 +93,7 @@ pref("int.overflow", 1234567890987654321);
);
// Other integer errors.
P(R"(
DEFAULT(R"(
pref("int.unexpected", 100foo);
pref("int.ok", 0);
)",
@ -92,7 +101,7 @@ pref("int.ok", 0);
);
// \x00 is not allowed.
P(R"(
DEFAULT(R"(
pref("string.bad-x-escape", "foo\x00bar");
pref("int.ok", 0);
)",
@ -101,7 +110,7 @@ pref("int.ok", 0);
// Various bad things after \x: end of string, punctuation, space, newline,
// EOF.
P(R"(
DEFAULT(R"(
pref("string.bad-x-escape", "foo\x");
pref("string.bad-x-escape", "foo\x,bar");
pref("string.bad-x-escape", "foo\x 12");
@ -116,7 +125,7 @@ pref("string.bad-x-escape", "foo\x)",
);
// Not enough hex digits.
P(R"(
DEFAULT(R"(
pref("string.bad-x-escape", "foo\x1");
pref("int.ok", 0);
)",
@ -124,7 +133,7 @@ pref("int.ok", 0);
);
// Invalid hex digit.
P(R"(
DEFAULT(R"(
pref("string.bad-x-escape", "foo\x1G");
pref("int.ok", 0);
)",
@ -134,7 +143,7 @@ pref("int.ok", 0);
// \u0000 is not allowed.
// (The string literal is broken in two so that MSVC doesn't complain about
// an invalid universal-character-name.)
P(R"(
DEFAULT(R"(
pref("string.bad-u-escape", "foo\)" R"(u0000 bar");
pref("int.ok", 0);
)",
@ -143,7 +152,7 @@ pref("int.ok", 0);
// Various bad things after \u: end of string, punctuation, space, newline,
// EOF.
P(R"(
DEFAULT(R"(
pref("string.bad-u-escape", "foo\u");
pref("string.bad-u-escape", "foo\u,bar");
pref("string.bad-u-escape", "foo\u 1234");
@ -158,7 +167,7 @@ pref("string.bad-u-escape", "foo\u)",
);
// Not enough hex digits.
P(R"(
DEFAULT(R"(
pref("string.bad-u-escape", "foo\u1");
pref("string.bad-u-escape", "foo\u12");
pref("string.bad-u-escape", "foo\u123");
@ -170,7 +179,7 @@ pref("int.ok", 0);
);
// Invalid hex digit.
P(R"(
DEFAULT(R"(
pref("string.bad-u-escape", "foo\u1G34");
pref("int.ok", 0);
)",
@ -180,7 +189,7 @@ pref("int.ok", 0);
// High surrogate not followed by low surrogate.
// (The string literal is broken in two so that MSVC doesn't complain about
// an invalid universal-character-name.)
P(R"(
DEFAULT(R"(
pref("string.bad-u-surrogate", "foo\)" R"(ud83c,blah");
pref("int.ok", 0);
)",
@ -190,7 +199,7 @@ pref("int.ok", 0);
// High surrogate followed by invalid low surrogate value.
// (The string literal is broken in two so that MSVC doesn't complain about
// an invalid universal-character-name.)
P(R"(
DEFAULT(R"(
pref("string.bad-u-surrogate", "foo\)" R"(ud83c\u1234");
pref("int.ok", 0);
)",
@ -198,7 +207,7 @@ pref("int.ok", 0);
);
// Unlike in JavaScript, \b, \f, \t, \v aren't allowed.
P(R"(
DEFAULT(R"(
pref("string.bad-escape", "foo\b");
pref("string.bad-escape", "foo\f");
pref("string.bad-escape", "foo\t");
@ -213,7 +222,7 @@ pref("int.ok", 0);
// Various bad things after \: non-special letter, number, punctuation,
// space, newline, EOF.
P(R"(
DEFAULT(R"(
pref("string.bad-escape", "foo\Q");
pref("string.bad-escape", "foo\1");
pref("string.bad-escape", "foo\,");
@ -232,7 +241,7 @@ pref("string.bad-escape", "foo\)",
// Unterminated string literals.
// Simple case.
P(R"(
DEFAULT(R"(
pref("string.unterminated-string", "foo
)",
"test:3: prefs parse error: unterminated string literal\n"
@ -241,7 +250,7 @@ pref("string.unterminated-string", "foo
// Alternative case; `int` comes after the string and is seen as a keyword.
// The parser then skips to the ';', so no error about the unterminated
// string is issued.
P(R"(
DEFAULT(R"(
pref("string.unterminated-string", "foo);
pref("int.ok", 0);
)",
@ -249,21 +258,21 @@ pref("int.ok", 0);
);
// Mismatched quotes (1).
P(R"(
DEFAULT(R"(
pref("string.unterminated-string", "foo');
)",
"test:3: prefs parse error: unterminated string literal\n"
);
// Mismatched quotes (2).
P(R"(
DEFAULT(R"(
pref("string.unterminated-string", 'foo");
)",
"test:3: prefs parse error: unterminated string literal\n"
);
// Unknown keywords.
P(R"(
DEFAULT(R"(
foo;
preff("string.bad-keyword", true);
ticky_pref("string.bad-keyword", true);
@ -278,33 +287,33 @@ pref("string.bad-keyword", TRUE);
);
// Unterminated C-style comment.
P(R"(
DEFAULT(R"(
/* comment
)",
"test:3: prefs parse error: unterminated /* comment\n"
);
// Malformed comment.
P(R"(
DEFAULT(R"(
/ comment
)",
"test:2: prefs parse error: expected '/' or '*' after '/'\n"
);
// C++-style comment ending in EOF (1).
P(R"(
DEFAULT(R"(
// comment)",
""
);
// C++-style comment ending in EOF (2).
P(R"(
DEFAULT(R"(
//)",
""
);
// Various unexpected characters.
P(R"(
DEFAULT(R"(
pref("unexpected.chars", &true);
pref("unexpected.chars" : true);
@pref("unexpected.chars", true);
@ -320,7 +329,7 @@ pref["unexpected.chars": true];
// All the parsing errors.
//-------------------------------------------------------------------------
P(R"(
DEFAULT(R"(
"pref"("parse.error": true);
pref1("parse.error": true);
pref(123: true);
@ -328,7 +337,9 @@ pref("parse.error" true);
pref("parse.error", pref);
pref("parse.error", -true);
pref("parse.error", +"value");
pref("parse.error", true,);
pref("parse.error", true;
pref("parse.error", true, sticky, locked;
pref("parse.error", true)
pref("int.ok", 1);
pref("parse.error", true))",
@ -339,59 +350,83 @@ pref("parse.error", true))",
"test:6: prefs parse error: expected pref value after ','\n"
"test:7: prefs parse error: expected integer literal after '-'\n"
"test:8: prefs parse error: expected integer literal after '+'\n"
"test:9: prefs parse error: expected ')' after pref value\n"
"test:11: prefs parse error: expected ';' after ')'\n"
"test:12: prefs parse error: expected ';' after ')'\n"
"test:9: prefs parse error: expected pref attribute after ','\n"
"test:10: prefs parse error: expected ',' or ')' after pref value\n"
"test:11: prefs parse error: expected ',' or ')' after pref attribute\n"
"test:13: prefs parse error: expected ';' after ')'\n"
"test:14: prefs parse error: expected ';' after ')'\n"
);
USER(R"(
pref("parse.error", true;
pref("int.ok", 1);
)",
"test:2: prefs parse error: expected ')' after pref value\n"
);
// Parse errors involving unexpected EOF.
P(R"(
DEFAULT(R"(
pref)",
"test:2: prefs parse error: expected '(' after pref specifier\n"
);
P(R"(
DEFAULT(R"(
pref()",
"test:2: prefs parse error: expected pref name after '('\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error")",
"test:2: prefs parse error: expected ',' after pref name\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error",)",
"test:2: prefs parse error: expected pref value after ','\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error", -)",
"test:2: prefs parse error: expected integer literal after '-'\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error", +)",
"test:2: prefs parse error: expected integer literal after '+'\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error", true)",
"test:2: prefs parse error: expected ',' or ')' after pref value\n"
);
USER(R"(
pref("parse.error", true)",
"test:2: prefs parse error: expected ')' after pref value\n"
);
P(R"(
DEFAULT(R"(
pref("parse.error", true,)",
"test:2: prefs parse error: expected pref attribute after ','\n"
);
DEFAULT(R"(
pref("parse.error", true, sticky)",
"test:2: prefs parse error: expected ',' or ')' after pref attribute\n"
);
DEFAULT(R"(
pref("parse.error", true))",
"test:2: prefs parse error: expected ';' after ')'\n"
);
// This is something we saw in practice with the old parser, which allowed
// repeated semicolons.
P(R"(
DEFAULT(R"(
pref("parse.error", true);;
pref("parse.error", true);;;
pref("parse.error", true);;;;
pref("parse.error", true, locked);;;
pref("parse.error", true, sticky, locked);;;;
pref("int.ok", 0);
)",
"test:2: prefs parse error: expected pref specifier at start of pref definition\n"
@ -411,24 +446,24 @@ pref("int.ok", 0);
// the error is on line 4. (Note: these ones don't use raw string literals
// because MSVC somehow swallows any \r that appears in them.)
P("\n \r \r\n bad",
DEFAULT("\n \r \r\n bad",
"test:4: prefs parse error: unknown keyword\n"
);
P("#\n#\r#\r\n bad",
DEFAULT("#\n#\r#\r\n bad",
"test:4: prefs parse error: unknown keyword\n"
);
P("//\n//\r//\r\n bad",
DEFAULT("//\n//\r//\r\n bad",
"test:4: prefs parse error: unknown keyword\n"
);
P("/*\n \r \r\n*/ bad",
DEFAULT("/*\n \r \r\n*/ bad",
"test:4: prefs parse error: unknown keyword\n"
);
// Note: the escape sequences do *not* affect the line number.
P("pref(\"foo\\n\n foo\\r\r foo\\r\\n\r\n foo\", bad);",
DEFAULT("pref(\"foo\\n\n foo\\r\r foo\\r\\n\r\n foo\", bad);",
"test:4: prefs parse error: unknown keyword\n"
);

View File

@ -1,5 +1,6 @@
// Note: this file tests only valid syntax. See
// modules/libpref/test/gtest/Parser.cpp for tests if invalid syntax.
// Note: this file tests only valid syntax (of user pref files, not default
// pref files). See modules/libpref/test/gtest/Parser.cpp for tests if invalid
// syntax.
#
# comment
@ -50,6 +51,10 @@ pref
pref("pref", true);
sticky_pref("sticky_pref", true);
user_pref("user_pref", true);
pref("sticky_pref2", true, sticky);
pref("locked_pref", true, locked);
pref("locked_sticky_pref", true, locked, sticky,sticky,
locked, locked, locked);
pref("bool.true", true);
pref("bool.false", false);

View File

@ -0,0 +1,2 @@
pref("testPref.unlocked.int", 333);
pref("testPref.locked.int", 444, locked);

View File

@ -0,0 +1,3 @@
// testPrefLocked.js defined this pref as a locked pref.
// Changing a locked pref has no effect.
user_pref("testPref.locked.int", 555);

View File

@ -0,0 +1,45 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/ */
// 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;
add_test(function notChangedFromAPI() {
ps.resetPrefs();
ps.readDefaultPrefsFromFile(do_get_file("data/testPrefLocked.js"));
Assert.strictEqual(ps.getIntPref("testPref.unlocked.int"), 333);
Assert.strictEqual(ps.getIntPref("testPref.locked.int"), 444);
// Unlocked pref: can set the user value, which is used upon reading.
ps.setIntPref("testPref.unlocked.int", 334);
Assert.ok(ps.prefHasUserValue("testPref.unlocked.int"), "has a user value");
Assert.strictEqual(ps.getIntPref("testPref.unlocked.int"), 334);
// Locked pref: can set the user value, but the default value is used upon
// reading.
ps.setIntPref("testPref.locked.int", 445);
Assert.ok(ps.prefHasUserValue("testPref.locked.int"), "has a user value");
Assert.strictEqual(ps.getIntPref("testPref.locked.int"), 444);
// After unlocking, the user value is used.
ps.unlockPref("testPref.locked.int");
Assert.ok(ps.prefHasUserValue("testPref.locked.int"), "has a user value");
Assert.strictEqual(ps.getIntPref("testPref.locked.int"), 445);
run_next_test();
});
add_test(function notChangedFromUserPrefs() {
ps.resetPrefs();
ps.readDefaultPrefsFromFile(do_get_file("data/testPrefLocked.js"));
ps.readUserPrefsFromFile(do_get_file("data/testPrefLockedUser.js"));
Assert.strictEqual(ps.getIntPref("testPref.unlocked.int"), 333);
Assert.strictEqual(ps.getIntPref("testPref.locked.int"), 444);
run_next_test();
});

View File

@ -10,7 +10,7 @@ function run_test() {
var prefs = ps.getBranch(null);
ps.resetPrefs();
ps.readUserPrefsFromFile(do_get_file('data/testParser.js'));
ps.readDefaultPrefsFromFile(do_get_file('data/testParser.js'));
Assert.equal(ps.getBoolPref("comment1"), true);
Assert.equal(ps.getBoolPref("comment2"), true);
@ -19,6 +19,11 @@ function run_test() {
Assert.equal(ps.getBoolPref("pref"), true);
Assert.equal(ps.getBoolPref("sticky_pref"), true);
Assert.equal(ps.getBoolPref("user_pref"), true);
Assert.equal(ps.getBoolPref("sticky_pref2"), true);
Assert.equal(ps.getBoolPref("locked_pref"), true);
Assert.equal(ps.getBoolPref("locked_sticky_pref"), true);
Assert.equal(ps.prefIsLocked("locked_pref"), true);
Assert.equal(ps.prefIsLocked("locked_sticky_pref"), true);
Assert.equal(ps.getBoolPref("bool.true"), true);
Assert.equal(ps.getBoolPref("bool.false"), false);

View File

@ -6,12 +6,17 @@ ChromeUtils.import("resource://gre/modules/Services.jsm");
const ps = Services.prefs;
// A little helper to reset the service and load some pref files
function resetAndLoad(filenames) {
// A little helper to reset the service and load one pref file.
function resetAndLoadDefaults() {
ps.resetPrefs();
for (let filename of filenames) {
ps.readUserPrefsFromFile(do_get_file(filename));
}
ps.readDefaultPrefsFromFile(do_get_file("data/testPrefSticky.js"));
}
// A little helper to reset the service and load two pref files.
function resetAndLoadAll() {
ps.resetPrefs();
ps.readDefaultPrefsFromFile(do_get_file("data/testPrefSticky.js"));
ps.readUserPrefsFromFile(do_get_file("data/testPrefStickyUser.js"));
}
// A little helper that saves the current state to a file in the profile
@ -39,7 +44,7 @@ function run_test() {
// A sticky pref should not be written if the value is unchanged.
add_test(function notWrittenWhenUnchanged() {
resetAndLoad(["data/testPrefSticky.js"]);
resetAndLoadDefaults();
Assert.strictEqual(ps.getBoolPref("testPref.unsticky.bool"), true);
Assert.strictEqual(ps.getBoolPref("testPref.sticky.bool"), false);
@ -61,7 +66,7 @@ add_test(function writtenOnceLoadedWithoutChange() {
// Load the same pref file *as well as* a pref file that has a user_pref for
// our sticky with the default value. It should be re-written without us
// touching it.
resetAndLoad(["data/testPrefSticky.js", "data/testPrefStickyUser.js"]);
resetAndLoadAll();
// reset and re-read what we just wrote - it should be written.
saveAndReload();
Assert.strictEqual(ps.getBoolPref("testPref.sticky.bool"), false,
@ -73,7 +78,7 @@ add_test(function writtenOnceLoadedWithoutChange() {
add_test(function writtenOnceLoadedWithChangeNonDefault() {
// Load the same pref file *as well as* a pref file that has a user_pref for
// our sticky - then change the pref. It should be written.
resetAndLoad(["data/testPrefSticky.js", "data/testPrefStickyUser.js"]);
resetAndLoadAll();
// Set a new val and check we wrote it.
ps.setBoolPref("testPref.sticky.bool", false);
saveAndReload();
@ -86,7 +91,7 @@ add_test(function writtenOnceLoadedWithChangeNonDefault() {
add_test(function writtenOnceLoadedWithChangeNonDefault() {
// Load the same pref file *as well as* a pref file that has a user_pref for
// our sticky - then change the pref. It should be written.
resetAndLoad(["data/testPrefSticky.js", "data/testPrefStickyUser.js"]);
resetAndLoadAll();
// Set a new val and check we wrote it.
ps.setBoolPref("testPref.sticky.bool", true);
saveAndReload();
@ -102,7 +107,7 @@ add_test(function writtenOnceLoadedWithChangeNonDefault() {
// the pref had never changed.)
add_test(function hasUserValue() {
// sticky pref without user value.
resetAndLoad(["data/testPrefSticky.js"]);
resetAndLoadDefaults();
Assert.strictEqual(ps.getBoolPref("testPref.sticky.bool"), false);
Assert.ok(!ps.prefHasUserValue("testPref.sticky.bool"),
"should not initially reflect a user value");
@ -121,7 +126,7 @@ add_test(function hasUserValue() {
ps.setBoolPref("testPref.sticky.bool", false, "expected default");
// And make sure the pref immediately reflects a user value after load.
resetAndLoad(["data/testPrefSticky.js", "data/testPrefStickyUser.js"]);
resetAndLoadAll();
Assert.strictEqual(ps.getBoolPref("testPref.sticky.bool"), false);
Assert.ok(ps.prefHasUserValue("testPref.sticky.bool"),
"should have a user value when loaded value is the default");
@ -132,7 +137,7 @@ add_test(function hasUserValue() {
add_test(function clearUserPref() {
// load things such that we have a sticky value which is the same as the
// default.
resetAndLoad(["data/testPrefSticky.js", "data/testPrefStickyUser.js"]);
resetAndLoadAll();
ps.clearUserPref("testPref.sticky.bool");
// Once we save prefs the sticky pref should no longer be written.
@ -153,7 +158,7 @@ add_test(function clearUserPref() {
// even if the value has not)
add_test(function observerFires() {
// load things so there's no sticky value.
resetAndLoad(["data/testPrefSticky.js"]);
resetAndLoadDefaults();
function observe(subject, topic, data) {
Assert.equal(data, "testPref.sticky.bool");

View File

@ -11,6 +11,8 @@ support-files =
[test_bug790374.js]
[test_stickyprefs.js]
support-files = data/testPrefSticky.js data/testPrefStickyUser.js
[test_locked_file_prefs.js]
support-files = data/testPrefLocked.js data/testPrefLockedUser.js
[test_changeType.js]
[test_defaultValues.js]
[test_dirtyPrefs.js]

View File

@ -25,7 +25,7 @@ function makePersona(id) {
add_task(async function run_test() {
_("Test fixtures.");
// read our custom prefs file before doing anything.
Services.prefs.readUserPrefsFromFile(do_get_file("prefs_test_prefs_store.js"));
Services.prefs.readDefaultPrefsFromFile(do_get_file("prefs_test_prefs_store.js"));
let engine = Service.engineManager.get("prefs");
let store = engine._store;