fixes bug 98533 "use lightweight parser to read pref files" r=dougt sr=brendan

This commit is contained in:
darin%meer.net 2003-09-16 16:19:00 +00:00
Родитель 3b26be75f0
Коммит 5ff9a74122
7 изменённых файлов: 660 добавлений и 389 удалений

Просмотреть файл

@ -60,6 +60,7 @@ CPPSRCS = nsPref.cpp \
nsPrefsFactory.cpp \
nsSafeSaveFile.cpp \
prefapi.cpp \
prefread.cpp \
$(NULL)
ifdef MOZ_PROFILESHARING

Просмотреть файл

@ -220,7 +220,6 @@ NS_IMETHODIMP nsPrefService::ReadUserPrefs(nsIFile *aFile)
NotifyServiceObservers(NS_PREFSERVICE_READ_TOPIC_ID);
JS_MaybeGC(gMochaContext);
} else {
rv = ReadAndOwnUserPrefFile(aFile);
}
@ -627,12 +626,11 @@ static nsresult openPrefFile(nsIFile* aFile, PRBool aIsErrorFatal,
if (NS_FAILED(rv))
return rv;
// XXX maybe we should read the file in chunks instead??
readBuf = (char *)PR_Malloc(fileSize);
if (!readBuf)
return NS_ERROR_OUT_OF_MEMORY;
JS_BeginRequest(gMochaContext);
PRUint32 amtRead = 0;
rv = inStr->Read(readBuf, fileSize, &amtRead);
NS_ASSERTION((amtRead == fileSize), "failed to read the entire prefs file!!");
@ -654,8 +652,6 @@ static nsresult openPrefFile(nsIFile* aFile, PRBool aIsErrorFatal,
}
PR_Free(readBuf);
JS_EndRequest(gMochaContext);
return rv;
}
@ -692,7 +688,7 @@ inplaceSortCallback(const void *data1, const void *data2, void *privateData)
}
//----------------------------------------------------------------------------------------
JSBool pref_InitInitialObjects()
PRBool pref_InitInitialObjects()
// Initialize default preference JavaScript buffers from
// appropriate TEXT resources
//----------------------------------------------------------------------------------------
@ -726,7 +722,7 @@ JSBool pref_InitInitialObjects()
rv = NS_GetSpecialDirectory(NS_APP_PREF_DEFAULTS_50_DIR, getter_AddRefs(defaultPrefDir));
if (NS_FAILED(rv))
return JS_FALSE;
return PR_FALSE;
nsIFile **defaultPrefFiles = (nsIFile **)nsMemory::Alloc(INITIAL_MAX_DEFAULT_PREF_FILES * sizeof(nsIFile *));
int maxDefaultPrefFiles = INITIAL_MAX_DEFAULT_PREF_FILES;
@ -737,13 +733,13 @@ JSBool pref_InitInitialObjects()
rv = defaultPrefDir->GetDirectoryEntries(getter_AddRefs(dirIterator));
if (!dirIterator) {
NS_ASSERTION(NS_SUCCEEDED(rv), "ERROR: Could not make a directory iterator.");
return JS_FALSE;
return PR_FALSE;
}
dirIterator->HasMoreElements(&hasMoreElements);
if (!hasMoreElements) {
NS_ASSERTION(NS_SUCCEEDED(rv), "ERROR: Prefs directory is empty.");
return JS_FALSE;
return PR_FALSE;
}
while (hasMoreElements) {
@ -802,29 +798,5 @@ JSBool pref_InitInitialObjects()
}
}
JS_MaybeGC(gMochaContext);
return JS_TRUE;
return PR_TRUE;
}
JSRuntime* PREF_GetJSRuntime()
{
nsresult rv;
if (!gJSRuntimeService) {
rv = CallGetService("@mozilla.org/js/xpc/RuntimeService;1",
&gJSRuntimeService);
if (NS_FAILED(rv)) {
NS_WARNING("nsJSRuntimeService is missing");
gJSRuntimeService = nsnull;
return nsnull;
}
}
JSRuntime* rt;
rv = gJSRuntimeService->GetRuntime(&rt);
if (NS_SUCCEEDED(rv))
return rt;
return nsnull;
}

Просмотреть файл

@ -37,8 +37,8 @@
#include "prefapi.h"
#include "prefapi_private_data.h"
#include "prefread.h"
#include "nsReadableUtils.h"
#include "jsapi.h"
#include "nsCRT.h"
#define PL_ARENA_CONST_ALIGN_MASK 3
@ -82,8 +82,6 @@
#include "Alert.h"
#endif
extern JSRuntime* PREF_GetJSRuntime();
#define BOGUS_DEFAULT_INT_PREF_VALUE (-5632)
#define BOGUS_DEFAULT_BOOL_PREF_VALUE (-2)
@ -117,54 +115,11 @@ matchPrefEntry(PLDHashTable*, const PLDHashEntryHdr* entry,
return (strcmp(prefEntry->key, otherKey) == 0);
}
PR_STATIC_CALLBACK(JSBool) pref_NativeDefaultPref(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval);
PR_STATIC_CALLBACK(JSBool) pref_NativeUserPref(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval);
/*----------------------------------------------------------------------------------------*/
JS_STATIC_DLL_CALLBACK(JSBool)
global_enumerate(JSContext *cx, JSObject *obj)
{
return JS_EnumerateStandardClasses(cx, obj);
}
JS_STATIC_DLL_CALLBACK(JSBool)
global_resolve(JSContext *cx, JSObject *obj, jsval id)
{
JSBool resolved;
return JS_ResolveStandardClass(cx, obj, id, &resolved);
}
JSContext * gMochaContext = NULL;
PRBool gErrorOpeningUserPrefs = PR_FALSE;
PLDHashTable gHashTable = { nsnull };
static PLArenaPool gPrefNameArena;
PRBool gDirty = PR_FALSE;
static JSRuntime * gMochaTaskState = NULL;
static JSObject * gMochaPrefObject = NULL;
static JSObject * gGlobalConfigObject = NULL;
static JSClass global_class = {
"global", 0,
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
global_enumerate, global_resolve, JS_ConvertStub, JS_FinalizeStub,
JSCLASS_NO_OPTIONAL_MEMBERS
};
static JSClass autoconf_class = {
"PrefConfig", 0,
JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub,
JSCLASS_NO_OPTIONAL_MEMBERS
};
static JSPropertySpec autoconf_props[] = {
{0,0,0,0,0}
};
static JSFunctionSpec autoconf_methods[] = {
{ "pref", pref_NativeDefaultPref, 2,0,0 },
{ "user_pref", pref_NativeUserPref, 2,0,0 },
{ NULL, NULL, 0,0,0 }
};
static struct CallbackNode* gCallbacks = NULL;
static PRBool gCallbacksEnabled = PR_FALSE;
static PRBool gIsAnyPrefLocked = PR_FALSE;
@ -218,7 +173,7 @@ static char *ArenaStrDup(const char* str, PLArenaPool* aArena)
#define PREF_HAS_USER_VALUE(pref) ((pref)->flags & PREF_USERSET)
#define PREF_TYPE(pref) (PrefType)((pref)->flags & PREF_VALUETYPE_MASK)
static JSBool pref_HashJSPref(unsigned int argc, jsval *argv, PrefAction action);
static void pref_ReaderCallback(void *closure, const char *pref, PrefValue, PrefType, PrefAction);
static PRBool pref_ValueChanged(PrefValue oldValue, PrefValue newValue, PrefType type);
/* -- Privates */
@ -233,17 +188,12 @@ struct CallbackNode {
static PrefResult pref_DoCallback(const char* changed_pref);
PR_STATIC_CALLBACK(JSBool) pref_BranchCallback(JSContext *cx, JSScript *script);
PR_STATIC_CALLBACK(void) pref_ErrorReporter(JSContext *cx, const char *message,JSErrorReport *report);
static void pref_Alert(char* msg);
static PrefResult pref_HashPref(const char *key, PrefValue value, PrefType type, PrefAction action);
static inline PrefHashEntry* pref_HashTableLookup(const void *key);
PRBool PREF_Init(const char *filename)
{
PRBool ok = PR_TRUE, request = PR_FALSE;
if (!gHashTable.ops) {
if (!PL_DHashTableInit(&gHashTable, &pref_HashTableOps, nsnull,
sizeof(PrefHashEntry), 1024))
@ -252,71 +202,13 @@ PRBool PREF_Init(const char *filename)
PL_INIT_ARENA_POOL(&gPrefNameArena, "PrefNameArena",
PREFNAME_ARENA_SIZE);
}
if (!gMochaTaskState)
{
gMochaTaskState = PREF_GetJSRuntime();
if (!gMochaTaskState)
return PR_FALSE;
}
if (!gMochaContext)
{
ok = PR_FALSE;
gMochaContext = JS_NewContext(gMochaTaskState, 8192);
if (!gMochaContext)
goto out;
JS_BeginRequest(gMochaContext);
request = PR_TRUE;
gGlobalConfigObject = JS_NewObject(gMochaContext, &global_class, NULL,
NULL);
if (!gGlobalConfigObject)
goto out;
/* MLM - need a global object for set version call now. */
JS_SetGlobalObject(gMochaContext, gGlobalConfigObject);
JS_SetVersion(gMochaContext, JSVERSION_1_5);
JS_SetBranchCallback(gMochaContext, pref_BranchCallback);
JS_SetErrorReporter(gMochaContext, NULL);
gMochaPrefObject = JS_DefineObject(gMochaContext,
gGlobalConfigObject,
"PrefConfig",
&autoconf_class,
NULL,
JSPROP_ENUMERATE|JSPROP_READONLY);
if (gMochaPrefObject)
{
if (!JS_DefineProperties(gMochaContext,
gMochaPrefObject,
autoconf_props))
{
goto out;
}
if (!JS_DefineFunctions(gMochaContext,
gMochaPrefObject,
autoconf_methods))
{
goto out;
}
}
ok = pref_InitInitialObjects();
}
out:
if (request)
JS_EndRequest(gMochaContext);
PRBool ok = pref_InitInitialObjects();
if (!ok)
gErrorOpeningUserPrefs = PR_TRUE;
return ok;
} /*PREF_Init*/
}
/* Frees the callback list. */
void PREF_Cleanup()
@ -339,104 +231,31 @@ void PREF_Cleanup()
/* Frees up all the objects except the callback list. */
void PREF_CleanupPrefs()
{
gMochaTaskState = NULL; /* We -don't- destroy this. */
if (gMochaContext) {
JSRuntime *rt;
gMochaPrefObject = NULL;
if (gGlobalConfigObject) {
JS_SetGlobalObject(gMochaContext, NULL);
gGlobalConfigObject = NULL;
}
rt = PREF_GetJSRuntime();
if (rt == JS_GetRuntime(gMochaContext)) {
JS_DestroyContext(gMochaContext);
gMochaContext = NULL;
} else {
#ifdef DEBUG
fputs("Runtime mismatch, so leaking context!\n", stderr);
#endif
}
}
if (gHashTable.ops) {
PL_DHashTableFinish(&gHashTable);
gHashTable.ops = nsnull;
PL_FinishArenaPool(&gPrefNameArena);
}
if (gSavedLine)
free(gSavedLine);
gSavedLine = NULL;
}
/* This is more recent than the below 3 routines which should be obsoleted */
JSBool
PRBool
PREF_EvaluateConfigScript(const char * js_buffer, size_t length,
const char* filename, PRBool bGlobalContext, PRBool bCallbacks,
PRBool skipFirstLine)
{
JSBool ok;
jsval result;
JSObject* scope;
JSErrorReporter errReporter;
if (bGlobalContext)
scope = gGlobalConfigObject;
else
scope = gMochaPrefObject;
if (!gMochaContext || !scope)
return JS_FALSE;
NS_ASSERTION(bCallbacks, "no support for disabling callbacks");
errReporter = JS_SetErrorReporter(gMochaContext, pref_ErrorReporter);
gCallbacksEnabled = bCallbacks;
PrefParseState ps;
PREF_InitParseState(&ps, pref_ReaderCallback, NULL);
PREF_ParseBuf(&ps, js_buffer, length);
PREF_FinalizeParseState(&ps);
if (skipFirstLine)
{
/* In order to protect the privacy of the JavaScript preferences file
* from loading by the browser, we make the first line unparseable
* by JavaScript. We must skip that line here before executing
* the JavaScript code.
*/
unsigned int i=0;
while (i < length)
{
char c = js_buffer[i++];
if (c == '\r')
{
if (js_buffer[i] == '\n')
i++;
break;
}
if (c == '\n')
break;
}
/* Free up gSavedLine to avoid MLK. */
if (gSavedLine)
free(gSavedLine);
gSavedLine = (char *)malloc(i + 1);
if (!gSavedLine)
return JS_FALSE;
memcpy(gSavedLine, js_buffer, i);
gSavedLine[i] = '\0';
length -= i;
js_buffer += i;
}
JS_BeginRequest(gMochaContext);
ok = JS_EvaluateScript(gMochaContext, scope,
js_buffer, length, filename, 0, &result);
JS_EndRequest(gMochaContext);
gCallbacksEnabled = PR_TRUE; /* ?? want to enable after reading user/lock file */
JS_SetErrorReporter(gMochaContext, errReporter);
return ok;
return PR_TRUE;
}
// note that this appends to aResult, and does not assign!
@ -1057,18 +876,6 @@ PREF_GetPrefType(const char *pref_name)
return PREF_INVALID;
}
PR_STATIC_CALLBACK(JSBool) pref_NativeDefaultPref
(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval)
{
return pref_HashJSPref(argc, argv, PREF_SETDEFAULT);
}
PR_STATIC_CALLBACK(JSBool) pref_NativeUserPref
(JSContext *cx, JSObject *obj, unsigned int argc, jsval *argv, jsval *rval)
{
return pref_HashJSPref(argc, argv, PREF_SETUSER);
}
/* -- */
PRBool
@ -1153,141 +960,11 @@ static PrefResult pref_DoCallback(const char* changed_pref)
return result;
}
#define MAYBE_GC_BRANCH_COUNT_MASK 4095
PR_STATIC_CALLBACK(JSBool)
pref_BranchCallback(JSContext *cx, JSScript *script)
{
static PRUint32 count = 0;
/*
* If we've been running for a long time, then try a GC to
* free up some memory.
*/
if ( (++count & MAYBE_GC_BRANCH_COUNT_MASK) == 0 )
JS_MaybeGC(cx);
return JS_TRUE;
}
/* copied from libmocha */
void
pref_ErrorReporter(JSContext *cx, const char *message,
JSErrorReport *report)
static void pref_ReaderCallback(void *closure,
const char *pref,
PrefValue value,
PrefType type,
PrefAction action)
{
char *last;
const char *s, *t;
last = PR_sprintf_append(0, "An error occurred reading the startup configuration file. "
"Please contact your administrator.");
#if defined(XP_MAC)
/* StandardAlert doesn't handle linefeeds. Use spaces to avoid garbage characters. */
last = PR_sprintf_append(last, " ");
#else
last = PR_sprintf_append(last, NS_LINEBREAK NS_LINEBREAK);
#endif
if (!report)
last = PR_sprintf_append(last, "%s\n", message);
else
{
if (report->filename)
last = PR_sprintf_append(last, "%s, ",
report->filename, report->filename);
if (report->lineno)
last = PR_sprintf_append(last, "line %u: ", report->lineno);
last = PR_sprintf_append(last, "%s. ", message);
if (report->linebuf)
{
for (s = t = report->linebuf; *s != '\0'; s = t)
{
for (; t != report->tokenptr && *t != '<' && *t != '\0'; t++)
;
last = PR_sprintf_append(last, "%.*s", t - s, s);
if (*t == '\0')
break;
last = PR_sprintf_append(last, (*t == '<') ? "" : "%c", *t);
t++;
}
}
}
if (last)
{
pref_Alert(last);
PR_Free(last);
}
pref_HashPref(pref, value, type, action);
}
#if defined(XP_MAC)
#include <Dialogs.h>
#include <Memory.h>
void pref_Alert(char* msg)
{
Str255 pmsg;
SInt16 itemHit;
pmsg[0] = PL_strlen(msg);
BlockMoveData(msg, pmsg + 1, pmsg[0]);
StandardAlert(kAlertPlainAlert, "\pConfiguration Warning", pmsg, NULL, &itemHit);
}
#else
/* Platform specific alert messages */
void pref_Alert(char* msg)
{
#if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
#if defined(XP_UNIX) || defined(XP_OS2) || defined(XP_BEOS)
if ( getenv("NO_PREF_SPAM") == NULL )
#endif
fputs(msg, stderr);
#endif
#if defined(XP_WIN)
MessageBox (NULL, msg, "Configuration Warning", MB_OK);
#elif defined(XP_OS2)
WinMessageBox (HWND_DESKTOP, 0, msg, "Configuration Warning", 0, MB_WARNING | MB_OK | MB_APPLMODAL | MB_MOVEABLE);
#elif defined(XP_BEOS)
BAlert *alert = new BAlert("Configuration Warning", msg, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_WARNING_ALERT);
// Calling Go() runs the BAlert and waits for the user to close the window. Go will delete the BAlert when it finishes.
alert->Go();
#endif
}
#endif
/*--------------------------------------------------------------------------------------*/
static JSBool pref_HashJSPref(unsigned int argc, jsval *argv, PrefAction action)
/* Native implementations of JavaScript functions
pref -> pref_NativeDefaultPref
userPref -> pref_NativeUserPref
*--------------------------------------------------------------------------------------*/
{
if (argc >= 2 && JSVAL_IS_STRING(argv[0]))
{
PrefValue value;
const char *key = JS_GetStringBytes(JSVAL_TO_STRING(argv[0]));
if (JSVAL_IS_STRING(argv[1]))
{
value.stringVal = JS_GetStringBytes(JSVAL_TO_STRING(argv[1]));
pref_HashPref(key, value, PREF_STRING, action);
}
else if (JSVAL_IS_INT(argv[1]))
{
value.intVal = JSVAL_TO_INT(argv[1]);
pref_HashPref(key, value, PREF_INT, action);
}
else if (JSVAL_IS_BOOLEAN(argv[1]))
{
value.boolVal = JSVAL_TO_BOOLEAN(argv[1]);
pref_HashPref(key, value, PREF_BOOL, action);
}
}
return JS_TRUE;
}

Просмотреть файл

@ -42,11 +42,8 @@
#define PREFAPI_H
#include "prtypes.h"
#include "jsapi.h"
#include "pldhash.h"
#define NEW_PREF_ARCH
#if defined(VMS)
/* Deal with case naming conflicts */
#define pref_CopyCharPref prefl_CopyCharPref
@ -58,21 +55,12 @@
NSPR_BEGIN_EXTERN_C
/*
// <font color=blue>
// Error codes
// </font>
*/
typedef int PROFILE_ERROR;
typedef union
{
char* stringVal;
PRInt32 intVal;
PRBool boolVal;
} PrefValue;
struct PrefHashEntry : PLDHashEntryHdr
{
@ -146,7 +134,7 @@ PREF_Cleanup();
void
PREF_CleanupPrefs();
JSBool
PRBool
PREF_EvaluateConfigScript(const char * js_buffer, size_t length,
const char* filename, PRBool bGlobalContext, PRBool bCallbacks,
PRBool skipFirstLine);

Просмотреть файл

@ -37,7 +37,6 @@
/* Data shared between prefapi.c and nsPref.cpp */
extern JSContext * gMochaContext;
extern PRBool gErrorOpeningUserPrefs;
extern PLDHashTable gHashTable;
extern PRBool gDirty;
@ -53,4 +52,4 @@ struct pref_saveArgs {
PLDHashOperator PR_CALLBACK pref_savePref(PLDHashTable*, PLDHashEntryHdr *, PRUint32, void *arg);
int PR_CALLBACK pref_CompareStrings(const void *v1, const void *v2, void* unused);
extern JSBool pref_InitInitialObjects(void);
extern PRBool pref_InitInitialObjects(void);

Просмотреть файл

@ -0,0 +1,506 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla.
*
* The Initial Developer of the Original Code is Darin Fisher.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@meer.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "prefread.h"
#ifdef TEST_PREFREAD
#include <stdio.h>
#define NS_WARNING(_s) printf(">>> " _s "!\n")
#else
#include "nsDebug.h" // for NS_WARNING
#endif
/* pref parser states */
enum {
PREF_PARSE_INIT,
PREF_PARSE_MATCH_STRING,
PREF_PARSE_UNTIL_NAME,
PREF_PARSE_NAME,
PREF_PARSE_UNTIL_COMMA,
PREF_PARSE_VALUE,
PREF_PARSE_ESC_STRING_VALUE,
PREF_PARSE_COMMENT_MAYBE_START,
PREF_PARSE_COMMENT_BLOCK,
PREF_PARSE_COMMENT_BLOCK_MAYBE_END,
PREF_PARSE_UNTIL_OPEN_PAREN,
PREF_PARSE_UNTIL_CLOSE_PAREN,
PREF_PARSE_UNTIL_SEMICOLON,
PREF_PARSE_UNTIL_EOL
};
static const char kUserPref[] = "user_pref";
static const char kPref[] = "pref";
static const char kTrue[] = "true";
static const char kFalse[] = "false";
/**
* pref_GrowBuf
*
* this function will increase the size of the buffer owned
* by the given pref parse state. the only requirement is
* that it increase the buffer by at least one byte, but we
* use a simple doubling algorithm.
*
* this buffer is used to store partial pref lines. it is
* freed when the parse state is destroyed.
*
* @param ps
* parse state instance
*
* this function updates all pointers that reference an
* address within lb since realloc may relocate the buffer.
*
* @return PR_FALSE if insufficient memory.
*/
static PRBool
pref_GrowBuf(PrefParseState *ps)
{
int bufLen, curPos, valPos;
bufLen = ps->lbend - ps->lb;
curPos = ps->lbcur - ps->lb;
valPos = ps->vb - ps->lb;
if (bufLen == 0)
bufLen = 128; /* default buffer size */
else
bufLen <<= 1; /* double buffer size */
#ifdef TEST_PREFREAD
fprintf(stderr, ">>> realloc(%d)\n", bufLen);
#endif
ps->lb = (char*) realloc(ps->lb, bufLen);
if (!ps->lb)
return PR_FALSE;
ps->lbcur = ps->lb + curPos;
ps->lbend = ps->lb + bufLen;
ps->vb = ps->lb + valPos;
return PR_TRUE;
}
void
PREF_InitParseState(PrefParseState *ps, PrefReader reader, void *closure)
{
memset(ps, 0, sizeof(*ps));
ps->reader = reader;
ps->closure = closure;
}
void
PREF_FinalizeParseState(PrefParseState *ps)
{
if (ps->lb)
free(ps->lb);
}
/**
* Pseudo-BNF
* ----------
* function = LJUNK function-name JUNK function-args
* function-name = "user_pref" | "pref"
* function-args = "(" JUNK pref-name JUNK "," JUNK pref-value JUNK ")" JUNK ";"
* pref-name = quoted-string
* pref-value = quoted-string | "true" | "false" | integer-value
* JUNK = *(WS | comment-block | comment-line)
* LJUNK = *(WS | comment-block | comment-line | bcomment-line)
* WS = SP | HT | LF | VT | FF | CR
* SP = <US-ASCII SP, space (32)>
* HT = <US-ASCII HT, horizontal-tab (9)>
* LF = <US-ASCII LF, linefeed (10)>
* VT = <US-ASCII HT, vertical-tab (11)>
* FF = <US-ASCII FF, form-feed (12)>
* CR = <US-ASCII CR, carriage return (13)>
* comment-block = <C/C++ style comment block>
* comment-line = <C++ style comment line>
* bcomment-line = <bourne-shell style comment line>
*/
PRBool
PREF_ParseBuf(PrefParseState *ps, const char *buf, int bufLen)
{
PrefValue value;
PrefType type;
PrefAction action;
const char *end;
char c;
int state;
state = ps->state;
for (end = buf + bufLen; buf != end; ++buf) {
c = *buf;
switch (state) {
/* initial state */
case PREF_PARSE_INIT:
if (ps->lbcur != ps->lb) { /* reset state */
ps->lbcur = ps->lb;
ps->vb = NULL;
ps->vtype = PREF_INVALID;
ps->fuser = PR_FALSE;
}
switch (c) {
case '/': /* begin comment block or line? */
state = PREF_PARSE_COMMENT_MAYBE_START;
break;
case '#': /* accept shell style comments */
state = PREF_PARSE_UNTIL_EOL;
break;
case 'u': /* indicating user_pref */
case 'p': /* indicating pref */
ps->smatch = (c == 'u' ? kUserPref : kPref);
ps->sindex = 1;
ps->nextstate = PREF_PARSE_UNTIL_OPEN_PAREN;
state = PREF_PARSE_MATCH_STRING;
break;
/* else skip char */
}
break;
/* string matching */
case PREF_PARSE_MATCH_STRING:
if (c == ps->smatch[ps->sindex++]) {
/* if we've matched all characters, then move to next state. */
if (ps->smatch[ps->sindex] == '\0') {
state = ps->nextstate;
ps->nextstate = PREF_PARSE_INIT; /* reset next state */
}
/* else wait for next char */
}
else {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
/* name parsing */
case PREF_PARSE_UNTIL_NAME:
if (c == '\"') {
ps->fuser = (ps->smatch == kUserPref);
state = PREF_PARSE_NAME;
}
else if (c == '/') { /* allow embedded comment */
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
case PREF_PARSE_NAME:
if (ps->lbcur == ps->lbend && !pref_GrowBuf(ps))
return PR_FALSE; /* out of memory */
if (c == '\"') {
*ps->lbcur++ = '\0';
state = PREF_PARSE_UNTIL_COMMA;
}
else
*ps->lbcur++ = c;
break;
/* parse until we find a comma separating name and value */
case PREF_PARSE_UNTIL_COMMA:
if (c == ',') {
ps->vb = ps->lbcur;
state = PREF_PARSE_VALUE;
}
else if (c == '/') { /* allow embedded comment */
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
/* value parsing */
case PREF_PARSE_VALUE:
if (ps->vtype == PREF_INVALID) {
if (c == '\"') {
ps->vtype = PREF_STRING;
break; /* wait next char */
}
else if (c == 't' || c == 'f') {
ps->vb = (char *) (c == 't' ? kTrue : kFalse);
ps->vtype = PREF_BOOL;
ps->smatch = ps->vb;
ps->sindex = 1;
ps->nextstate = PREF_PARSE_UNTIL_CLOSE_PAREN;
state = PREF_PARSE_MATCH_STRING;
break;
}
else if (isdigit(c) || (c == '-') || (c == '+')) {
ps->vtype = PREF_INT;
/* fall through and write c to line buffer... */
}
else if (c == '/') { /* allow embedded comment */
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
break;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
}
if (ps->lbcur == ps->lbend && !pref_GrowBuf(ps))
return PR_FALSE; /* out of memory */
switch (ps->vtype) {
case PREF_STRING:
/* skip char if start of escape sequence */
if (c == '\\')
state = PREF_PARSE_ESC_STRING_VALUE;
else if (c != '\"')
*ps->lbcur++ = c;
else {
*ps->lbcur++ = '\0';
state = PREF_PARSE_UNTIL_CLOSE_PAREN;
}
break;
case PREF_INT:
if (isdigit(c) || (c == '-') || (c == '+'))
*ps->lbcur++ = c;
else {
*ps->lbcur++ = '\0'; /* stomp null terminator; we are done. */
if (c == ')')
state = PREF_PARSE_UNTIL_SEMICOLON;
else if (c == '/') { /* allow embedded comment */
ps->nextstate = PREF_PARSE_UNTIL_CLOSE_PAREN;
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (isspace(c))
state = PREF_PARSE_UNTIL_CLOSE_PAREN;
else {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
}
default:
break;
}
break;
case PREF_PARSE_ESC_STRING_VALUE:
switch (c) {
case '\"':
case '\\':
break;
case 'r':
c = '\r';
break;
case 'n':
c = '\n';
break;
default:
NS_WARNING("preserving unexpected JS escape sequence");
/* preserve the escape sequence */
*ps->lbcur++ = '\\';
break;
}
*ps->lbcur++ = c;
state = PREF_PARSE_VALUE;
break;
/* comment parsing */
case PREF_PARSE_COMMENT_MAYBE_START:
switch (c) {
case '*': /* comment block */
state = PREF_PARSE_COMMENT_BLOCK;
break;
case '/': /* comment line */
state = PREF_PARSE_UNTIL_EOL;
break;
default:
/* pref file is malformed */
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
case PREF_PARSE_COMMENT_BLOCK:
if (c == '*')
state = PREF_PARSE_COMMENT_BLOCK_MAYBE_END;
break;
case PREF_PARSE_COMMENT_BLOCK_MAYBE_END:
switch (c) {
case '/':
state = ps->nextstate;
ps->nextstate = PREF_PARSE_INIT;
break;
case '*': /* stay in this state */
break;
default:
state = PREF_PARSE_COMMENT_BLOCK;
}
break;
/* function open and close parsing */
case PREF_PARSE_UNTIL_OPEN_PAREN:
/* tolerate only whitespace and embedded comments */
if (c == '(')
state = PREF_PARSE_UNTIL_NAME;
else if (c == '/') {
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
case PREF_PARSE_UNTIL_CLOSE_PAREN:
/* tolerate only whitespace and embedded comments */
if (c == ')')
state = PREF_PARSE_UNTIL_SEMICOLON;
else if (c == '/') {
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
/* function terminator ';' parsing */
case PREF_PARSE_UNTIL_SEMICOLON:
/* tolerate only whitespace and embedded comments */
if (c == ';') {
type = ps->vtype;
action = ps->fuser ? PREF_SETUSER : PREF_SETDEFAULT;
switch (type) {
case PREF_STRING:
value.stringVal = ps->vb;
break;
case PREF_INT:
if ((ps->vb[0] == '-' || ps->vb[0] == '+') && ps->vb[1] == '\0') {
NS_WARNING("malformed integer value");
return PR_FALSE;
}
value.intVal = atoi(ps->vb);
break;
case PREF_BOOL:
value.boolVal = (ps->vb == kTrue);
break;
default:
break;
}
(*ps->reader)(ps->closure, ps->lb, value, type, action);
state = PREF_PARSE_INIT;
}
else if (c == '/') {
ps->nextstate = state; /* return here when done with comment */
state = PREF_PARSE_COMMENT_MAYBE_START;
}
else if (!isspace(c)) {
NS_WARNING("malformed pref file");
return PR_FALSE;
}
break;
/* eol parsing */
case PREF_PARSE_UNTIL_EOL:
/* need to handle mac, unix, or dos line endings.
* PREF_PARSE_INIT will eat the next \n in case
* we have \r\n. */
if (c == '\r' || c == '\n') {
state = ps->nextstate;
ps->nextstate = PREF_PARSE_INIT; /* reset next state */
}
break;
}
}
ps->state = state;
return PR_TRUE;
}
#ifdef TEST_PREFREAD
static void
pref_reader(void *closure,
const char *pref,
PrefValue val,
PrefType type,
PrefAction action)
{
printf("%spref(\"%s\", ", action == PREF_SETUSER ? "user_" : "", pref);
switch (type) {
case PREF_STRING:
printf("\"%s\");\n", val.stringVal);
break;
case PREF_INT:
printf("%i);\n", val.intVal);
break;
case PREF_BOOL:
printf("%s);\n", val.boolVal == PR_FALSE ? "false" : "true");
break;
}
}
int
main(int argc, char **argv)
{
PrefParseState ps;
char buf[4096]; /* i/o buffer */
FILE *fp;
int n;
if (argc == 1) {
printf("usage: prefread file.js\n");
return -1;
}
fp = fopen(argv[1], "r");
if (!fp) {
printf("failed to open file\n");
return -1;
}
PREF_InitParseState(&ps, pref_reader, NULL);
while ((n = fread(buf, 1, sizeof(buf), fp)) > 0)
PREF_ParseBuf(&ps, buf, n);
PREF_FinalizeParseState(&ps);
fclose(fp);
return 0;
}
#endif /* TEST_PREFREAD */

Просмотреть файл

@ -0,0 +1,128 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla.
*
* The Initial Developer of the Original Code is Darin Fisher.
* Portions created by the Initial Developer are Copyright (C) 2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Darin Fisher <darin@meer.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef prefread_h__
#define prefread_h__
#include "prtypes.h"
#include "prefapi.h"
NSPR_BEGIN_EXTERN_C
/**
* Callback function used to notify consumer of preference name value pairs.
* The pref name and value must be copied by the implementor of the callback
* if they are needed beyond the scope of the callback function.
*
* @param closure
* user data passed to PREF_InitParseState
* @param pref
* preference name
* @param val
* preference value
* @param type
* preference type (PREF_STRING, PREF_INT, or PREF_BOOL)
* @param action
* preference action (PREF_SETDEFAULT or PREF_SETUSER)
*/
typedef void (*PrefReader)(void *closure,
const char *pref,
PrefValue val,
PrefType type,
PrefAction action);
/* structure fields are private */
typedef struct PrefParseState {
PrefReader reader;
void *closure;
int state; /* PREF_PARSE_... */
int nextstate; /* sometimes used... */
const char *smatch; /* string to match */
int sindex; /* next char of smatch to check */
char *lb; /* line buffer (only allocation) */
char *lbcur; /* line buffer cursor */
char *lbend; /* line buffer end */
char *vb; /* value buffer (ptr into lb) */
PrefType vtype; /* PREF_STRING,INT,BOOL */
PRBool fuser; /* PR_TRUE if user_pref */
} PrefParseState;
/**
* PREF_InitParseState
*
* Called to initialize a PrefParseState instance.
*
* @param ps
* PrefParseState instance.
* @param reader
* PrefReader callback function, which will be called once for each
* preference name value pair extracted.
* @param closure
* PrefReader closure.
*/
void PREF_InitParseState(PrefParseState *ps, PrefReader reader, void *closure);
/**
* PREF_FinalizeParseState
*
* Called to release any memory in use by the PrefParseState instance.
*
* @param ps
* PrefParseState instance.
*/
void PREF_FinalizeParseState(PrefParseState *ps);
/**
* PREF_ParseBuf
*
* Called to parse a buffer containing some portion of a preference file. This
* function may be called repeatedly as new data is made available. The
* PrefReader callback function passed PREF_InitParseState will be called as
* preference name value pairs are extracted from the data.
*
* @param ps
* PrefParseState instance. Must have been initialized.
* @param buf
* Raw buffer containing data to be parsed.
* @param bufLen
* Length of buffer.
*
* @return PR_FALSE if buffer contains malformed content.
*/
PRBool PREF_ParseBuf(PrefParseState *ps, const char *buf, int bufLen);
NSPR_END_EXTERN_C
#endif /* prefread_h__ */