예제 #1
0
nsresult
nsConsoleService::Init()
{
    mMessages = (nsIConsoleMessage **)
        nsMemory::Alloc(mBufferSize * sizeof(nsIConsoleMessage *));
    if (!mMessages)
        return NS_ERROR_OUT_OF_MEMORY;

    // Array elements should be 0 initially for circular buffer algorithm.
    memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage *));

    mLock = PR_NewLock();
    if (!mLock)
        return NS_ERROR_OUT_OF_MEMORY;

    return NS_OK;
}
예제 #2
0
static PRIntn prmain(PRIntn argc, char **argv)
{
    PRStatus rv;
    PRLock *ml = PR_NewLock();
    PRCondVar *cv = PRP_NewNakedCondVar();
    PRIntervalTime tenmsecs = PR_MillisecondsToInterval(10);

    rv = PRP_TryLock(ml);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; 
    
    rv = PRP_TryLock(ml);
    PR_ASSERT(PR_FAILURE == rv);
    if ((rv != PR_FAILURE) & (!debug_mode)) failed_already=1; 

    rv = PRP_NakedNotify(cv);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; 

    rv = PRP_NakedBroadcast(cv);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1; 

    rv = PRP_NakedWait(cv, ml, tenmsecs);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1;     

    PR_Unlock(ml);    
        
    rv = PRP_NakedNotify(cv);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1;     

    rv = PRP_NakedBroadcast(cv);
    PR_ASSERT(PR_SUCCESS == rv);
    if ((rv != PR_SUCCESS) & (!debug_mode)) failed_already=1;     

    PRP_DestroyNakedCondVar(cv);
    PR_DestroyLock(ml);

    if (debug_mode) printf("Test succeeded\n");

    return 0;

}  /* prmain */
예제 #3
0
파일: searchthread.c 프로젝트: Firstyear/ds
/* new searchthread */
SearchThread *st_new(void)
{
    SearchThread *st = (SearchThread *)malloc(sizeof(SearchThread));

    if (!st) return NULL;
    st->searchCount = st->failCount = 0;
    st->mintime = 10000;
    st->maxtime = 0;
    st->ld = NULL;
    st->ld2 = NULL;
    st->soc = -1;
    st->tid = NULL;
    st->id = 0;
    st->alive = 1;
    st->lock = PR_NewLock();
	st->retry = 0;
    return st;
}
예제 #4
0
/**************************************************************************
 *
 * P k 1 1 I n s t a l l _ S e t E r r o r H a n d l e r
 *
 * Sets the error handler to be used by the library.  Returns the current
 * error handler function.
 */
Pk11Install_ErrorHandler
Pk11Install_SetErrorHandler(Pk11Install_ErrorHandler handler)
{
    Pk11Install_ErrorHandler old;

    if (!errorHandlerLock) {
        errorHandlerLock = PR_NewLock();
    }

    PR_Lock(errorHandlerLock);

    old = errorHandler;
    errorHandler = handler;

    PR_Unlock(errorHandlerLock);

    return old;
}
예제 #5
0
파일: objset.c 프로젝트: Firstyear/ds
/*
 * Create a new, empty object set.
 * Returns a pointer to the new object set, or NULL if an error occurred.
 */
Objset *
objset_new(FNFree objset_destructor)
{
	objset *set;

	set = (objset *)slapi_ch_malloc(sizeof(objset));
	set->lock = PR_NewLock();
	if (NULL == set->lock)
	{
		slapi_ch_free((void **)&set);
	}
	else
	{
		set->head = set->tail = NULL;
		set->destructor = objset_destructor;
	}
	return set;
}
예제 #6
0
파일: mempool.c 프로젝트: Firstyear/ds
static void
create_counters()
{
	PR_CREATE_COUNTER(slapi_ch_counter_malloc,"slapi_ch","malloc","");
	PR_CREATE_COUNTER(slapi_ch_counter_calloc,"slapi_ch","calloc","");
	PR_CREATE_COUNTER(slapi_ch_counter_realloc,"slapi_ch","realloc","");
	PR_CREATE_COUNTER(slapi_ch_counter_strdup,"slapi_ch","strdup","");
	PR_CREATE_COUNTER(slapi_ch_counter_free,"slapi_ch","free","");
	PR_CREATE_COUNTER(slapi_ch_counter_created,"slapi_ch","created","");
	PR_CREATE_COUNTER(slapi_ch_counter_exist,"slapi_ch","exist","");

	/* ensure that we have space to allow for shutdown calls to malloc()
	 * from should we run out of memory.
	 */
	if (oom_emergency_area == NULL) {
	  oom_emergency_area = malloc(OOM_PREALLOC_SIZE);
	}
	oom_emergency_lock = PR_NewLock();
}
예제 #7
0
파일: prfdcach.c 프로젝트: Akesure/jxcore
void _PR_InitFdCache(void)
{
    /*
    ** The fd caching is enabled by default for DEBUG builds,
    ** disabled by default for OPT builds. That default can
    ** be overridden at runtime using environment variables
    ** or a super-wiz-bang API.
    */
    const char *low = PR_GetEnv("NSPR_FD_CACHE_SIZE_LOW");
    const char *high = PR_GetEnv("NSPR_FD_CACHE_SIZE_HIGH");

    /* 
    ** _low is allowed to be zero, _high is not.
    ** If _high is zero, we're not doing the caching.
    */

    _pr_fd_cache.limit_low = 0;
#if defined(DEBUG)
    _pr_fd_cache.limit_high = FD_SETSIZE;
#else
    _pr_fd_cache.limit_high = 0;
#endif  /* defined(DEBUG) */

    if (NULL != low) _pr_fd_cache.limit_low = atoi(low);
    if (NULL != high) _pr_fd_cache.limit_high = atoi(high);

    if (_pr_fd_cache.limit_low < 0)
        _pr_fd_cache.limit_low = 0;
    if (_pr_fd_cache.limit_low > FD_SETSIZE)
        _pr_fd_cache.limit_low = FD_SETSIZE;

    if (_pr_fd_cache.limit_high > FD_SETSIZE)
        _pr_fd_cache.limit_high = FD_SETSIZE;

    if (_pr_fd_cache.limit_high < _pr_fd_cache.limit_low)
        _pr_fd_cache.limit_high = _pr_fd_cache.limit_low;

    _pr_fd_cache.ml = PR_NewLock();
    PR_ASSERT(NULL != _pr_fd_cache.ml);
    _pr_fd_cache.stack = PR_CreateStack("FD");
    PR_ASSERT(NULL != _pr_fd_cache.stack);

}  /* _PR_InitFdCache */
예제 #8
0
JSDStaticLock*
jsd_CreateLock()
{
    JSDStaticLock* lock;

    if( ! (lock = js_pod_calloc<JSDStaticLock>(1)) ||
        ! (lock->lock = PR_NewLock()) )
    {
        if(lock)
        {
            free(lock);
            lock = NULL;
        }
    }
#ifdef DEBUG
    if(lock) lock->sig = (uint16_t) JSD_LOCK_SIG;
#endif
    return lock;
}    
예제 #9
0
파일: addthread.c 프로젝트: Firstyear/ds
/* new addthread */
AddThread *at_new(void)
{
    AddThread *at = (AddThread *)malloc(sizeof(AddThread));

    if (!at) return NULL;
    at->addCount = at->failCount = at->addTotal = 0;
    at->mintime = 10000;
    at->maxtime = 0;
    at->ld = NULL;
    at->tid = NULL;
    at->id = 0;
    at->alive = 1;
    at->retry = 0;
    at->lock = PR_NewLock();
    at->blob = NULL;
    /* make sure the id generator has initialized */
    getID();
    return at;
}
예제 #10
0
void*
jsd_CreateLock()
{
    JSDStaticLock* lock;

    if( ! (lock = (JSDStaticLock*)calloc(1, sizeof(JSDStaticLock))) || 
        ! (lock->lock = PR_NewLock()) )
    {
        if(lock)
        {
            free(lock);
            lock = NULL;
        }
    }
#ifdef DEBUG
    if(lock) lock->sig = (uint16) JSD_LOCK_SIG;
#endif
    return lock;
}    
static PRIntn PR_CALLBACK RealMain( PRIntn argc, char **argv )
{
	PLOptStatus os;
  	PLOptState *opt = PL_CreateOptState(argc, argv, "dhlmc");
	PRBool locks = PR_FALSE, monitors = PR_FALSE, cmonitors = PR_FALSE;

    err = PR_GetSpecialFD(PR_StandardError);

	while (PL_OPT_EOL != (os = PL_GetNextOpt(opt)))
    {
		if (PL_OPT_BAD == os) continue;
        switch (opt->option)
        {
        case 'd':  /* debug mode (noop) */
            break;
        case 'l':  /* locks */
			locks = PR_TRUE;
            break;
        case 'm':  /* monitors */
			monitors = PR_TRUE;
            break;
        case 'c':  /* cached monitors */
			cmonitors = PR_TRUE;
            break;
        case 'h':  /* needs guidance */
         default:
            Help();
            return 2;
        }
    }
	PL_DestroyOptState(opt);

    ml = PR_NewLock();
    if (locks) T1Lock();
    if (monitors) T1Mon();
    if (cmonitors) T1CMon();

    PR_DestroyLock(ml);

    PR_fprintf(err, "Done!\n");    
    return 0;
}  /* main */
예제 #12
0
static PRStatus TimerInit(void)
{
    tm_vars.ml = PR_NewLock();
    if (NULL == tm_vars.ml)
    {
        goto failed;
    }
    tm_vars.new_timer = PR_NewCondVar(tm_vars.ml);
    if (NULL == tm_vars.new_timer)
    {
        goto failed;
    }
    tm_vars.cancel_timer = PR_NewCondVar(tm_vars.ml);
    if (NULL == tm_vars.cancel_timer)
    {
        goto failed;
    }
    PR_INIT_CLIST(&tm_vars.timer_queue);
    tm_vars.manager_thread = PR_CreateThread(
        PR_SYSTEM_THREAD, TimerManager, NULL, PR_PRIORITY_NORMAL,
        PR_LOCAL_THREAD, PR_UNJOINABLE_THREAD, 0);
    if (NULL == tm_vars.manager_thread)
    {
        goto failed;
    }
    return PR_SUCCESS;

failed:
    if (NULL != tm_vars.cancel_timer)
    {
        PR_DestroyCondVar(tm_vars.cancel_timer);
    }
    if (NULL != tm_vars.new_timer)
    {
        PR_DestroyCondVar(tm_vars.new_timer);
    }
    if (NULL != tm_vars.ml)
    {
        PR_DestroyLock(tm_vars.ml);
    }
    return PR_FAILURE;
}
예제 #13
0
static PRIntervalTime ContentiousLock(PRUint32 loops)
{
    PRStatus status;
    PRThread *thread = NULL;
    LockContentious_t * contention;
    PRIntervalTime rv, overhead, timein = PR_IntervalNow();

    contention = PR_NEWZAP(LockContentious_t);
    contention->loops = loops;
    contention->overhead = 0;
    contention->ml = PR_NewLock();
    contention->interval = contention_interval;
    thread = PR_CreateThread(
        PR_USER_THREAD, LockContender, contention,
        PR_PRIORITY_LOW, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0);
    PR_ASSERT(thread != NULL);

    overhead = PR_IntervalNow() - timein;

    while (contention->loops-- > 0)
    {
        PR_Lock(contention->ml);
        PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(contention->ml);
        contention->contentious+= 1;
        contention->overhead += contention->interval;
        PR_Sleep(contention->interval);
        PR_ASSERT_CURRENT_THREAD_OWNS_LOCK(contention->ml);
        PR_Unlock(contention->ml);
    }

    timein = PR_IntervalNow();
    status = PR_JoinThread(thread);
    PR_DestroyLock(contention->ml);
    overhead += (PR_IntervalNow() - timein);
    rv = overhead + contention->overhead;
    if (verbosity)
        PR_fprintf(
            std_err, "Access ratio: %u to %u\n",
            contention->contentious, contention->contender);
    PR_Free(contention);
    return rv;
}  /* ContentiousLock */
LdapSessionPool::LdapSessionPool(LdapRealm *ldapRealm,int limit)
{
    _ldapRealm = ldapRealm;
    _maxSessions = (limit < 1 ? 1 : limit);
    _waiters = 0;
    _lock = PR_NewLock();
    assert(_lock);
    _cvar = PR_NewCondVar(_lock);
    assert(_cvar);

    // add new pool to list of all pools
    if (_poolListLock == NULL) {
        static PRCallOnceType once = { 0, 0, (PRStatus)0 };
        PR_CallOnce(&once, PoolListCreate);
    }
    PR_Lock(_poolListLock);
    _nextPool = _poolList;
    _poolList = this;
    PR_Unlock(_poolListLock);
}
nsSocketTransportService::nsSocketTransportService()
    : mThread(nsnull)
    , mThreadEvent(nsnull)
    , mAutodialEnabled(PR_FALSE)
    , mLock(PR_NewLock())
    , mInitialized(PR_FALSE)
    , mShuttingDown(PR_FALSE)
    , mActiveCount(0)
    , mIdleCount(0)
    , mSendBufferSize(0)
{
#if defined(PR_LOGGING)
    gSocketTransportLog = PR_NewLogModule("nsSocketTransport");
#endif

    NS_ASSERTION(NS_IsMainThread(), "wrong thread");

    NS_ASSERTION(!gSocketTransportService, "must not instantiate twice");
    gSocketTransportService = this;
}
//-----------------------------------------------------------------------------
CDatabaseQuery::CDatabaseQuery()
: m_pLock(PR_NewLock())
, m_IsAborting(PR_FALSE)
, m_IsExecuting(PR_FALSE)
, m_AsyncQuery(PR_FALSE)
, m_CurrentQuery((PRUint32)-1)
, m_LastError(0)
, m_pQueryRunningMonitor(nsAutoMonitor::NewMonitor("CDatabaseQuery.m_pdbQueryRunningMonitor"))
, m_QueryHasCompleted(PR_FALSE)
, m_RollingLimit(0)
, m_RollingLimitColumnIndex(0)
, m_RollingLimitResult(0)
{
#ifdef PR_LOGGING
  if (!sDatabaseQueryLog)
    sDatabaseQueryLog = PR_NewLogModule("sbDatabaseQuery");
#endif

  m_CallbackList.Init(DATABASEQUERY_DEFAULT_CALLBACK_SLOTS);
} //ctor
StatsThreadNode::StatsThreadNode(int nProfileBucketsCount):
                                 next(0),
                                 profile(0)
{
    // Reset the slot to null
    memset(&threadStats, 0, sizeof(threadStats));
    threadStats.timeStarted = PR_Now();
    threadStats.mode = STATS_THREAD_IDLE;

    // Allocate the profile
    nProfileBucketsCount_ = nProfileBucketsCount;
    if (nProfileBucketsCount)
    {
        profile = new StatsProfileNode[nProfileBucketsCount];
        statsMakeListFromArray(profile, nProfileBucketsCount);
    }

    // Create the lock that serializes access to realtime thread statistics
    lock_ = PR_NewLock();

}
예제 #18
0
void
js_lock_task(JSTaskState *task)
{
    PRThread *me = PR_GetCurrentThread();

    if (! js_owner_lock) {
      js_owner_lock = PR_NewLock();
    }

    if ( js_owner_thread == me) {
        PR_ASSERT(js_owner_count > 0);
        js_owner_count++;
    }
    else {
        PR_Lock(js_owner_lock);
        PR_ASSERT(js_owner_count == 0);
        js_owner_count = 1;
        js_owner_thread = me;
    }

}
예제 #19
0
파일: psearch.c 프로젝트: leto/389-ds
/*
 * Allocate and initialize an empty PSearch node.
 */
static PSearch *
psearch_alloc()
{
    PSearch 	*ps;

    ps = (PSearch *) slapi_ch_calloc( 1, sizeof( PSearch ));

    ps->ps_pblock = NULL;
    if (( ps->ps_lock = PR_NewLock()) == NULL ) {
	LDAPDebug( LDAP_DEBUG_ANY, "psearch_add: cannot create new lock.  "
		"Persistent search abandoned.\n", 0, 0, 0 );
	slapi_ch_free((void **)&ps);
	return( NULL );
    }
    ps->ps_tid = (PRThread *) NULL;
    ps->ps_complete = 0;
    ps->ps_eq_head = ps->ps_eq_tail = (PSEQNode *) NULL;
    ps->ps_lasttime = (time_t) 0L;
    ps->ps_next = NULL;
    return ps;
}
예제 #20
0
static PRIntervalTime ConditionNotify(PRUint32 loops)
{
    PRThread *thread;
    NotifyData notifyData;
    PRIntervalTime timein, overhead;
    
    timein = PR_IntervalNow();

    notifyData.counter = loops;
    notifyData.ml = PR_NewLock();
    notifyData.child = PR_NewCondVar(notifyData.ml);
    notifyData.parent = PR_NewCondVar(notifyData.ml);
    thread = PR_CreateThread(
        PR_USER_THREAD, Notifier, &notifyData,
        PR_GetThreadPriority(PR_GetCurrentThread()),
        thread_scope, PR_JOINABLE_THREAD, 0);

    overhead = PR_IntervalNow() - timein;  /* elapsed so far */

    PR_Lock(notifyData.ml);
    while (notifyData.counter > 0)
    {
        notifyData.pending = PR_TRUE;
        PR_NotifyCondVar(notifyData.child);
        while (notifyData.pending)
            PR_WaitCondVar(notifyData.parent, PR_INTERVAL_NO_TIMEOUT);
    }
    PR_Unlock(notifyData.ml);

    timein = PR_IntervalNow();

    (void)PR_JoinThread(thread);
    PR_DestroyCondVar(notifyData.child);
    PR_DestroyCondVar(notifyData.parent);
    PR_DestroyLock(notifyData.ml);
    
    overhead += (PR_IntervalNow() - timein);  /* more overhead */

    return overhead;
}  /* ConditionNotify */
예제 #21
0
// We put the atoms in a hash table for speedy lookup.. see ResolveAtom.
nsresult
nsHttp::CreateAtomTable()
{
    NS_ASSERTION(!sAtomTable.ops, "atom table already initialized");

    if (!sLock) {
        sLock = PR_NewLock();
        if (!sLock)
            return NS_ERROR_OUT_OF_MEMORY;
    }

    // The capacity for this table is initialized to a value greater than the
    // number of known atoms (NUM_HTTP_ATOMS) because we expect to encounter a
    // few random headers right off the bat.
    if (!PL_DHashTableInit(&sAtomTable, &ops, nsnull, sizeof(PLDHashEntryStub),
                           NUM_HTTP_ATOMS + 10)) {
        sAtomTable.ops = nsnull;
        return NS_ERROR_OUT_OF_MEMORY;
    }

    // fill the table with our known atoms
    const char *const atoms[] = {
#define HTTP_ATOM(_name, _value) nsHttp::_name._val,
#include "nsHttpAtomList.h"
#undef HTTP_ATOM
        nsnull
    };

    for (int i = 0; atoms[i]; ++i) {
        PLDHashEntryStub *stub = reinterpret_cast<PLDHashEntryStub *>
                                                 (PL_DHashTableOperate(&sAtomTable, atoms[i], PL_DHASH_ADD));
        if (!stub)
            return NS_ERROR_OUT_OF_MEMORY;
        
        NS_ASSERTION(!stub->key, "duplicate static atom");
        stub->key = atoms[i];
    }

    return NS_OK;
}
예제 #22
0
nsresult
TimeStamp::Startup()
{
  if (gInitialized)
    return NS_OK;

  const char *envp;
  APIRET rc;

  // Use the same variable as NSPR's os2inrval.c does to let the user disable the
  // high-resolution timer (it is known that it doesn't work well on some hardware)
  if ((envp = getenv("NSPR_OS2_NO_HIRES_TIMER")) != NULL) {
    if (atoi(envp) != 1) {
      // Attempt to use the high-res timer
      rc = DosTmrQueryFreq(&gTicksPerSec);
      if (rc == NO_ERROR)
        gUseHighResTimer = true;
    }
  }

  if (!gUseHighResTimer) {
    // TimeStamp has to use bare PRLock instead of mozilla::Mutex
    // because TimeStamp can be used very early in startup.
    gTimeStampLock = PR_NewLock();
    if (!gTimeStampLock)
      return NS_ERROR_OUT_OF_MEMORY;
    gRolloverCount = 1;
    gLastNow = 0;
    gTicksPerSec = PR_TicksPerSecond();
  }

  gTicksPerSecDbl = gTicksPerSec;
  gTicksPerMsDbl = gTicksPerSecDbl / 1000.0;

  gInitialized = true;
  sFirstTimeStamp = TimeStamp::Now();
  sProcessCreation = TimeStamp();

  return NS_OK;
}
예제 #23
0
Resolver :: Resolver(PRIntervalTime timeout)
{
    curlookups = namelookups = addrlookups = 0;
    ar_vc = 0;

    ok = PR_FALSE;

    ar_default_workerthread_timeout = timeout;

    memset(&ar_reinfo, 0, sizeof(ar_reinfo));

    dnslock = PR_NewLock();

    initcvar = PR_NewCondVar(dnslock);

    awake = PR_FALSE;

    afd = NULL;

    // then create a DNS manager background thread

    PRThread* ar_worker = PR_CreateThread(PR_SYSTEM_THREAD,
        run,
        this,
        PR_PRIORITY_NORMAL,
        PR_LOCAL_THREAD,
        PR_JOINABLE_THREAD,
        0);
    
    if (ar_worker)
    {
        wait();

        if (!ok)
        {
            PR_JoinThread(ar_worker);
        }
    }
}
예제 #24
0
static PRIntervalTime Alarms1(PRUint32 loops)
{
    PRAlarm *alarm;
    AlarmData ad;
    PRIntervalTime overhead, timein = PR_IntervalNow();
    PRIntervalTime duration = PR_SecondsToInterval(3);

    PRLock *ml = PR_NewLock();
    PRCondVar *cv = PR_NewCondVar(ml);

    ad.ml = ml;
    ad.cv = cv;
    ad.rate = 1;
    ad.times = loops;
    ad.late = ad.times = 0;
    ad.duration = duration;
    ad.timein = PR_IntervalNow();
    ad.period = PR_SecondsToInterval(1);

    alarm = PR_CreateAlarm();

    (void)PR_SetAlarm(
        alarm, ad.period, ad.rate, AlarmFn1, &ad);
        
    overhead = PR_IntervalNow() - timein;

    PR_Lock(ml);
    while ((PRIntervalTime)(PR_IntervalNow() - ad.timein) < duration)
        PR_WaitCondVar(cv, PR_INTERVAL_NO_TIMEOUT);
    PR_Unlock(ml);

    timein = PR_IntervalNow();
    (void)PR_DestroyAlarm(alarm);
    PR_DestroyCondVar(cv);
    PR_DestroyLock(ml);
    overhead += (PR_IntervalNow() - timein);
    
    return duration + overhead;
}  /* Alarms1 */
예제 #25
0
파일: psearch.c 프로젝트: leto/389-ds
/*
 * Initialize the list structure which contains the list
 * of outstanding persistent searches.  This must be
 * called early during server startup.
 */
void
ps_init_psearch_system()
{
    if ( !PS_IS_INITIALIZED()) {
	psearch_list = (PSearch_List *) slapi_ch_calloc( 1, sizeof( PSearch_List ));
	if (( psearch_list->pl_rwlock = slapi_new_rwlock()) == NULL ) {
	    LDAPDebug( LDAP_DEBUG_ANY, "init_psearch_list: cannot initialize lock structure. "
		    "The server is terminating.\n", 0, 0, 0 );
	    exit( -1 );
	}
	if (( psearch_list->pl_cvarlock = PR_NewLock()) == NULL ) {
	    LDAPDebug( LDAP_DEBUG_ANY, "init_psearch_list: cannot create new lock.  "
		    "The server is terminating.\n", 0, 0, 0 );
	    exit( -1 );
	}
	if (( psearch_list->pl_cvar = PR_NewCondVar( psearch_list->pl_cvarlock )) == NULL ) {
	    LDAPDebug( LDAP_DEBUG_ANY, "init_psearch_list: cannot create new condition variable.  "
		    "The server is terminating.\n", 0, 0, 0 );
	    exit( -1 );
	}
	psearch_list->pl_head = NULL;
    }
}
예제 #26
0
nsHashtable::nsHashtable(PRUint32 aInitSize, PRBool threadSafe)
  : mLock(NULL), mEnumerating(PR_FALSE)
{
    MOZ_COUNT_CTOR(nsHashtable);

    PRBool result = PL_DHashTableInit(&mHashtable, &hashtableOps, nsnull,
                                      sizeof(HTEntry), aInitSize);
    
    NS_ASSERTION(result, "Hashtable failed to initialize");

    // make sure we detect this later
    if (!result)
        mHashtable.ops = nsnull;
    
    if (threadSafe) {
        mLock = PR_NewLock();
        if (mLock == NULL) {
            // Cannot create a lock. If running on a multiprocessing system
            // we are sure to die.
            PR_ASSERT(mLock != NULL);
        }
    }
}
예제 #27
0
PR_IMPLEMENT(PRAlarm*) PR_CreateAlarm(void)
{
    PRAlarm *alarm = PR_NEWZAP(PRAlarm);
    if (alarm != NULL)
    {
        if ((alarm->lock = PR_NewLock()) == NULL) goto done;
        if ((alarm->cond = PR_NewCondVar(alarm->lock)) == NULL) goto done;
        alarm->state = alarm_active;
        PR_INIT_CLIST(&alarm->timers);
        alarm->notifier = PR_CreateThread(
            PR_USER_THREAD, pr_alarmNotifier, alarm,
            PR_GetThreadPriority(PR_GetCurrentThread()),
            PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0);
        if (alarm->notifier == NULL) goto done;
    }
    return alarm;

done:
    if (alarm->cond != NULL) PR_DestroyCondVar(alarm->cond);
    if (alarm->lock != NULL) PR_DestroyLock(alarm->lock);
    PR_DELETE(alarm);
    return NULL;
}  /* CreateAlarm */
예제 #28
0
nsExceptionService::nsExceptionService()
  : mProviders(4, PR_TRUE) /* small, thread-safe hashtable */
{
#ifdef NS_DEBUG
  if (PR_AtomicIncrement(&totalInstances)!=1) {
    NS_ERROR("The nsExceptionService is a singleton!");
  }
#endif
  /* member initializers and constructor code */
  if (tlsIndex == BAD_TLS_INDEX) {
    PRStatus status;
    status = PR_NewThreadPrivateIndex( &tlsIndex, ThreadDestruct );
    NS_ASSERTION(status==0, "ScriptErrorService could not allocate TLS storage.");
  }
  lock = PR_NewLock();
  NS_ASSERTION(lock, "Error allocating ExceptionService lock");

  // observe XPCOM shutdown.
  nsCOMPtr<nsIObserverService> observerService =
    mozilla::services::GetObserverService();
  NS_ASSERTION(observerService, "Could not get observer service!");
  if (observerService)
    observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_FALSE);
}
예제 #29
0
int main(int argc, char **argv)
#endif
{
    PRUintn pdkey;
    PRStatus status;
    char *path = NULL;
    PRDir *dir = NULL;
    PRLock *ml = NULL;
    PRCondVar *cv = NULL;
    PRThread *thread = NULL;
    PRIntervalTime interval = 0;
    PRFileDesc *file, *udp, *tcp, *pair[2];
    PRIntn test;

    if ( argc < 2)
    {
        test = 0;
    }
    else
        test = atoi(argv[1]);
        
    switch (test)
    {
        case 0: ml = PR_NewLock(); 
            break;
            
        case 1: interval = PR_SecondsToInterval(1);
            break;
            
        case 2: thread = PR_CreateThread(
            PR_USER_THREAD, lazyEntry, NULL, PR_PRIORITY_NORMAL,
            PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); 
            break;
            
        case 3: file = PR_Open("/usr/tmp/", PR_RDONLY, 0); 
            break;
            
        case 4: udp = PR_NewUDPSocket(); 
            break;
            
        case 5: tcp = PR_NewTCPSocket(); 
            break;
            
        case 6: dir = PR_OpenDir("/usr/tmp/"); 
            break;
            
        case 7: (void)PR_NewThreadPrivateIndex(&pdkey, NULL);
            break;
        
        case 8: path = PR_GetEnv("PATH");
            break;
            
        case 9: status = PR_NewTCPSocketPair(pair);
            break;
            
        case 10: PR_SetConcurrency(2);
            break;
            
        default: 
            printf(
                "lazyinit: unrecognized command line argument: %s\n", 
                argv[1] );
            printf( "FAIL\n" );
            exit( 1 );
            break;
    } /* switch() */
    return 0;
}  /* Lazy */
static void InitTraceLog(void)
{
  if (gInitialized) return;
  gInitialized = true;

  bool defined;
  defined = InitLog("XPCOM_MEM_BLOAT_LOG", "bloat/leaks", &gBloatLog);
  if (!defined)
    gLogLeaksOnly = InitLog("XPCOM_MEM_LEAK_LOG", "leaks", &gBloatLog);
  if (defined || gLogLeaksOnly) {
    RecreateBloatView();
    if (!gBloatView) {
      NS_WARNING("out of memory");
      gBloatLog = nullptr;
      gLogLeaksOnly = false;
    }
  }

  (void)InitLog("XPCOM_MEM_REFCNT_LOG", "refcounts", &gRefcntsLog);

  (void)InitLog("XPCOM_MEM_ALLOC_LOG", "new/delete", &gAllocLog);

  defined = InitLog("XPCOM_MEM_LEAKY_LOG", "for leaky", &gLeakyLog);
  if (defined) {
    gLogToLeaky = true;
    PRFuncPtr p = nullptr, q = nullptr;
#ifdef HAVE_DLOPEN
    {
      PRLibrary *lib = nullptr;
      p = PR_FindFunctionSymbolAndLibrary("__log_addref", &lib);
      if (lib) {
        PR_UnloadLibrary(lib);
        lib = nullptr;
      }
      q = PR_FindFunctionSymbolAndLibrary("__log_release", &lib);
      if (lib) {
        PR_UnloadLibrary(lib);
      }
    }
#endif
    if (p && q) {
      leakyLogAddRef = (void (*)(void*,int,int)) p;
      leakyLogRelease = (void (*)(void*,int,int)) q;
    }
    else {
      gLogToLeaky = false;
      fprintf(stdout, "### ERROR: XPCOM_MEM_LEAKY_LOG defined, but can't locate __log_addref and __log_release symbols\n");
      fflush(stdout);
    }
  }

  const char* classes = getenv("XPCOM_MEM_LOG_CLASSES");

#ifdef HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR
  if (classes) {
    (void)InitLog("XPCOM_MEM_COMPTR_LOG", "nsCOMPtr", &gCOMPtrLog);
  } else {
    if (getenv("XPCOM_MEM_COMPTR_LOG")) {
      fprintf(stdout, "### XPCOM_MEM_COMPTR_LOG defined -- but XPCOM_MEM_LOG_CLASSES is not defined\n");
    }
  }
#else
  const char* comptr_log = getenv("XPCOM_MEM_COMPTR_LOG");
  if (comptr_log) {
    fprintf(stdout, "### XPCOM_MEM_COMPTR_LOG defined -- but it will not work without dynamic_cast\n");
  }
#endif

  if (classes) {
    // if XPCOM_MEM_LOG_CLASSES was set to some value, the value is interpreted
    // as a list of class names to track
    gTypesToLog = PL_NewHashTable(256,
                                  PL_HashString,
                                  PL_CompareStrings,
                                  PL_CompareValues,
                                  &typesToLogHashAllocOps, NULL);
    if (!gTypesToLog) {
      NS_WARNING("out of memory");
      fprintf(stdout, "### XPCOM_MEM_LOG_CLASSES defined -- unable to log specific classes\n");
    }
    else {
      fprintf(stdout, "### XPCOM_MEM_LOG_CLASSES defined -- only logging these classes: ");
      const char* cp = classes;
      for (;;) {
        char* cm = (char*) strchr(cp, ',');
        if (cm) {
          *cm = '\0';
        }
        PL_HashTableAdd(gTypesToLog, nsCRT::strdup(cp), (void*)1);
        fprintf(stdout, "%s ", cp);
        if (!cm) break;
        *cm = ',';
        cp = cm + 1;
      }
      fprintf(stdout, "\n");
    }

    gSerialNumbers = PL_NewHashTable(256,
                                     HashNumber,
                                     PL_CompareValues,
                                     PL_CompareValues,
                                     &serialNumberHashAllocOps, NULL);


  }

  const char* objects = getenv("XPCOM_MEM_LOG_OBJECTS");
  if (objects) {
    gObjectsToLog = PL_NewHashTable(256,
                                    HashNumber,
                                    PL_CompareValues,
                                    PL_CompareValues,
                                    NULL, NULL);

    if (!gObjectsToLog) {
      NS_WARNING("out of memory");
      fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- unable to log specific objects\n");
    }
    else if (! (gRefcntsLog || gAllocLog || gCOMPtrLog)) {
      fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- but none of XPCOM_MEM_(REFCNT|ALLOC|COMPTR)_LOG is defined\n");
    }
    else {
      fprintf(stdout, "### XPCOM_MEM_LOG_OBJECTS defined -- only logging these objects: ");
      const char* cp = objects;
      for (;;) {
        char* cm = (char*) strchr(cp, ',');
        if (cm) {
          *cm = '\0';
        }
        intptr_t top = 0;
        intptr_t bottom = 0;
        while (*cp) {
          if (*cp == '-') {
            bottom = top;
            top = 0;
            ++cp;
          }
          top *= 10;
          top += *cp - '0';
          ++cp;
        }
        if (!bottom) {
          bottom = top;
        }
        for (intptr_t serialno = bottom; serialno <= top; serialno++) {
          PL_HashTableAdd(gObjectsToLog, (const void*)serialno, (void*)1);
          fprintf(stdout, "%ld ", serialno);
        }
        if (!cm) break;
        *cm = ',';
        cp = cm + 1;
      }
      fprintf(stdout, "\n");
    }
  }


  if (gBloatLog || gRefcntsLog || gAllocLog || gLeakyLog || gCOMPtrLog) {
    gLogging = true;
  }

  gTraceLock = PR_NewLock();
}