Пример #1
0
nsresult nsAutoConfig::evaluateLocalFile(nsIFile *file)
{
    nsresult rv;
    nsCOMPtr<nsIInputStream> inStr;
    
    rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), file);
    if (NS_FAILED(rv)) 
        return rv;
        
    PRInt64 fileSize;
    PRUint32 fs, amt=0;
    file->GetFileSize(&fileSize);
    LL_L2UI(fs, fileSize); // Converting 64 bit structure to unsigned int
    char *buf = (char *)PR_Malloc(fs * sizeof(char));
    if (!buf) 
        return NS_ERROR_OUT_OF_MEMORY;
    
    rv = inStr->Read(buf, fs, &amt);
    if (NS_SUCCEEDED(rv)) {
      EvaluateAdminConfigScript(buf, fs, nsnull, PR_FALSE, 
                                PR_TRUE, PR_FALSE);
    }
    inStr->Close();
    PR_Free(buf);
    return rv;
}
static void TestIntervals(void)
{
    PRStatus rv;
    PRUint32 delta;
    PRInt32 seconds;
    PRUint64 elapsed, thousand;
    PRTime timein, timeout;
    PRLock *ml = PR_NewLock();
    PRCondVar *cv = PR_NewCondVar(ml);
    for (seconds = 0; seconds < 10; ++seconds)
    {
        PRIntervalTime ticks = PR_SecondsToInterval(seconds);
        PR_Lock(ml);
        timein = PR_Now();
        rv = PR_WaitCondVar(cv, ticks);
        timeout = PR_Now();
        PR_Unlock(ml);
        LL_SUB(elapsed, timeout, timein);
        LL_I2L(thousand, 1000);
        LL_DIV(elapsed, elapsed, thousand);
        LL_L2UI(delta, elapsed);
        if (debug_mode) PR_fprintf(output, 
            "TestIntervals: %swaiting %ld seconds took %ld msecs\n",
            ((rv == PR_SUCCESS) ? "" : "FAILED "), seconds, delta);
    }
    PR_DestroyCondVar(cv);
    PR_DestroyLock(ml);
    if (debug_mode) PR_fprintf(output, "\n");
}  /* TestIntervals */
Пример #3
0
static PRUint32
NowInMinutes()
{
    PRTime now = PR_Now(), minutes, factor;
    LL_I2L(factor, 60 * PR_USEC_PER_SEC);
    LL_DIV(minutes, now, factor);
    PRUint32 result;
    LL_L2UI(result, minutes);
    return result;
}
Пример #4
0
PR_IMPLEMENT(PRUint64) PR_htonll(PRUint64 n)
{
#ifdef IS_BIG_ENDIAN
    return n;
#else
    PRUint64 tmp;
    PRUint32 hi, lo;
    LL_L2UI(lo, n);
    LL_SHR(tmp, n, 32);
    LL_L2UI(hi, tmp);
    hi = htonl(hi);
    lo = htonl(lo);
    LL_UI2L(n, lo);
    LL_SHL(n, n, 32);
    LL_UI2L(tmp, hi);
    LL_ADD(n, n, tmp);
    return n;
#endif
}  /* htonll */
Пример #5
0
/***********************************************************************
** PRIVATE FUNCTION:    Random
** DESCRIPTION:
**   Generate a pseudo-random number
** INPUTS:      None
** OUTPUTS:     None
** RETURN:      A pseudo-random unsigned number, 32-bits wide
** SIDE EFFECTS:
**      Updates random seed (a static)
** RESTRICTIONS:
**      None
** MEMORY:      NA
** ALGORITHM:
**      Uses the current interval timer value, promoted to a 64 bit
**      float as a multiplier for a static residue (which begins
**      as an uninitialized variable). The result is bits [16..48)
**      of the product. Seed is then updated with the return value
**      promoted to a float-64.
***********************************************************************/
static PRUint32 Random(void)
{
    PRUint32 rv;
    PRUint64 shift;
    static PRFloat64 seed = 0x58a9382;  /* Just make sure it isn't 0! */
    PRFloat64 random = seed * (PRFloat64)PR_IntervalNow();
    LL_USHR(shift, *((PRUint64*)&random), 16);
    LL_L2UI(rv, shift);
    seed = (PRFloat64)rv;
    return rv;
}  /* Random */
/***********************************************************************
** PRIVATE FUNCTION:    Random
** DESCRIPTION:
**   Generate a pseudo-random number
** INPUTS:      None
** OUTPUTS:     None
** RETURN:      A pseudo-random unsigned number, 32-bits wide
** SIDE EFFECTS:
**      Updates random seed (a static)
** RESTRICTIONS:
**      None
** MEMORY:      NA
** ALGORITHM:
**      Uses the current interval timer value, promoted to a 64 bit
**      float as a multiplier for a static residue (which begins
**      as an uninitialized variable). The result is bits [16..48)
**      of the product. Seed is then updated with the return value
**      promoted to a float-64.
***********************************************************************/
PRUint32 HammerData::Random()
{
    PRUint32 rv;
    PRUint64 shift;
    RCInterval now = RCInterval(RCInterval::now);
    PRFloat64 random = seed * (PRFloat64)((PRIntervalTime)now);
    LL_USHR(shift, *((PRUint64*)&random), 16);
    LL_L2UI(rv, shift);
    seed = (PRFloat64)rv;
    return rv;
}  /* HammerData::Random */
Пример #7
0
uint32_t
SecondsFromPRTime(PRTime prTime)
{
  int64_t  microSecondsPerSecond, intermediateResult;
  uint32_t seconds;

  LL_I2L(microSecondsPerSecond, PR_USEC_PER_SEC);
  intermediateResult = prTime / microSecondsPerSecond;
  LL_L2UI(seconds, intermediateResult);
  return seconds;
}
Пример #8
0
PRUint32
deltaMicroSeconds(PRTime aStartTime, PRTime aEndTime)
{
  PRUint32 delta;
  PRUint64 loadTime64;

  LL_SUB(loadTime64, aEndTime, aStartTime);
  LL_L2UI(delta, loadTime64);

  return delta;
}
Пример #9
0
static VALUE
RubyFrom64BitInt(PRUint64 aNative)
{
    PRUint64 lo64, hi64;
    LL_L2UI(lo64, aNative);
    LL_SHR(hi64, aNative, 32);
    {
    VALUE lo = UINT2NUM(lo64);
    VALUE hi = UINT2NUM(hi64);
    VALUE hiRuby = rb_funcall(hi, id_lshift, 1, INT2FIX(32));
    return rb_funcall(hiRuby, id_plus, 1, lo);
    }
}
Пример #10
0
/***********************************************************************
 *
 * G e n e r a t e C e r t
 *
 * Runs the whole process of creating a new cert, getting info from the
 * user, etc.
 */
int
GenerateCert(char *nickname, int keysize, char *token)
{
    CERTCertDBHandle * db;
    CERTCertificate * cert;
    char	*subject;
    unsigned long	serial;
    char	stdinbuf[160];

    /* Print warning about having the browser open */
    PR_fprintf(PR_STDOUT /*always go to console*/,
        "\nWARNING: Performing this operation while the browser is running could cause"
        "\ncorruption of your security databases. If the browser is currently running,"
        "\nyou should exit the browser before continuing this operation. Enter "
        "\n\"y\" to continue, or anything else to abort: ");
    pr_fgets(stdinbuf, 160, PR_STDIN);
    PR_fprintf(PR_STDOUT, "\n");
    if (tolower(stdinbuf[0]) != 'y') {
	PR_fprintf(errorFD, "Operation aborted at user's request.\n");
	errorCount++;
	return - 1;
    }

    db = CERT_GetDefaultCertDB();
    if (!db) {
	FatalError("Unable to open certificate database");
    }

    if (PK11_FindCertFromNickname(nickname, &pwdata)) {
	PR_fprintf(errorFD,
	    "ERROR: Certificate with nickname \"%s\" already exists in database. You\n"
	    "must choose a different nickname.\n", nickname);
	errorCount++;
	exit(ERRX);
    }

    LL_L2UI(serial, PR_Now());

    subject = GetSubjectFromUser(serial);

    cert = GenerateSelfSignedObjectSigningCert(nickname, db, subject,
         		serial, keysize, token);

    if (cert) {
	output_ca_cert(cert, db);
	CERT_DestroyCertificate(cert);
    }

    PORT_Free(subject);
    return 0;
}
Пример #11
0
/* returns an unsigned int containing the number of seconds in PR_Now() */
PRUint32
ssl_Time(void)
{
    PRUint32 myTime;
#if (defined(XP_UNIX) || defined(XP_WIN) || defined(_WINDOWS) || defined(XP_BEOS)) && !defined(_WIN32_WCE)
    myTime = time(NULL);	/* accurate until the year 2038. */
#else
    /* portable, but possibly slower */
    PRTime now;
    PRInt64 ll;

    now = PR_Now();
    LL_I2L(ll, 1000000L);
    LL_DIV(now, now, ll);
    LL_L2UI(myTime, now);
#endif
    return myTime;
}
Пример #12
0
//-------------------------------------------------------------------------
nsresult
DataStruct::ReadCache(nsISupports** aData, uint32_t* aDataLen)
{
  // if we don't have a cache filename we are out of luck
  if (!mCacheFileName)
    return NS_ERROR_FAILURE;

  // get the path and file name
  nsCOMPtr<nsIFile> cacheFile ( getter_AddRefs(GetFileSpec(mCacheFileName)) );
  bool exists;
  if ( cacheFile && NS_SUCCEEDED(cacheFile->Exists(&exists)) && exists ) {
    // get the size of the file
    int64_t fileSize;
    int64_t max32(LL_INIT(0, 0xFFFFFFFF));
    cacheFile->GetFileSize(&fileSize);
    if (LL_CMP(fileSize, >, max32))
      return NS_ERROR_OUT_OF_MEMORY;
    uint32_t size;
    LL_L2UI(size, fileSize);

    // create new memory for the large clipboard data
    nsAutoArrayPtr<char> data(new char[size]);
    if ( !data )
      return NS_ERROR_OUT_OF_MEMORY;
      
    // now read it all in
    nsCOMPtr<nsIInputStream> inStr;
    NS_NewLocalFileInputStream( getter_AddRefs(inStr),
                                cacheFile);
    
    if (!cacheFile) return NS_ERROR_FAILURE;

    nsresult rv = inStr->Read(data, fileSize, aDataLen);

    // make sure we got all the data ok
    if (NS_SUCCEEDED(rv) && *aDataLen == size) {
      nsPrimitiveHelpers::CreatePrimitiveForData ( mFlavor.get(), data, fileSize, aData );
      return *aData ? NS_OK : NS_ERROR_FAILURE;
    }

    // zero the return params
    *aData    = nullptr;
    *aDataLen = 0;
  }
Пример #13
0
PRUint32 ticks2xsec(tmreader* aReader, PRUint32 aTicks, PRUint32 aResolution)
/*
** Convert platform specific ticks to second units
** Returns 0 on success.
*/
{
    PRUint32 retval = 0;
    PRUint64 bigone;
    PRUint64 tmp64;

    LL_UI2L(bigone, aResolution);
    LL_UI2L(tmp64, aTicks);
    LL_MUL(bigone, bigone, tmp64);
    LL_UI2L(tmp64, aReader->ticksPerSec);
    LL_DIV(bigone, bigone, tmp64);
    LL_L2UI(retval, bigone);

    return retval;
}
Пример #14
0
PRUint32 nsMailDatabase::GetMailboxModDate()
{
  PRUint32 retModTime = 0;
  PRInt64 lastModTime;
  if (m_folderFile)
  {
    nsresult rv = m_folderFile->GetLastModifiedTime(&lastModTime);
    if (NS_SUCCEEDED(rv))
    {

      PRTime  temp64;
      PRInt64 thousand;
      LL_I2L(thousand, PR_MSEC_PER_SEC);
      LL_DIV(temp64, lastModTime, thousand);
      LL_L2UI(retModTime, temp64);
    }
  }
  return retModTime;
}
Пример #15
0
PRBool nsAbIPCCard::Same(nsIAbCard *card)
{
    if(!card)
        return PR_FALSE;

    nsresult rv;
    nsCOMPtr<nsIAbMDBCard> dbCard;
    dbCard = do_QueryInterface(card, &rv);
    if(NS_SUCCEEDED(rv)) {
        // first check the palmID for the cards if they exist
        nsXPIDLString palmIDStr;
        rv = dbCard->GetStringAttribute(CARD_ATTRIB_PALMID, getter_Copies(palmIDStr));
        if(NS_SUCCEEDED(rv) && palmIDStr.get()) {
            PRInt32 palmID=0;
            PRFloat64 f = PR_strtod(NS_LossyConvertUCS2toASCII(palmIDStr).get(), nsnull);
            PRInt64 l;
            LL_D2L(l, f);
            LL_L2UI(palmID, l);
            if(palmID && mRecordId)
                return mRecordId == palmID;
        }
    }

    nsXPIDLString str;
    card->GetFirstName(getter_Copies(str));
    if (Compare(str, m_FirstName, nsCaseInsensitiveStringComparator()))
        return PR_FALSE;
    card->GetLastName(getter_Copies(str));
    if (Compare(str, m_LastName, nsCaseInsensitiveStringComparator()))
        return PR_FALSE;
    card->GetDisplayName(getter_Copies(str));
    if (Compare(str, m_DisplayName, nsCaseInsensitiveStringComparator()))
        return PR_FALSE;
    card->GetNickName(getter_Copies(str));
    if (Compare(str, m_NickName, nsCaseInsensitiveStringComparator()))
        return PR_FALSE;

    return PR_TRUE;
}
void nsNetscapeProfileMigratorBase::CopyNextFolder()
{
  if (mFileCopyTransactionIndex < mFileCopyTransactions.Length())
  {
    PRUint32 percentage = 0;
    fileTransactionEntry fileTransaction =
      mFileCopyTransactions.ElementAt(mFileCopyTransactionIndex++);

    // copy the file
    fileTransaction.srcFile->CopyTo(fileTransaction.destFile,
                                    fileTransaction.newName);

    // add to our current progress
    PRInt64 fileSize;
    fileTransaction.srcFile->GetFileSize(&fileSize);
    LL_ADD(mCurrentProgress, mCurrentProgress, fileSize);

    PRInt64 percentDone;
    LL_MUL(percentDone, mCurrentProgress, 100);

    LL_DIV(percentDone, percentDone, mMaxProgress);

    LL_L2UI(percentage, percentDone);

    nsAutoString index;
    index.AppendInt(percentage);

    NOTIFY_OBSERVERS(MIGRATION_PROGRESS, index.get());

    // fire a timer to handle the next one.
    mFileIOTimer = do_CreateInstance("@mozilla.org/timer;1");

    if (mFileIOTimer)
      mFileIOTimer->InitWithCallback(static_cast<nsITimerCallback *>(this), percentage == 100 ? 500 : 0, nsITimer::TYPE_ONE_SHOT);
  } else
    EndCopyFolders();

  return;
}
Пример #17
0
NS_IMETHODIMP nsAbIPCCard::Copy(nsIAbCard *srcCard)
{
    NS_ENSURE_ARG_POINTER(srcCard);

    nsresult rv;
    nsCOMPtr<nsIAbMDBCard> dbCard;
    dbCard = do_QueryInterface(srcCard, &rv);
    if(NS_SUCCEEDED(rv) && dbCard) {
        nsXPIDLString palmIDStr;
        nsresult rv = dbCard->GetStringAttribute(CARD_ATTRIB_PALMID, getter_Copies(palmIDStr));
        if(NS_SUCCEEDED(rv) && palmIDStr.get()) {
            PRFloat64 f = PR_strtod(NS_LossyConvertUCS2toASCII(palmIDStr).get(), nsnull);
            PRInt64 l;
            LL_D2L(l, f);
            LL_L2UI(mRecordId, l);
        }
        else
            mRecordId = 0;
        // set tableID, RowID and Key for the card
        PRUint32 tableID=0;
        dbCard->GetDbTableID(&tableID);
        SetDbTableID(tableID);
        PRUint32 rowID=0;
        dbCard->GetDbRowID(&rowID);
        SetDbRowID(rowID);
        PRUint32 key;
        dbCard->GetKey(&key);
        SetKey(key);
    }
    PRUint32 lastModifiedDate = 0;
    srcCard->GetLastModifiedDate(&lastModifiedDate);
    mStatus = (lastModifiedDate) ? ATTR_MODIFIED : ATTR_NEW;

    rv = nsAbCardProperty::Copy(srcCard);
    // do we need to join the work and home addresses?
    // or split them?

    return rv;
}
Пример #18
0
NS_IMETHODIMP
nsSpamSettings::GetLogStream(nsIOutputStream **aLogStream)
{
  NS_ENSURE_ARG_POINTER(aLogStream);

  nsresult rv;

  if (!mLogStream) {
    nsCOMPtr <nsILocalFile> logFile = do_QueryInterface(mLogFile, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    // append to the end of the log file
    rv = MsgNewBufferedFileOutputStream(getter_AddRefs(mLogStream),
                                        logFile,
                                        PR_CREATE_FILE | PR_WRONLY | PR_APPEND,
                                        0600);
    NS_ENSURE_SUCCESS(rv, rv);

    PRInt64 fileSize;
    rv = logFile->GetFileSize(&fileSize);
    NS_ENSURE_SUCCESS(rv, rv);

    PRUint32 fileLen;
    LL_L2UI(fileLen, fileSize);
    // write the header at the start
    if (fileLen == 0)
    {
      PRUint32 writeCount;

      rv = mLogStream->Write(LOG_HEADER, LOG_HEADER_LEN, &writeCount);
      NS_ENSURE_SUCCESS(rv, rv);
      NS_ASSERTION(writeCount == LOG_HEADER_LEN, "failed to write out log header");
    }
  }

  NS_ADDREF(*aLogStream = mLogStream);
  return NS_OK;
}
Пример #19
0
// static
PRBool xptiManifest::Write(xptiInterfaceInfoManager* aMgr,
                           xptiWorkingSet*           aWorkingSet)
{

    PRBool succeeded = PR_FALSE;
    PRFileDesc* fd = nsnull;
    PRUint32 i;
    PRUint32 size32;
    PRIntn interfaceCount = 0;
    nsCAutoString appDirString;
    
    nsCOMPtr<nsILocalFile> tempFile;
    if(!aMgr->GetCloneOfManifestLocation(getter_AddRefs(tempFile)) || !tempFile)
        return PR_FALSE;

    nsCAutoString originalLeafName;
    tempFile->GetNativeLeafName(originalLeafName);

    nsCAutoString leafName;
    leafName.Assign(originalLeafName + NS_LITERAL_CSTRING(".tmp"));

    tempFile->SetNativeLeafName(leafName);

    // All exits via "goto out;" from here on...
    if(NS_FAILED(tempFile->
                 OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
                                  0666, &fd)) || !fd)
    {
        goto out;
    }

    // write file header comments

    if(!PR_fprintf(fd, "%s\n", g_Disclaimer))
        goto out;

    // write the [Header] block, version number, and appdir.

    if(!PR_fprintf(fd, "\n[%s,%d]\n", g_TOKEN_Header, 2))
        goto out;

    if(!PR_fprintf(fd, "%d,%s,%d,%d\n", 
                       0, g_TOKEN_Version, g_VERSION_MAJOR, g_VERSION_MINOR))
        goto out;

    GetCurrentAppDirString(aMgr, appDirString);
    if(appDirString.IsEmpty())
        goto out;

    if(!PR_fprintf(fd, "%d,%s,%s\n", 
                       1, g_TOKEN_AppDir, appDirString.get()))
        goto out;

    // write Directories list

    if(!PR_fprintf(fd, "\n[%s,%d]\n", 
                       g_TOKEN_Directories, 
                       (int) aWorkingSet->GetDirectoryCount()))
        goto out;

    for(i = 0; i < aWorkingSet->GetDirectoryCount(); i++)
    {
        nsCOMPtr<nsILocalFile> dir;        
        nsCAutoString str;

        aWorkingSet->GetDirectoryAt(i, getter_AddRefs(dir));
        if(!dir)
            goto out;

        dir->GetPersistentDescriptor(str);
        if(str.IsEmpty())
            goto out;
        
        if(!PR_fprintf(fd, "%d,%s\n", (int) i, str.get()))
            goto out;
    }

    // write Files list

    if(!PR_fprintf(fd, "\n[%s,%d]\n", 
                       g_TOKEN_Files, 
                       (int) aWorkingSet->GetFileCount()))
        goto out;

    for(i = 0; i < aWorkingSet->GetFileCount(); i++)
    {
        const xptiFile& file = aWorkingSet->GetFileAt(i);

        LL_L2UI(size32, file.GetSize());
    
        if(!PR_fprintf(fd, "%d,%s,%d,%u,%lld\n",
                           (int) i,
                           file.GetName(),
                           (int) file.GetDirectory(),
                           size32, PRInt64(file.GetDate())))
        goto out;
    }

    // write ArchiveItems list

    if(!PR_fprintf(fd, "\n[%s,%d]\n", 
                       g_TOKEN_ArchiveItems, 
                       (int) aWorkingSet->GetZipItemCount()))
        goto out;

    for(i = 0; i < aWorkingSet->GetZipItemCount(); i++)
    {
        if(!PR_fprintf(fd, "%d,%s\n",
                           (int) i,
                           aWorkingSet->GetZipItemAt(i).GetName()))
        goto out;
    }

    // write the Interfaces list

    interfaceCount = aWorkingSet->mNameTable->entryCount;

    if(!PR_fprintf(fd, "\n[%s,%d]\n", 
                       g_TOKEN_Interfaces, 
                       (int) interfaceCount))
        goto out;

    if(interfaceCount != (PRIntn)
        PL_DHashTableEnumerate(aWorkingSet->mNameTable, 
                               xpti_InterfaceWriter, fd))
        goto out;


    if(PR_SUCCESS == PR_Close(fd))
    {
        succeeded = PR_TRUE;
    }
    fd = nsnull;

out:
    if(fd)
        PR_Close(fd);
    
    if(succeeded)
    {
        // delete the old file and rename this
        nsCOMPtr<nsILocalFile> mainFile;
        if(!aMgr->GetCloneOfManifestLocation(getter_AddRefs(mainFile)) || !mainFile)
            return PR_FALSE;
    
        PRBool exists;
        if(NS_FAILED(mainFile->Exists(&exists)))
            return PR_FALSE;

        if(exists && NS_FAILED(mainFile->Remove(PR_FALSE)))
            return PR_FALSE;
    
        nsCOMPtr<nsIFile> parent;
        mainFile->GetParent(getter_AddRefs(parent));
            
        // MoveTo means rename.
        if(NS_FAILED(tempFile->MoveToNative(parent, originalLeafName)))
            return PR_FALSE;
    }

    return succeeded;
}        
nsresult
mozJSComponentLoader::GlobalForLocation(nsILocalFile *aComponent,
                                        JSObject **aGlobal,
                                        char **aLocation)
{
    nsresult rv;

    JSPrincipals* jsPrincipals = nsnull;
    JSCLContextHelper cx(mContext);

#ifndef XPCONNECT_STANDALONE
    rv = mSystemPrincipal->GetJSPrincipals(cx, &jsPrincipals);
    NS_ENSURE_SUCCESS(rv, rv);

    JSPrincipalsHolder princHolder(mContext, jsPrincipals);
#endif

    nsCOMPtr<nsIXPCScriptable> backstagePass;
    rv = mRuntimeService->GetBackstagePass(getter_AddRefs(backstagePass));
    NS_ENSURE_SUCCESS(rv, rv);

    JSCLAutoErrorReporterSetter aers(cx, mozJSLoaderErrorReporter);

    nsCOMPtr<nsIXPConnect> xpc =
        do_GetService(kXPConnectServiceContractID, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    // Make sure InitClassesWithNewWrappedGlobal() installs the
    // backstage pass as the global in our compilation context.
    JS_SetGlobalObject(cx, nsnull);

    nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
    rv = xpc->InitClassesWithNewWrappedGlobal(cx, backstagePass,
                                              NS_GET_IID(nsISupports),
                                              nsIXPConnect::
                                                  FLAG_SYSTEM_GLOBAL_OBJECT,
                                              getter_AddRefs(holder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *global;
    rv = holder->GetJSObject(&global);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineFunctions(cx, global, gGlobalFun)) {
        return NS_ERROR_FAILURE;
    }

    nsCOMPtr<nsIXPConnectJSObjectHolder> locationHolder;
    rv = xpc->WrapNative(cx, global, aComponent,
                         NS_GET_IID(nsILocalFile),
                         getter_AddRefs(locationHolder));
    NS_ENSURE_SUCCESS(rv, rv);

    JSObject *locationObj;
    rv = locationHolder->GetJSObject(&locationObj);
    NS_ENSURE_SUCCESS(rv, rv);

    if (!JS_DefineProperty(cx, global, "__LOCATION__",
                           OBJECT_TO_JSVAL(locationObj), nsnull, nsnull, 0)) {
        return NS_ERROR_FAILURE;
    }

    nsCAutoString nativePath;
    // Quick hack to unbust XPCONNECT_STANDALONE.
    // This leaves the jsdebugger with a non-URL pathname in the 
    // XPCONNECT_STANDALONE case - but at least it builds and runs otherwise.
    // See: http://bugzilla.mozilla.org/show_bug.cgi?id=121438
#ifdef XPCONNECT_STANDALONE
    localFile->GetNativePath(nativePath);
#else
    NS_GetURLSpecFromFile(aComponent, nativePath);
#endif

    // Before compiling the script, first check to see if we have it in
    // the fastload file.  Note: as a rule, fastload errors are not fatal
    // to loading the script, since we can always slow-load.
    nsCOMPtr<nsIFastLoadService> flSvc = do_GetFastLoadService(&rv);

    // Save the old state and restore it upon return
    FastLoadStateHolder flState(flSvc);
    PRBool fastLoading = PR_FALSE;

    if (NS_SUCCEEDED(rv)) {
        rv = StartFastLoad(flSvc);
        if (NS_SUCCEEDED(rv)) {
            fastLoading = PR_TRUE;
        }
    }

    nsCOMPtr<nsIURI> uri;
    rv = NS_NewURI(getter_AddRefs(uri), nativePath);
    NS_ENSURE_SUCCESS(rv, rv);

    JSScript *script = nsnull;

    if (fastLoading) {
        rv = ReadScript(flSvc, nativePath.get(), uri, cx, &script);
        if (NS_SUCCEEDED(rv)) {
            LOG(("Successfully loaded %s from fastload\n", nativePath.get()));
            fastLoading = PR_FALSE; // no need to write out the script
        } else if (rv == NS_ERROR_NOT_AVAILABLE) {
            // This is ok, it just means the script is not yet in the
            // fastload file.
            rv = NS_OK;
        } else {
            LOG(("Failed to deserialize %s\n", nativePath.get()));

            // Remove the fastload file, it may be corrupted.
            LOG(("Invalid fastload file detected, removing it\n"));
            nsCOMPtr<nsIObjectOutputStream> objectOutput;
            flSvc->GetOutputStream(getter_AddRefs(objectOutput));
            if (objectOutput) {
                flSvc->SetOutputStream(nsnull);
                objectOutput->Close();
            }
            nsCOMPtr<nsIObjectInputStream> objectInput;
            flSvc->GetInputStream(getter_AddRefs(objectInput));
            if (objectInput) {
                flSvc->SetInputStream(nsnull);
                objectInput->Close();
            }
            if (mFastLoadFile) {
                mFastLoadFile->Remove(PR_FALSE);
            }
            fastLoading = PR_FALSE;
        }
    }


    if (!script || NS_FAILED(rv)) {
        // The script wasn't in the fastload cache, so compile it now.
        LOG(("Slow loading %s\n", nativePath.get()));

#ifdef HAVE_PR_MEMMAP
        PRInt64 fileSize;
        rv = aComponent->GetFileSize(&fileSize);
        if (NS_FAILED(rv))
            return rv;

        PRInt64 maxSize;
        LL_UI2L(maxSize, PR_UINT32_MAX);
        if (LL_CMP(fileSize, >, maxSize)) {
            NS_ERROR("file too large");
            return NS_ERROR_FAILURE;
        }

        PRFileDesc *fileHandle;
        rv = aComponent->OpenNSPRFileDesc(PR_RDONLY, 0, &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        // Make sure the file is closed, no matter how we return.
        FileAutoCloser fileCloser(fileHandle);

        PRFileMap *map = PR_CreateFileMap(fileHandle, fileSize,
                                          PR_PROT_READONLY);
        if (!map) {
            NS_ERROR("Failed to create file map");
            return NS_ERROR_FAILURE;
        }

        // Make sure the file map is closed, no matter how we return.
        FileMapAutoCloser mapCloser(map);

        PRUint32 fileSize32;
        LL_L2UI(fileSize32, fileSize);

        char *buf = static_cast<char*>(PR_MemMap(map, 0, fileSize32));
        if (!buf) {
            NS_WARNING("Failed to map file");
            return NS_ERROR_FAILURE;
        }

        script = JS_CompileScriptForPrincipals(cx, global,
                                               jsPrincipals,
                                               buf, fileSize32,
                                               nativePath.get(), 1);
        PR_MemUnmap(buf, fileSize32);

#else  /* HAVE_PR_MEMMAP */

        /**
         * No memmap implementation, so fall back to using
         * JS_CompileFileHandleForPrincipals().
         */

        FILE *fileHandle;
        rv = aComponent->OpenANSIFileDesc("r", &fileHandle);
        NS_ENSURE_SUCCESS(rv, rv);

        script = JS_CompileFileHandleForPrincipals(cx, global,
                                                   nativePath.get(),
                                                   fileHandle, jsPrincipals);

        /* JS will close the filehandle after compilation is complete. */

#endif /* HAVE_PR_MEMMAP */
    }
Пример #21
0
nsresult nsReadConfig::openAndEvaluateJSFile(const char *aFileName, PRBool isEncoded, 
                                             PRInt32 obscureValue,
                                             PRBool isBinDir)
{
    nsresult rv;
    nsCOMPtr<nsIFile> jsFile;

    if (isBinDir) {
        rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR, 
                                    getter_AddRefs(jsFile));
        if (NS_FAILED(rv)) 
            return rv;
        
#ifdef XP_MAC
        jsFile->AppendNative(NS_LITERAL_CSTRING("Essential Files"));
#endif
    } else {
        rv = NS_GetSpecialDirectory(NS_APP_DEFAULTS_50_DIR,
                                    getter_AddRefs(jsFile));
        if (NS_FAILED(rv)) 
            return rv;
        rv = jsFile->AppendNative(NS_LITERAL_CSTRING("autoconfig"));
        if (NS_FAILED(rv))
            return rv;
    }
    rv = jsFile->AppendNative(nsDependentCString(aFileName));
    if (NS_FAILED(rv)) 
        return rv;

    nsCOMPtr<nsIInputStream> inStr;
    rv = NS_NewLocalFileInputStream(getter_AddRefs(inStr), jsFile);
    if (NS_FAILED(rv)) 
        return rv;        
        
    PRInt64 fileSize;
    PRUint32 fs, amt = 0;
    jsFile->GetFileSize(&fileSize);
    LL_L2UI(fs, fileSize); // Converting 64 bit structure to unsigned int

    char *buf = (char *)PR_Malloc(fs * sizeof(char));
    if (!buf) 
        return NS_ERROR_OUT_OF_MEMORY;
      
    rv = inStr->Read(buf, fs, &amt);
    NS_ASSERTION((amt == fs), "failed to read the entire configuration file!!");
    if (NS_SUCCEEDED(rv)) {
        if (obscureValue > 0) {

            // Unobscure file by subtracting some value from every char. 
            for (PRUint32 i = 0; i < amt; i++)
                buf[i] -= obscureValue;
        }
        nsCAutoString path;

        jsFile->GetNativePath(path);
        nsCAutoString fileURL;
        fileURL = NS_LITERAL_CSTRING("file:///") + path;
        rv = EvaluateAdminConfigScript(buf, amt, fileURL.get(), 
                                       PR_FALSE, PR_TRUE, 
                                       isEncoded ? PR_TRUE:PR_FALSE);
    }
    inStr->Close();
    PR_Free(buf);
    
    return rv;
}