Пример #1
0
JS_REQUIRES_STACK AbortableRecordingStatus
TraceRecorder::downRecursion()
{
    JSStackFrame* fp = cx->fp;
    if ((jsbytecode*)fragment->ip < fp->script->code ||
        (jsbytecode*)fragment->ip >= fp->script->code + fp->script->length) {
        RETURN_STOP_A("inner recursive call must compile first");
    }

    /* Adjust the stack by the budget the down-frame needs. */
    int slots = NativeStackSlots(cx, 1) - NativeStackSlots(cx, 0);
    JS_ASSERT(unsigned(slots) == NativeStackSlots(cx, 1) - fp->argc - 2 - fp->script->nfixed - 2);

    /* Guard that there is enough stack space. */
    JS_ASSERT(tree->maxNativeStackSlots >= tree->nativeStackBase / sizeof(double));
    int guardSlots = slots + tree->maxNativeStackSlots -
                     tree->nativeStackBase / sizeof(double);
    LIns* sp_top = lir->ins2(LIR_piadd, lirbuf->sp, lir->insImmWord(guardSlots * sizeof(double)));
    guard(true, lir->ins2(LIR_plt, sp_top, eos_ins), OOM_EXIT);

    /* Guard that there is enough call stack space. */
    LIns* rp_top = lir->ins2(LIR_piadd, lirbuf->rp, lir->insImmWord(sizeof(FrameInfo*)));
    guard(true, lir->ins2(LIR_plt, rp_top, eor_ins), OOM_EXIT);

    /*
     * For every slot in the new frame that is not in the tracker, create a load
     * in the tracker. This is necessary because otherwise snapshot() will see
     * missing imports and use the down frame, rather than the new frame.
     * This won't affect performance because the loads will be killed if not
     * used.
     */
    ImportFrameSlotsVisitor visitor(*this);
    VisitStackSlots(visitor, cx, callDepth);

    /* Add space for a new JIT frame. */
    lirbuf->sp = lir->ins2(LIR_piadd, lirbuf->sp, lir->insImmWord(slots * sizeof(double)));
    lir->insStorei(lirbuf->sp, lirbuf->state, offsetof(InterpState, sp));
    lirbuf->rp = lir->ins2(LIR_piadd, lirbuf->rp, lir->insImmWord(sizeof(FrameInfo*)));
    lir->insStorei(lirbuf->rp, lirbuf->state, offsetof(InterpState, rp));
    --callDepth;
    clearCurrentFrameSlotsFromTracker(nativeFrameTracker);

    /*
     * If the callee and caller have identical call sites, this is a down-
     * recursive loop. Otherwise something special happened. For example, a
     * recursive call that is unwinding could nest back down recursively again.
     * In this case, we build a fragment that ideally we'll never invoke
     * directly, but link from a down-recursive branch. The UNLINKED_EXIT tells
     * closeLoop() that the peer trees should match the recursive pc, not the
     * tree pc.
     */
    VMSideExit* exit;
    if ((jsbytecode*)fragment->root->ip == fp->script->code)
        exit = snapshot(UNSTABLE_LOOP_EXIT);
    else
        exit = snapshot(RECURSIVE_UNLINKED_EXIT);
    exit->recursive_pc = fp->script->code;
    debug_only_print0(LC_TMTracer, "Compiling down-recursive function call.\n");
    JS_ASSERT(tree->recursion != Recursion_Disallowed);
    tree->recursion = Recursion_Detected;
    return closeLoop(exit);
}
Пример #2
0
void
StorageComponent::setDistribution(DistributionSP distribution)
{
    std::lock_guard guard(_lock);
    _distribution = distribution;
}
Пример #3
0
 bool GlobalCache::has_seen(STATE, Symbol* sym) {
   utilities::thread::SpinLock::LockGuard guard(lock_);
   SeenMethodSet::const_iterator seen = seen_methods.find(sym->index());
   return seen != seen_methods.end();
 }
Пример #4
0
void
StorageComponent::setDocumentTypeRepo(DocumentTypeRepoSP repo)
{
    std::lock_guard guard(_lock);
    _docTypeRepo = repo;
}
Пример #5
0
void
StorageComponent::setLoadTypes(LoadTypeSetSP loadTypes)
{
    std::lock_guard guard(_lock);
    _loadTypes = loadTypes;
}
Пример #6
0
StorageComponent::LoadTypeSetSP
StorageComponent::getLoadTypes() const
{
    std::lock_guard guard(_lock);
    return _loadTypes;
}
Пример #7
0
StorageComponent::DistributionSP
StorageComponent::getDistribution() const
{
    std::lock_guard guard(_lock);
    return _distribution;
}
Пример #8
0
ComboBox::ActionGuard<ComboBox::TextChangeAction> ComboBox::SetTextChangeAction(TextChangeAction action) {

    ActionGuard<TextChangeAction> guard(&text_change_action_, TextChangeAction::UnselectDropDownItem);
    text_change_action_ = action;
    return guard;
}
Пример #9
0
StorageComponent::DocumentTypeRepoSP
StorageComponent::getTypeRepo() const
{
    std::lock_guard guard(_lock);
    return _docTypeRepo;
}
Пример #10
0
void SoapServerInternal::SetProtocolBinding(const string& url, SoapProtocol* binding)
{
	lock_guard<mutex> guard(m_protocolLock);
	m_protocolBindings[url] = binding;
}
Пример #11
0
ComboBox::ActionGuard<ComboBox::SelectionChangeAction> ComboBox::SetSelectionChangeAction(SelectionChangeAction action) {

    ActionGuard<SelectionChangeAction> guard(&selection_change_action_, SelectionChangeAction::CloseDropDownWindow);
    selection_change_action_ = action;
    return guard;
}
Пример #12
0
bool Bra::isUnconditional() const
{
	return guard()->isAlwaysTrue();
}
Пример #13
0
void Instruction::setGuard(PredicateOperand* p)
{
	delete guard();
	
	reads[0] = p;
}
Пример #14
0
JS_REQUIRES_STACK LIns*
TraceRecorder::slurpNullSlot(LIns* val_ins, jsval* vp, VMSideExit* exit)
{
    guard(true, lir->ins_peq0(val_ins), exit);
    return val_ins;
}
Пример #15
0
void
FeedHandler::changeFeedState(FeedState::SP newState)
{
    std::lock_guard<std::mutex> guard(_feedLock);
    changeFeedState(std::move(newState), guard);
}
Пример #16
0
 void GlobalCache::add_seen(STATE, Symbol* sym) {
   utilities::thread::SpinLock::LockGuard guard(lock_);
   seen_methods.insert(sym->index());
 }
Пример #17
0
void AuthorizationManagerImpl::invalidateUserCache() {
    CacheGuard guard(this, CacheGuard::fetchSynchronizationManual);
    _invalidateUserCache_inlock();
}
Пример #18
0
Status AuthorizationManagerImpl::acquireUser(OperationContext* opCtx,
                                             const UserName& userName,
                                             User** acquiredUser) {
    if (userName == internalSecurity.user->getName()) {
        *acquiredUser = internalSecurity.user;
        return Status::OK();
    }

    stdx::unordered_map<UserName, User*>::iterator it;

    CacheGuard guard(this, CacheGuard::fetchSynchronizationManual);
    while ((_userCache.end() == (it = _userCache.find(userName))) &&
           guard.otherUpdateInFetchPhase()) {
        guard.wait();
    }

    if (it != _userCache.end()) {
        fassert(16914, it->second);
        fassert(17003, it->second->isValid());
        fassert(17008, it->second->getRefCount() > 0);
        it->second->incrementRefCount();
        *acquiredUser = it->second;
        return Status::OK();
    }

    std::unique_ptr<User> user;

    int authzVersion = _version;
    guard.beginFetchPhase();

    // Number of times to retry a user document that fetches due to transient
    // AuthSchemaIncompatible errors.  These errors should only ever occur during and shortly
    // after schema upgrades.
    static const int maxAcquireRetries = 2;
    Status status = Status::OK();
    for (int i = 0; i < maxAcquireRetries; ++i) {
        if (authzVersion == schemaVersionInvalid) {
            Status status = _externalState->getStoredAuthorizationVersion(opCtx, &authzVersion);
            if (!status.isOK())
                return status;
        }

        switch (authzVersion) {
            default:
                status = Status(ErrorCodes::BadValue,
                                mongoutils::str::stream()
                                    << "Illegal value for authorization data schema version, "
                                    << authzVersion);
                break;
            case schemaVersion28SCRAM:
            case schemaVersion26Final:
            case schemaVersion26Upgrade:
                status = _fetchUserV2(opCtx, userName, &user);
                break;
            case schemaVersion24:
                status = Status(ErrorCodes::AuthSchemaIncompatible,
                                mongoutils::str::stream()
                                    << "Authorization data schema version "
                                    << schemaVersion24
                                    << " not supported after MongoDB version 2.6.");
                break;
        }
        if (status.isOK())
            break;
        if (status != ErrorCodes::AuthSchemaIncompatible)
            return status;

        authzVersion = schemaVersionInvalid;
    }
    if (!status.isOK())
        return status;

    guard.endFetchPhase();

    user->incrementRefCount();
    // NOTE: It is not safe to throw an exception from here to the end of the method.
    if (guard.isSameCacheGeneration()) {
        _userCache.insert(std::make_pair(userName, user.get()));
        if (_version == schemaVersionInvalid)
            _version = authzVersion;
    } else {
        // If the cache generation changed while this thread was in fetch mode, the data
        // associated with the user may now be invalid, so we must mark it as such.  The caller
        // may still opt to use the information for a short while, but not indefinitely.
        user->invalidate();
    }
    *acquiredUser = user.release();

    return Status::OK();
}
Пример #19
0
JS_REQUIRES_STACK AbortableRecordingStatus
TraceRecorder::slurpDownFrames(jsbytecode* return_pc)
{
    /* Missing - no go */
    if (cx->fp->argc != cx->fp->fun->nargs)
        RETURN_STOP_A("argc != nargs");

    LIns* argv_ins;
    unsigned frameDepth;
    unsigned downPostSlots;

    JSStackFrame* fp = cx->fp;
    LIns* fp_ins = addName(lir->insLoad(LIR_ldp, cx_ins, offsetof(JSContext, fp)), "fp");

    /*
     * When first emitting slurp code, do so against the down frame. After
     * popping the interpreter frame, it is illegal to resume here, as the
     * down frame has been moved up. So all this code should be skipped if
     * anchoring off such an exit.
     */
    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) {
        fp_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, down)), "downFp");
        fp = fp->down;

        argv_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, argv)), "argv");

        /* If recovering from a SLURP_MISMATCH, all of this is unnecessary. */
        if (!anchor || anchor->exitType != RECURSIVE_SLURP_MISMATCH_EXIT) {
            /* fp->down should not be NULL. */
            guard(false, lir->ins_peq0(fp_ins), RECURSIVE_LOOP_EXIT);

            /* fp->down->argv should not be NULL. */
            guard(false, lir->ins_peq0(argv_ins), RECURSIVE_LOOP_EXIT);

            /*
             * Guard on the script being the same. This might seem unnecessary,
             * but it lets the recursive loop end cleanly if it doesn't match.
             * With only the pc check, it is harder to differentiate between
             * end-of-recursion and recursion-returns-to-different-pc.
             */
            guard(true,
                  lir->ins2(LIR_peq,
                            addName(lir->insLoad(LIR_ldp,
                                                 fp_ins,
                                                 offsetof(JSStackFrame, script)),
                                    "script"),
                            INS_CONSTPTR(cx->fp->down->script)),
                  RECURSIVE_LOOP_EXIT);
        }

        /* fp->down->regs->pc should be == pc. */
        guard(true,
              lir->ins2(LIR_peq,
                        lir->insLoad(LIR_ldp,
                                     addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, regs)),
                                             "regs"),
                                     offsetof(JSFrameRegs, pc)),
                        INS_CONSTPTR(return_pc)),
              RECURSIVE_SLURP_MISMATCH_EXIT);

        /* fp->down->argc should be == argc. */
        guard(true,
              lir->ins2(LIR_eq,
                        addName(lir->insLoad(LIR_ld, fp_ins, offsetof(JSStackFrame, argc)),
                                "argc"),
                        INS_CONST(cx->fp->argc)),
              MISMATCH_EXIT);

        /* Pop the interpreter frame. */
        LIns* args[] = { lirbuf->state, cx_ins };
        guard(false, lir->ins_eq0(lir->insCall(&js_PopInterpFrame_ci, args)), MISMATCH_EXIT);

        /* Compute slots for the down frame. */
        downPostSlots = NativeStackSlots(cx, 1) - NativeStackSlots(cx, 0);
        frameDepth = 1;
    } else {
        /* Note: loading argv from fp, not fp->down. */
        argv_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, argv)), "argv");

        /* Slots for this frame, minus the return value. */
        downPostSlots = NativeStackSlots(cx, 0) - 1;
        frameDepth = 0;
    }

    /*
     * This is a special exit used as a template for the stack-slurping code.
     * LeaveTree will ignore all but the final slot, which contains the return
     * value. The slurpSlot variable keeps track of the last slot that has been
     * unboxed, as to avoid re-unboxing when taking a SLURP_FAIL exit.
     */
    unsigned numGlobalSlots = tree->globalSlots->length();
    unsigned safeSlots = NativeStackSlots(cx, frameDepth) + 1 + numGlobalSlots;
    jsbytecode* recursive_pc = return_pc + JSOP_CALL_LENGTH;
    VMSideExit* exit = (VMSideExit*)
        traceMonitor->traceAlloc->alloc(sizeof(VMSideExit) + sizeof(TraceType) * safeSlots);
    memset(exit, 0, sizeof(VMSideExit));
    exit->pc = (jsbytecode*)recursive_pc;
    exit->from = fragment;
    exit->exitType = RECURSIVE_SLURP_FAIL_EXIT;
    exit->numStackSlots = downPostSlots + 1;
    exit->numGlobalSlots = numGlobalSlots;
    exit->sp_adj = ((downPostSlots + 1) * sizeof(double)) - tree->nativeStackBase;
    exit->recursive_pc = recursive_pc;

    /*
     * Build the exit typemap. This may capture extra types, but they are
     * thrown away.
     */
    TraceType* typeMap = exit->stackTypeMap();
    jsbytecode* oldpc = cx->fp->regs->pc;
    cx->fp->regs->pc = exit->pc;
    CaptureStackTypes(cx, frameDepth, typeMap);
    cx->fp->regs->pc = oldpc;
    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT)
        typeMap[downPostSlots] = determineSlotType(&stackval(-1));
    else
        typeMap[downPostSlots] = anchor->stackTypeMap()[anchor->numStackSlots - 1];
    determineGlobalTypes(&typeMap[exit->numStackSlots]);
#if defined JS_JIT_SPEW
    TreevisLogExit(cx, exit);
#endif

    /*
     * Return values are tricky because there are two cases. Anchoring off a
     * slurp failure (the second case) means the return value has already been
     * moved. However it can still be promoted to link trees together, so we
     * load it from the new location.
     *
     * In all other cases, the return value lives in the tracker and it can be
     * grabbed safely.
     */
    LIns* rval_ins;
    TraceType returnType = exit->stackTypeMap()[downPostSlots];
    if (!anchor || anchor->exitType != RECURSIVE_SLURP_FAIL_EXIT) {
        rval_ins = get(&stackval(-1));
        if (returnType == TT_INT32) {
            JS_ASSERT(determineSlotType(&stackval(-1)) == TT_INT32);
            JS_ASSERT(isPromoteInt(rval_ins));
            rval_ins = demote(lir, rval_ins);
        }
        /*
         * The return value must be written out early, before slurping can fail,
         * otherwise it will not be available when there's a type mismatch.
         */
        lir->insStorei(rval_ins, lirbuf->sp, exit->sp_adj - sizeof(double));
    } else {
        switch (returnType)
        {
          case TT_PSEUDOBOOLEAN:
          case TT_INT32:
            rval_ins = lir->insLoad(LIR_ld, lirbuf->sp, exit->sp_adj - sizeof(double));
            break;
          case TT_DOUBLE:
            rval_ins = lir->insLoad(LIR_ldf, lirbuf->sp, exit->sp_adj - sizeof(double));
            break;
          case TT_FUNCTION:
          case TT_OBJECT:
          case TT_STRING:
          case TT_NULL:
            rval_ins = lir->insLoad(LIR_ldp, lirbuf->sp, exit->sp_adj - sizeof(double));
            break;
          default:
            JS_NOT_REACHED("unknown type");
            RETURN_STOP_A("unknown type"); 
        }
    }

    /* Slurp */
    SlurpInfo info;
    info.curSlot = 0;
    info.exit = exit;
    info.typeMap = typeMap;
    info.slurpFailSlot = (anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT) ?
                         anchor->slurpFailSlot : 0;

    /* callee */
    slurpSlot(lir->insLoad(LIR_ldp, argv_ins, -2 * ptrdiff_t(sizeof(jsval))),
              &fp->argv[-2],
              &info);
    /* this */
    slurpSlot(lir->insLoad(LIR_ldp, argv_ins, -1 * ptrdiff_t(sizeof(jsval))),
              &fp->argv[-1],
              &info);
    /* args[0..n] */
    for (unsigned i = 0; i < JS_MAX(fp->argc, fp->fun->nargs); i++)
        slurpSlot(lir->insLoad(LIR_ldp, argv_ins, i * sizeof(jsval)), &fp->argv[i], &info);
    /* argsobj */
    slurpSlot(addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, argsobj)), "argsobj"),
              &fp->argsobj,
              &info);
    /* scopeChain */
    slurpSlot(addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, scopeChain)), "scopeChain"),
              (jsval*) &fp->scopeChain,
              &info);
    /* vars */
    LIns* slots_ins = addName(lir->insLoad(LIR_ldp, fp_ins, offsetof(JSStackFrame, slots)),
                              "slots");
    for (unsigned i = 0; i < fp->script->nfixed; i++)
        slurpSlot(lir->insLoad(LIR_ldp, slots_ins, i * sizeof(jsval)), &fp->slots[i], &info);
    /* stack vals */
    unsigned nfixed = fp->script->nfixed;
    jsval* stack = StackBase(fp);
    LIns* stack_ins = addName(lir->ins2(LIR_piadd,
                                        slots_ins,
                                        INS_CONSTWORD(nfixed * sizeof(jsval))),
                              "stackBase");
    size_t limit = size_t(fp->regs->sp - StackBase(fp));
    if (anchor && anchor->exitType == RECURSIVE_SLURP_FAIL_EXIT)
        limit--;
    else
        limit -= fp->fun->nargs + 2;
    for (size_t i = 0; i < limit; i++)
        slurpSlot(lir->insLoad(LIR_ldp, stack_ins, i * sizeof(jsval)), &stack[i], &info);

    JS_ASSERT(info.curSlot == downPostSlots);

    /* Jump back to the start */
    exit = copy(exit);
    exit->exitType = UNSTABLE_LOOP_EXIT;
#if defined JS_JIT_SPEW
    TreevisLogExit(cx, exit);
#endif

    RecursiveSlotMap slotMap(*this, downPostSlots, rval_ins);
    for (unsigned i = 0; i < downPostSlots; i++)
        slotMap.addSlot(typeMap[i]);
    slotMap.addSlot(&stackval(-1), typeMap[downPostSlots]);
    VisitGlobalSlots(slotMap, cx, *tree->globalSlots);
    debug_only_print0(LC_TMTracer, "Compiling up-recursive slurp...\n");
    exit = copy(exit);
    if (exit->recursive_pc == fragment->root->ip)
        exit->exitType = UNSTABLE_LOOP_EXIT;
    else
        exit->exitType = RECURSIVE_UNLINKED_EXIT;
    debug_only_printf(LC_TMTreeVis, "TREEVIS CHANGEEXIT EXIT=%p TYPE=%s\n", (void*)exit,
                      getExitName(exit->exitType));
    JS_ASSERT(tree->recursion >= Recursion_Unwinds);
    return closeLoop(slotMap, exit);
}
Пример #20
0
std::exception_ptr rt_kafka_link_t::get_closing_error() {
	std::unique_lock<mutex_t> guard(closing_error_lock_);
	return closing_error_;
}
Пример #21
0
OID AuthorizationManagerImpl::getCacheGeneration() {
    CacheGuard guard(this, CacheGuard::fetchSynchronizationManual);
    return _cacheGeneration;
}
Пример #22
0
void PSPSaveDialog::DisplaySaveDataInfo2(bool showNewData) {
	std::lock_guard<std::mutex> guard(paramLock);

	tm modif_time;
	const char *save_title;
	u32 data_size;

	if (showNewData || param.GetFileInfo(currentSelectedSave).size == 0) {
		time_t t;
		time(&t);
		localtime_r(&t, &modif_time);
		save_title = param.GetPspParam()->sfoParam.savedataTitle;
		// TODO: Account for icon, etc., etc.
		data_size = param.GetPspParam()->dataSize;
	} else {
		modif_time = param.GetFileInfo(currentSelectedSave).modif_time;
		save_title = param.GetFileInfo(currentSelectedSave).saveTitle;
		data_size = param.GetFileInfo(currentSelectedSave).size;
	}

	char date[256];
	char am_pm[] = "AM";
	char hour_time[10] ;
	int hour = modif_time.tm_hour;
	int min  = modif_time.tm_min;
	switch (g_Config.iTimeFormat) {
	case 1:
		if (hour > 12) {
			strcpy(am_pm, "PM");
			hour -= 12;
		}
		snprintf(hour_time, 10, "%02d:%02d %s", hour, min, am_pm);
		break;
	case 2:
		snprintf(hour_time, 10, "%02d:%02d", hour, min);
		break;
	default:
		if (hour > 12) {
			strcpy(am_pm, "PM");
			hour -= 12;
		}
		snprintf(hour_time, 10, "%02d:%02d %s", hour, min, am_pm);
	}

	int day   = modif_time.tm_mday;
	int month = modif_time.tm_mon + 1;
	int year  = modif_time.tm_year + 1900;
	s64 sizeK = data_size / 1024;
	switch (g_Config.iDateFormat) {
	case 1:
		snprintf(date, 256, "%d/%02d/%02d", year, month, day);
		break;
	case 2:
		snprintf(date, 256, "%02d/%02d/%d", month, day, year);
		break;
	case 3:
		snprintf(date, 256, "%02d/%02d/%d", day, month, year);
		break;
	default:
		snprintf(date, 256, "%d/%02d/%02d", year, month, day);
	}

	std::string saveinfoTxt = StringFromFormat("%.128s\n%s  %s\n%lld KB", save_title, date, hour_time, sizeK);
	PPGeDrawText(saveinfoTxt.c_str(), 9, 202, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0x80000000));
	PPGeDrawText(saveinfoTxt.c_str(), 8, 200, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0xFFFFFFFF));
}
Пример #23
0
int PSPSaveDialog::Update(int animSpeed)
{
	if (GetStatus() != SCE_UTILITY_STATUS_RUNNING)
		return SCE_ERROR_UTILITY_INVALID_STATUS;

	if (!param.GetPspParam()) {
		ChangeStatusShutdown(SAVEDATA_SHUTDOWN_DELAY_US);
		return 0;
	}

	if (pendingStatus != SCE_UTILITY_STATUS_RUNNING) {
		// We're actually done, we're just waiting to tell the game that.
		return 0;
	}

	// The struct may have been updated by the game.  This happens in "Where Is My Heart?"
	// Check if it has changed, reload it.
	// TODO: Cut down on preloading?  This rebuilds the list from scratch.
	int size = Memory::Read_U32(requestAddr);
	if (memcmp(Memory::GetPointer(requestAddr), &originalRequest, size) != 0) {
		memset(&request, 0, sizeof(request));
		Memory::Memcpy(&request, requestAddr, size);
		Memory::Memcpy(&originalRequest, requestAddr, size);
		std::lock_guard<std::mutex> guard(paramLock);
		param.SetPspParam(&request);
	}

	UpdateButtons();
	UpdateFade(animSpeed);

	okButtonImg = I_CIRCLE;
	cancelButtonImg = I_CROSS;
	okButtonFlag = CTRL_CIRCLE;
	cancelButtonFlag = CTRL_CROSS;
	if (param.GetPspParam()->common.buttonSwap == 1) {
		okButtonImg = I_CROSS;
		cancelButtonImg = I_CIRCLE;
		okButtonFlag = CTRL_CROSS;
		cancelButtonFlag = CTRL_CIRCLE;
	}

	I18NCategory *di = GetI18NCategory("Dialog");

	switch (display)
	{
		case DS_SAVE_LIST_CHOICE:
			StartDraw();

			DisplaySaveList();
			DisplaySaveDataInfo1();

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_SAVE);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
				StartFade(false);
			} else if (IsButtonPressed(okButtonFlag)) {
				// Save exist, ask user confirm
				if (param.GetFileInfo(currentSelectedSave).size > 0) {
					yesnoChoice = 0;
					display = DS_SAVE_CONFIRM_OVERWRITE;
				} else {
					display = DS_SAVE_SAVING;
					StartIOThread();
				}
			}
			EndDraw();
		break;
		case DS_SAVE_CONFIRM:
			StartDraw();

			DisplaySaveIcon(false);
			DisplaySaveDataInfo2(true);

			DisplayMessage(di->T("Confirm Save", "Do you want to save this data?"), true);

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_SAVE);

			if (IsButtonPressed(cancelButtonFlag) || (IsButtonPressed(okButtonFlag) && yesnoChoice == 0)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
				StartFade(false);
			} else if (IsButtonPressed(okButtonFlag)) {
				display = DS_SAVE_SAVING;
				StartIOThread();
			}

			EndDraw();
		break;
		case DS_SAVE_CONFIRM_OVERWRITE:
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("Confirm Overwrite","Do you want to overwrite the data?"), true);

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_SAVE);

			if (IsButtonPressed(cancelButtonFlag) || (IsButtonPressed(okButtonFlag) && yesnoChoice == 0)) {
				if (param.GetPspParam()->mode != SCE_UTILITY_SAVEDATA_TYPE_SAVE)
					display = DS_SAVE_LIST_CHOICE;
				else {
					param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
					StartFade(false);
				}
			} else if (IsButtonPressed(okButtonFlag)) {
				display = DS_SAVE_SAVING;
				StartIOThread();
			}

			EndDraw();
		break;
		case DS_SAVE_SAVING:
			if (ioThreadStatus != SAVEIO_PENDING) {
				JoinIOThread();
			}

			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2(true);

			DisplayMessage(di->T("Saving","Saving\nPlease Wait..."));

			DisplayBanner(DB_SAVE);

			EndDraw();
		break;
		case DS_SAVE_FAILED:
			JoinIOThread();
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2(true);

			DisplayMessage(di->T("SavingFailed", "Unable to save data."));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_SAVE);

			if (IsButtonPressed(cancelButtonFlag)) {
				// Go back to the list so they can try again.
				if (param.GetPspParam()->mode != SCE_UTILITY_SAVEDATA_TYPE_SAVE) {
					display = DS_SAVE_LIST_CHOICE;
				} else {
					param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
					StartFade(false);
				}
			}

			EndDraw();
		break;
		case DS_SAVE_DONE:
			if (ioThread) {
				JoinIOThread();
				param.SetPspParam(param.GetPspParam());
			}
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2(true);

			DisplayMessage(di->T("Save completed"));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_SAVE);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_SUCCESS;
				// Set the save to use for autosave and autoload
				param.SetSelectedSave(param.GetFileInfo(currentSelectedSave).idx);
				StartFade(false);
			}

			EndDraw();
		break;

		case DS_LOAD_LIST_CHOICE:
			StartDraw();
			
			DisplaySaveList();
			DisplaySaveDataInfo1();

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_LOAD);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
				StartFade(false);
			} else if (IsButtonPressed(okButtonFlag)) {
				display = DS_LOAD_LOADING;
				StartIOThread();
			}

			EndDraw();
		break;
		case DS_LOAD_CONFIRM:
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("ConfirmLoad", "Load this data?"), true);

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_LOAD);

			if (IsButtonPressed(cancelButtonFlag) || (IsButtonPressed(okButtonFlag) && yesnoChoice == 0)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
				StartFade(false);
			} else if (IsButtonPressed(okButtonFlag)) {
				display = DS_LOAD_LOADING;
				StartIOThread();
			}

			EndDraw();
		break;
		case DS_LOAD_LOADING:
			if (ioThreadStatus != SAVEIO_PENDING) {
				JoinIOThread();
			}

			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("Loading","Loading\nPlease Wait..."));

			DisplayBanner(DB_LOAD);

			EndDraw();
		break;
		case DS_LOAD_FAILED:
			JoinIOThread();
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("LoadingFailed", "Unable to load data."));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_LOAD);

			if (IsButtonPressed(cancelButtonFlag)) {
				// Go back to the list so they can try again.
				if (param.GetPspParam()->mode != SCE_UTILITY_SAVEDATA_TYPE_LOAD) {
					display = DS_LOAD_LIST_CHOICE;
				} else {
					param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
					StartFade(false);
				}
			}

			EndDraw();
		break;
		case DS_LOAD_DONE:
			JoinIOThread();
			StartDraw();
			
			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("Load completed"));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_LOAD);

			// Allow OK to be pressed as well to confirm the save.
			// The PSP only allows cancel, but that's generally not great UX.
			// Allowing this here makes it quicker for most users to get into the actual game.
			if (IsButtonPressed(cancelButtonFlag) || IsButtonPressed(okButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_SUCCESS;
				// Set the save to use for autosave and autoload
				param.SetSelectedSave(param.GetFileInfo(currentSelectedSave).idx);
				StartFade(false);
			}

			EndDraw();
		break;
		case DS_LOAD_NODATA:
			StartDraw();

			DisplayMessage(di->T("There is no data"));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_LOAD);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_SAVEDATA_ERROR_LOAD_NO_DATA;
				StartFade(false);
			}

			EndDraw();
		break;

		case DS_DELETE_LIST_CHOICE:
			StartDraw();
			
			DisplaySaveList();
			DisplaySaveDataInfo1();

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_DELETE);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_DIALOG_RESULT_CANCEL;
				StartFade(false);
			} else if (IsButtonPressed(okButtonFlag)) {
				yesnoChoice = 0;
				display = DS_DELETE_CONFIRM;
			}

			EndDraw();
		break;
		case DS_DELETE_CONFIRM:
			StartDraw();

			DisplaySaveIcon(true);
			DisplaySaveDataInfo2();

			DisplayMessage(di->T("DeleteConfirm", 
						"This save data will be deleted.\nAre you sure you want to continue?"), 
						true);

			DisplayButtons(DS_BUTTON_OK | DS_BUTTON_CANCEL);
			DisplayBanner(DB_DELETE);

			if (IsButtonPressed(cancelButtonFlag))
				display = DS_DELETE_LIST_CHOICE;
			else if (IsButtonPressed(okButtonFlag)) {
				if (yesnoChoice == 0)
					display = DS_DELETE_LIST_CHOICE;
				else {
					display = DS_DELETE_DELETING;
					StartIOThread();
				}
			}

			EndDraw();
		break;
		case DS_DELETE_DELETING:
			if (ioThreadStatus != SAVEIO_PENDING) {
				JoinIOThread();
			}

			StartDraw();

			DisplayMessage(di->T("Deleting","Deleting\nPlease Wait..."));

			DisplayBanner(DB_DELETE);

			EndDraw();
		break;
		case DS_DELETE_FAILED:
			JoinIOThread();
			StartDraw();

			DisplayMessage(di->T("DeleteFailed", "Unable to delete data."));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_DELETE);

			if (IsButtonPressed(cancelButtonFlag)) {
				display = DS_DELETE_LIST_CHOICE;
			}

			EndDraw();
		break;
		case DS_DELETE_DONE:
			if (ioThread) {
				JoinIOThread();
				param.SetPspParam(param.GetPspParam());
			}
			StartDraw();
			
			DisplayMessage(di->T("Delete completed"));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_DELETE);

			if (IsButtonPressed(cancelButtonFlag)) {
				if (param.GetFilenameCount() == 0)
					display = DS_DELETE_NODATA;
				else
					display = DS_DELETE_LIST_CHOICE;
			}

			EndDraw();
		break;
		case DS_DELETE_NODATA:
			StartDraw();
			
			DisplayMessage(di->T("There is no data"));

			DisplayButtons(DS_BUTTON_CANCEL);
			DisplayBanner(DB_DELETE);

			if (IsButtonPressed(cancelButtonFlag)) {
				param.GetPspParam()->common.result = SCE_UTILITY_SAVEDATA_ERROR_DELETE_NO_DATA;
				StartFade(false);
			}

			EndDraw();
		break;

		case DS_NONE: // For action which display nothing
			switch (ioThreadStatus) {
			case SAVEIO_NONE:
				StartIOThread();
				break;
			case SAVEIO_PENDING:
			case SAVEIO_DONE:
				// To make sure there aren't any timing variations, we sync the next frame.
				JoinIOThread();
				ChangeStatus(SCE_UTILITY_STATUS_FINISHED, 0);
				break;
			}
		break;

		default:
			ChangeStatus(SCE_UTILITY_STATUS_FINISHED, 0);
		break;
	}

	if (status == SCE_UTILITY_STATUS_FINISHED || pendingStatus == SCE_UTILITY_STATUS_FINISHED)
		Memory::Memcpy(requestAddr, &request, request.common.size);
	
	return 0;
}
Пример #24
0
std::string CachingFileLoader::Path() const {
	lock_guard guard(backendMutex_);
	return backend_->Path();
}
Пример #25
0
void PSPSaveDialog::DisplaySaveDataInfo1()
{
	std::lock_guard<std::mutex> guard(paramLock);
	if (param.GetFileInfo(currentSelectedSave).size == 0) {
		I18NCategory *di = GetI18NCategory("Dialog");
		PPGeDrawText(di->T("NEW DATA"), 180, 136, PPGE_ALIGN_VCENTER, 0.6f, CalcFadedColor(0xFFFFFFFF));
	} else {
		char title[512];
		char time[512];
		char saveTitle[1024];
		char saveDetail[1024];

		char am_pm[] = "AM";
		char hour_time[10] ;
		int hour = param.GetFileInfo(currentSelectedSave).modif_time.tm_hour;
		int min  = param.GetFileInfo(currentSelectedSave).modif_time.tm_min;
		switch (g_Config.iTimeFormat) {
		case 1:
			if (hour > 12) {
				strcpy(am_pm, "PM");
				hour -= 12;
			}
			snprintf(hour_time,10,"%02d:%02d %s", hour, min, am_pm);
			break;
		case 2:
			snprintf(hour_time,10,"%02d:%02d", hour, min); 
			break;
		default:
			if (hour > 12) {
				strcpy(am_pm, "PM");
				hour -= 12;
			}
			snprintf(hour_time,10,"%02d:%02d %s", hour, min, am_pm);
		}

		snprintf(title, sizeof(title), "%s", param.GetFileInfo(currentSelectedSave).title);
		int day   = param.GetFileInfo(currentSelectedSave).modif_time.tm_mday;
		int month = param.GetFileInfo(currentSelectedSave).modif_time.tm_mon + 1;
		int year  = param.GetFileInfo(currentSelectedSave).modif_time.tm_year + 1900;
		s64 sizeK = param.GetFileInfo(currentSelectedSave).size / 1024;
		switch (g_Config.iDateFormat) {
		case 1:
			snprintf(time, sizeof(time), "%d/%02d/%02d   %s  %lld KB", year, month, day, hour_time, sizeK);
			break;
		case 2:
			snprintf(time, sizeof(time), "%02d/%02d/%d   %s  %lld KB", month, day, year, hour_time, sizeK);
			break;
		case 3:
			snprintf(time, sizeof(time), "%02d/%02d/%d   %s  %lld KB", day, month, year, hour_time, sizeK);
			break;
		default:
			snprintf(time, sizeof(time), "%d/%02d/%02d   %s  %lld KB", year, month, day, hour_time, sizeK);
		}
		snprintf(saveTitle, sizeof(saveTitle), "%s", param.GetFileInfo(currentSelectedSave).saveTitle);
		snprintf(saveDetail, sizeof(saveDetail), "%s", param.GetFileInfo(currentSelectedSave).saveDetail);

		PPGeDrawRect(180, 136, 480, 137, CalcFadedColor(0xFFFFFFFF));
		std::string titleTxt = title;
		std::string timeTxt = time;
		std::string saveTitleTxt = saveTitle;
		std::string saveDetailTxt = saveDetail;

		PPGeDrawText(titleTxt.c_str(), 181, 138, PPGE_ALIGN_BOTTOM, 0.6f, CalcFadedColor(0x80000000));
		PPGeDrawText(titleTxt.c_str(), 180, 136, PPGE_ALIGN_BOTTOM, 0.6f, CalcFadedColor(0xFFC0C0C0));
		PPGeDrawText(timeTxt.c_str(), 181, 139, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0x80000000));
		PPGeDrawText(timeTxt.c_str(), 180, 137, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0xFFFFFFFF));
		PPGeDrawText(saveTitleTxt.c_str(), 176, 162, PPGE_ALIGN_LEFT, 0.55f, CalcFadedColor(0x80000000));
		PPGeDrawText(saveTitleTxt.c_str(), 175, 159, PPGE_ALIGN_LEFT, 0.55f, CalcFadedColor(0xFFFFFFFF));
		PPGeDrawText(saveDetailTxt.c_str(), 176, 183, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0x80000000));
		PPGeDrawText(saveDetailTxt.c_str(), 175, 181, PPGE_ALIGN_LEFT, 0.5f, CalcFadedColor(0xFFFFFFFF));
	}
}
Пример #26
0
bool CJob::wasCancelled() const {
    CMutexLocker guard(CThreadPool::Get().m_mutex);
    return m_eState == CANCELLED;
}
Пример #27
0
void CThreadPool::cancelJobs(const std::set<CJob*>& jobs) {
    // Thanks to the mutex, jobs cannot change state anymore. There are
    // three different states which can occur:
    //
    // READY: The job is still in our list of pending jobs and no threads
    // got it yet. Just clean up.
    //
    // DONE: The job finished running and was already written to the pipe
    // that is used for waking up finished jobs. We can just read from the
    // pipe until we see this job.
    //
    // RUNNING: This is the complicated case. The job is currently being
    // executed. We change its state to CANCELLED so that wasCancelled()
    // returns true. Afterwards we wait on a CV for the job to have finished
    // running. This CV is signaled by jobDone() which checks the job's
    // status and sees that the job was cancelled. It signals to us that
    // cancellation is done by changing the job's status to DONE.

    CMutexLocker guard(m_mutex);
    std::set<CJob*> wait, finished, deleteLater;
    std::set<CJob*>::const_iterator it;

    // Start cancelling all jobs
    for (it = jobs.begin(); it != jobs.end(); ++it) {
        switch ((*it)->m_eState) {
            case CJob::READY: {
                (*it)->m_eState = CJob::CANCELLED;

                // Job wasn't started yet, must be in the queue
                std::list<CJob*>::iterator it2 =
                    std::find(m_jobs.begin(), m_jobs.end(), *it);
                assert(it2 != m_jobs.end());
                m_jobs.erase(it2);
                deleteLater.insert(*it);
                continue;
            }

            case CJob::RUNNING:
                (*it)->m_eState = CJob::CANCELLED;
                wait.insert(*it);
                continue;

            case CJob::DONE:
                (*it)->m_eState = CJob::CANCELLED;
                finished.insert(*it);
                continue;

            case CJob::CANCELLED:
            default:
                assert(0);
        }
    }

    // Now wait for cancellation to be done

    // Collect jobs that really were cancelled. Finished cancellation is
    // signaled by changing their state to DONE.
    while (!wait.empty()) {
        it = wait.begin();
        while (it != wait.end()) {
            if ((*it)->m_eState != CJob::CANCELLED) {
                assert((*it)->m_eState == CJob::DONE);
                // Re-set state for the destructor
                (*it)->m_eState = CJob::CANCELLED;
                deleteLater.insert(*it);
                wait.erase(it++);
            } else
                it++;
        }

        if (wait.empty()) break;

        // Then wait for more to be done
        m_cancellationCond.wait(m_mutex);
    }

    // We must call destructors with m_mutex unlocked so that they can call
    // wasCancelled()
    guard.unlock();

    // Handle finished jobs. They must already be in the pipe.
    while (!finished.empty()) {
        CJob* job = getJobFromPipe();
        if (finished.erase(job) > 0) {
            assert(job->m_eState == CJob::CANCELLED);
            delete job;
        } else
            finishJob(job);
    }

    // Delete things that still need to be deleted
    while (!deleteLater.empty()) {
        delete *deleteLater.begin();
        deleteLater.erase(deleteLater.begin());
    }
}
Пример #28
0
string g_GetPasswordFromConsole(const string& prompt)
{
    string      password;
    CMutex      lock;
    CMutexGuard guard(lock);

#if defined(NCBI_OS_UNIX)
    // UNIX implementation

#if defined(HAVE_READPASSPHRASE)

    char password_buffer[1024];
    char* raw_password = readpassphrase(prompt.c_str(), password_buffer,
                                        sizeof(password_buffer),
                                        RPP_ECHO_OFF | RPP_REQUIRE_TTY);

#elif defined(HAVE_GETPASSPHRASE)

    char* raw_password = getpassphrase(prompt.c_str());

#elif defined(HAVE_GETPASS)

    char* raw_password = getpass(prompt.c_str());

#else
#  error "Unsupported Unix platform; the getpass, getpassphrase, and readpassphrase functions are all absent"
#endif

    if (!raw_password)
        NCBI_THROW
            (CGetPasswordFromConsoleException, eGetPassError,
             "g_GetPasswordFromConsole(): error getting password");
    password = string(raw_password);

#elif defined(NCBI_OS_MSWIN)
    // Windows implementation

    for (size_t index = 0;  index < prompt.size();  ++index) {
        _putch(prompt[index]);
    }

    for (;;) {
        char ch;
        ch = _getch();
        if (ch == '\r'  ||  ch == '\n')
            break;
        if (ch == '\003')
            NCBI_THROW(CGetPasswordFromConsoleException, eKeyboardInterrupt,
                       "g_GetPasswordFromConsole(): keyboard interrupt");
        if (ch == '\b') {
            if ( !password.empty() ) {
                password.resize(password.size() - 1);
            }
        }
        else
            password.append(1, ch);
    }

    _putch('\r');
    _putch('\n');
#endif

    return password;
}
Пример #29
0
/**
 *
 * Test program and example for guarded logs.
 *
 */
int main(int argc, char *argv[])
{
    maci::SimpleClient client;

    if (client.init(argc,argv) == 0)
	{
	return -1;
	}
    else
	{
	// Log into the manager before doing anything
	client.login();
	}

    /*****************************************************************/
    /*
     * This example guards a log
     * produced using any subclass of Logging::BaseLog
     * These are the normal logs
     *
     * All examples follow this same pattern
     */

    /*
     * 1. The first step is to instantiate the guard template.
     * In this case the guarding is not done for multiple
     * executions of this function, since it is the main().
     * 
     * In that case we would have to declare the guard as static.
     * The same applies to all following examples
     *
     * This approach also allows to use the same guard for multiple logs
     * (as long as they are of the same logger type)
     */
    Logging::RepeatGuardLogger<Logging::BaseLog> guardbl(10000000,10);

    /*
     * 2. We get the standard logger for this "object"
     *    and we make a simple normal log, just to see that it works. 
     */
    Logging::Logger::LoggerSmartPtr logger = getLogger();
    logger->log(Logging::Logger::LM_INFO, "Simple test.",
	       __FILE__,__LINE__,
	       "main");

    /*
     * 3. Finally we make a loop with the guarded log
     */
    for(int i=0;i<50;i++)
	{
	guardbl.log(logger, Logging::Logger::LM_INFO, 
		    "Log A without incrementing",
		    __FILE__,__LINE__,
		    "main");
	guardbl.log(logger, Logging::Logger::LM_INFO, 
		    "Log B without incrementing",
		    __FILE__,__LINE__,
		    "main");
	guardbl.logAndIncrement(logger, Logging::Logger::LM_INFO, 
		    "LogAndIncrement",
		    __FILE__,__LINE__,
		    "main");
	}

    /*****************************************************************/
    /*
     * This example guards a type-safe log
     * produced using any subclass of Logging::TypeSafeLog
     */

    Logging::RepeatGuardLogger<Logging::TypeSafeLog> guard(10000000,10);

    repeatGuardLogTypeExample::simpleLog my_simpleLog(__FILE__,__LINE__,"main");
    my_simpleLog.log();


    guard.log(my_simpleLog);

    for(int i=0;i<50;i++)
	{
	guard.logAndIncrement(my_simpleLog);
	}

    /*****************************************************************/
    /*
     * This example guards the logging of an exception
     * produced using any subclass of ACSErr::ACSbaseExImpl
     */


    Logging::RepeatGuardLogger<ACSErr::ACSbaseExImpl> guardex(10000000,10);

    ACSErrTypeCommon::GenericErrorExImpl displayMessageEx(
	__FILE__, __LINE__, "main");
    displayMessageEx.log();


    guardex.log(displayMessageEx);

    for(int i=0;i<50;i++)
	{
	guardex.logAndIncrement(displayMessageEx);
	}

    /*****************************************************************/
    client.logout();

    return 0;

}
Пример #30
-1
static NTSTATUS DOKAN_CALLBACK
FuseGetFileSecurity(LPCWSTR FileName, PSECURITY_INFORMATION SecurityInformation,
                    PSECURITY_DESCRIPTOR SecurityDescriptor, ULONG BufferLength,
                    PULONG LengthNeeded, PDOKAN_FILE_INFO DokanFileInfo) {
    impl_fuse_context *impl = the_impl;
    if (impl->debug())
        FPRINTF(stderr, "GetFileSecurity: " PRIxDWORD "\n", *SecurityInformation);

    BY_HANDLE_FILE_INFORMATION byHandleFileInfo;
    ZeroMemory(&byHandleFileInfo, sizeof(BY_HANDLE_FILE_INFORMATION));

    int ret;
    {
        impl_chain_guard guard(impl, DokanFileInfo->ProcessId);
        ret =
            impl->get_file_information(FileName, &byHandleFileInfo, DokanFileInfo);
    }

    if (0 != ret) {
        return errno_to_ntstatus_error(ret);
    }

    if (byHandleFileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        // We handle directories for the Explorer's
        // context menu. (New Folder, ...)

        // Authenticated users rights
        PSECURITY_DESCRIPTOR SecurityDescriptorTmp = nullptr;
        ULONG Size = 0;
        if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
                    "D:PAI(A;OICI;FA;;;AU)", SDDL_REVISION_1, &SecurityDescriptorTmp,
                    &Size)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        LPTSTR pStringBuffer = nullptr;
        if (!ConvertSecurityDescriptorToStringSecurityDescriptor(
                    SecurityDescriptorTmp, SDDL_REVISION_1, *SecurityInformation,
                    &pStringBuffer, nullptr)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        LocalFree(SecurityDescriptorTmp);
        SecurityDescriptorTmp = nullptr;
        Size = 0;
        if (!ConvertStringSecurityDescriptorToSecurityDescriptor(
                    pStringBuffer, SDDL_REVISION_1, &SecurityDescriptorTmp, &Size)) {
            return STATUS_NOT_IMPLEMENTED;
        }

        if (Size > BufferLength) {
            *LengthNeeded = Size;
            return STATUS_BUFFER_OVERFLOW;
        }

        memcpy(SecurityDescriptor, SecurityDescriptorTmp, Size);
        *LengthNeeded = Size;

        if (pStringBuffer != nullptr)
            LocalFree(pStringBuffer);
        if (SecurityDescriptorTmp != nullptr)
            LocalFree(SecurityDescriptorTmp);

        return STATUS_SUCCESS;
    }
    return STATUS_NOT_IMPLEMENTED;
}