already_AddRefed<DetailedPromise> MediaKeys::Init(ErrorResult& aRv) { RefPtr<DetailedPromise> promise(MakePromise(aRv, NS_LITERAL_CSTRING("MediaKeys::Init()"))); if (aRv.Failed()) { return nullptr; } mProxy = new CDMProxy(this, mKeySystem); // Determine principal (at creation time) of the MediaKeys object. nsCOMPtr<nsIScriptObjectPrincipal> sop = do_QueryInterface(GetParentObject()); if (!sop) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get script principal in MediaKeys::Init")); return promise.forget(); } mPrincipal = sop->GetPrincipal(); // Determine principal of the "top-level" window; the principal of the // page that will display in the URL bar. nsCOMPtr<nsPIDOMWindowInner> window = GetParentObject(); if (!window) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get top-level window in MediaKeys::Init")); return promise.forget(); } nsCOMPtr<nsPIDOMWindowOuter> top = window->GetOuterWindow()->GetTop(); if (!top || !top->GetExtantDoc()) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get document in MediaKeys::Init")); return promise.forget(); } mTopLevelPrincipal = top->GetExtantDoc()->NodePrincipal(); if (!mPrincipal || !mTopLevelPrincipal) { NS_WARNING("Failed to get principals when creating MediaKeys"); promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get principal(s) in MediaKeys::Init")); return promise.forget(); } nsAutoString origin; nsresult rv = nsContentUtils::GetUTFOrigin(mPrincipal, origin); if (NS_FAILED(rv)) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get principal origin string in MediaKeys::Init")); return promise.forget(); } nsAutoString topLevelOrigin; rv = nsContentUtils::GetUTFOrigin(mTopLevelPrincipal, topLevelOrigin); if (NS_FAILED(rv)) { promise->MaybeReject(NS_ERROR_DOM_INVALID_STATE_ERR, NS_LITERAL_CSTRING("Couldn't get top-level principal origin string in MediaKeys::Init")); return promise.forget(); } nsIDocument* doc = window->GetExtantDoc(); const bool inPrivateBrowsing = nsContentUtils::IsInPrivateBrowsing(doc); EME_LOG("MediaKeys[%p]::Create() (%s, %s), %s", this, NS_ConvertUTF16toUTF8(origin).get(), NS_ConvertUTF16toUTF8(topLevelOrigin).get(), (inPrivateBrowsing ? "PrivateBrowsing" : "NonPrivateBrowsing")); // The CDMProxy's initialization is asynchronous. The MediaKeys is // refcounted, and its instance is returned to JS by promise once // it's been initialized. No external refs exist to the MediaKeys while // we're waiting for the promise to be resolved, so we must hold a // reference to the new MediaKeys object until it's been created, // or its creation has failed. Store the id of the promise returned // here, and hold a self-reference until that promise is resolved or // rejected. MOZ_ASSERT(!mCreatePromiseId, "Should only be created once!"); mCreatePromiseId = StorePromise(promise); AddRef(); mProxy->Init(mCreatePromiseId, origin, topLevelOrigin, KeySystemToGMPName(mKeySystem), inPrivateBrowsing, new MediaKeysGMPCrashHelper(this)); return promise.forget(); }
BasicPacketFlow::BasicPacketFlow(Process* p, IHXSessionStats* pSessionStats, UINT16 unStreamCount, PacketFlowManager* pFlowMgr, BOOL bIsMulticast) : m_tvBankedPlayTime(0,0) { m_pProc = p; m_pFlowMgr = pFlowMgr; m_unStreamCount = unStreamCount; m_uNumStreamsRegistered = 0; m_ulRefCount = 0; m_bPaused = FALSE; m_bInSeek = FALSE; m_bInitialSubscriptionDone = FALSE; m_bInitialPlayReceived = FALSE; m_bGetPacketsOutstanding = FALSE; m_tTimeLineStart.tv_sec = 0; m_tTimeLineStart.tv_usec = 0; m_bTimeLineSuspended = TRUE; m_bIsMulticast = bIsMulticast; m_ulPacketsOutstanding = 0; m_fDeliveryRatio = 1.0; m_bSourceIsDone = FALSE; m_ulNumStreamDones = 0; m_uEndPoint = 0; m_bIsPausePointSet = FALSE; m_bIsDone = FALSE; m_ulResendIDPosition = 0; m_bSubscribed = FALSE; m_bAutoSubscription = TRUE; m_ulWouldBlocking = 0; m_bWouldBlockAvailable = FALSE; m_pConvertShim = 0; m_pConvertingPacket = NULL; m_bPlayPendingOnSeek = FALSE; m_pPlayerControl = NULL; m_pPlayerSessionId = NULL; m_pRateManager = NULL; m_bSeekPacketPending = FALSE; m_bSessionPlaying = FALSE; m_bDeliveryBandwidthSet = FALSE; m_pStats = pSessionStats; m_pStats->AddRef(); m_bRTPInfoRequired = TRUE; m_uFirstStreamRegistered = 0xFFFF; m_ulSetDeliveryBandwidth = 0; m_ulBandwidth = 0; memset(m_pResendIDs, 0, sizeof(UINT32) * MAX_RESENDS_PER_SECOND); // Contorted initialization due to NT not able to intialize array // elements on creation even though it is standard C++ m_pStreams = new PacketStream[unStreamCount]; // then the intialization for (UINT16 iStream = 0; iStream < unStreamCount; iStream++) m_pStreams[iStream].SetFlow(this); // get clock for PlayTime tracking if (HXR_OK != m_pProc->pc->server_context-> QueryInterface(IID_IHXAccurateClock, (void**) &m_pAccurateClock)) { // system doesn't have accurate clock, use our own. AddRef(); m_pAccurateClock = (IHXAccurateClock*) this; } // for safety, initialize this to current time, although we really // set it in Play(). HXTimeval hxt = m_pAccurateClock->GetTimeOfDay(); m_tvRTSPPlayTime.tv_sec = hxt.tv_sec; m_tvRTSPPlayTime.tv_usec = hxt.tv_usec; }
AwtTextComponent::OleCallback::OleCallback() { m_refs = 0; AddRef(); }
/** default (NULL) construct or construct from a raw pointer */ FORCEINLINE CCountedPtr(Tcls *pObj = NULL) : m_pT(pObj) {AddRef();}
void CchaffIGC::Terminate(void) { AddRef(); TmodelIGC<IchaffIGC>::Terminate(); Release(); }
void RocketDocument3D::AddReference() { AddRef(); }
GDIFontRasterizer::GDIFontRasterizer() : RefCount(0), FontDC(NULL), NonBoldFontDC(NULL), LastBitmap(NULL), ChAntialiasMethodInit(false) , ChUseResampling(false), ChAntialiasMethod(camResample8) { AddRef(); }
///////////////////////////////////////////////////////////////////////// // Method: // IUnknown::QueryInterface // Purpose: // Implement this to export the interfaces supported by your // object. // STDMETHODIMP FileObjectWrapper::QueryInterface(REFIID riid, void** ppvObj) { if (IsEqualIID(riid, IID_IUnknown)) { AddRef(); *ppvObj = (IUnknown*)(IHXFileObject *)this; return HXR_OK; } else if (IsEqualIID(riid, IID_IHXFileObject)) { if(m_has_file_object) { AddRef(); *ppvObj = (IHXFileObject*)this; return HXR_OK; } } else if (IsEqualIID(riid, IID_IHXFileStat)) { if(m_has_file_stat) { AddRef(); *ppvObj = (IHXFileStat*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXFileExists)) { if(m_has_file_exists) { AddRef(); *ppvObj = (IHXFileExists*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXFileMimeMapper)) { if(m_has_file_mime_mapper) { AddRef(); *ppvObj = (IHXFileMimeMapper*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXBroadcastMapper)) { if(m_has_broadcast_mapper) { AddRef(); *ppvObj = (IHXBroadcastMapper*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXGetFileFromSamePool)) { if(m_has_pool_object) { AddRef(); *ppvObj = (IHXGetFileFromSamePool*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXRequestHandler)) { if(m_has_request_handler) { AddRef(); *ppvObj = (IHXRequestHandler*)this; return HXR_OK; } } else if(IsEqualIID(riid, IID_IHXPostDataHandler)) { if(m_has_post_data_handler) { AddRef(); *ppvObj = (IHXPostDataHandler*)this; return HXR_OK; } } *ppvObj = NULL; return HXR_NOINTERFACE; }
HX_RESULT StaticPushSource::Init(IHXPSinkControl* pSink) { HX_RESULT h_result = HXR_OK; IHXFileObject* pFileObject; IHXBandwidthNegotiator* pBandwidthNegotiator; pSink->AddRef(); m_pSinkControl = pSink; AddRef(); if (HXR_OK == h_result) { if(HXR_OK == m_pFileObject->QueryInterface(IID_IHXFileObject, (void**)&pFileObject)) { if(m_pBWEValues && (HXR_OK == m_pFileFormat->QueryInterface( IID_IHXBandwidthNegotiator, (void**)&pBandwidthNegotiator))) { pBandwidthNegotiator->SetBandwidthInfo(m_pBWEValues); pBandwidthNegotiator->Release(); m_pBWEValues->Release(); m_pBWEValues = NULL; } h_result = m_pFileFormat->InitFileFormat(m_pRequest, this, pFileObject); /* * The IHXFileObject belongs to the IHXFileFormatObject... */ HX_RELEASE(m_pFileObject); HX_RELEASE(pFileObject); /* * so does the IHXRequest */ HX_RELEASE(m_pRequest); if (HXR_OK != h_result) { ERRMSG(m_proc->pc->error_handler, "File Format initialization failed\n"); m_pFileFormat->Close(); m_pFileFormat->Release(); m_pFileFormat = 0; } } } Release(); return h_result; }
// Management thread void NiAdminThread(THREAD *thread, void *param) { NAT_ADMIN *a = (NAT_ADMIN *)param; NAT *n; SOCK *s; UCHAR random[SHA1_SIZE]; UINT err; // Validate arguments if (thread == NULL || param == NULL) { return; } // Random number generation Rand(random, sizeof(random)); a->Thread = thread; AddRef(a->Thread->ref); s = a->Sock; AddRef(s->ref); n = a->Nat; LockList(n->AdminList); { Add(n->AdminList, a); } UnlockList(n->AdminList); NoticeThreadInit(thread); err = ERR_AUTH_FAILED; if (StartSSL(s, n->AdminX, n->AdminK)) { PACK *p; // Send the random number p = NewPack(); PackAddData(p, "auth_random", random, sizeof(random)); if (HttpServerSend(s, p)) { PACK *p; // Receive a password p = HttpServerRecv(s); if (p != NULL) { UCHAR secure_password[SHA1_SIZE]; UCHAR secure_check[SHA1_SIZE]; if (PackGetData2(p, "secure_password", secure_password, sizeof(secure_password))) { SecurePassword(secure_check, n->HashedPassword, random); if (Cmp(secure_check, secure_password, SHA1_SIZE) == 0) { UCHAR test[SHA1_SIZE]; // Password match Hash(test, "", 0, true); SecurePassword(test, test, random); #if 0 if (Cmp(test, secure_check, SHA1_SIZE) == 0 && s->RemoteIP.addr[0] != 127) { // A client can not connect from the outside with blank password err = ERR_NULL_PASSWORD_LOCAL_ONLY; } else #endif { // Successful connection err = ERR_NO_ERROR; NiAdminMain(n, s); } } } FreePack(p); } } FreePack(p); if (err != ERR_NO_ERROR) { p = PackError(err); HttpServerSend(s, p); FreePack(p); } } Disconnect(s); ReleaseSock(s); }
// Management port Listen thread void NiListenThread(THREAD *thread, void *param) { NAT *n = (NAT *)param; SOCK *a; UINT i; bool b = false; // Validate arguments if (thread == NULL || param == NULL) { return; } // Initialize the management list n->AdminList = NewList(NULL); while (true) { a = Listen(DEFAULT_NAT_ADMIN_PORT); if (b == false) { b = true; NoticeThreadInit(thread); } if (a != NULL) { break; } Wait(n->HaltEvent, NAT_ADMIN_PORT_LISTEN_INTERVAL); if (n->Halt) { return; } } n->AdminListenSock = a; AddRef(a->ref); // Waiting while (true) { SOCK *s = Accept(a); THREAD *t; NAT_ADMIN *admin; if (s == NULL) { break; } if (n->Halt) { ReleaseSock(s); break; } admin = ZeroMalloc(sizeof(NAT_ADMIN)); admin->Nat = n; admin->Sock = s; t = NewThread(NiAdminThread, admin); WaitThreadInit(t); ReleaseThread(t); } // Disconnect all management connections LockList(n->AdminList); { for (i = 0;i < LIST_NUM(n->AdminList);i++) { NAT_ADMIN *a = LIST_DATA(n->AdminList, i); Disconnect(a->Sock); WaitThread(a->Thread, INFINITE); ReleaseThread(a->Thread); ReleaseSock(a->Sock); Free(a); } } UnlockList(n->AdminList); ReleaseList(n->AdminList); ReleaseSock(a); }
STDMETHODIMP DragDropTarget::QueryInterface(REFIID riid, void **ppv) { *ppv = this; AddRef(); return NOERROR; }
NS_IMETHODIMP morkStdioFile::AcquireBud(nsIMdbEnv * mdbev, nsIMdbHeap* ioHeap, nsIMdbFile **acquiredFile) // AcquireBud() starts a new "branch" version of the file, empty of content, // so that a new version of the file can be written. This new file // can later be told to BecomeTrunk() the original file, so the branch // created by budding the file will replace the original file. Some // file subclasses might initially take the unsafe but expedient // approach of simply truncating this file down to zero length, and // then returning the same morkFile pointer as this, with an extra // reference count increment. Note that the caller of AcquireBud() is // expected to eventually call CutStrongRef() on the returned file // in order to release the strong reference. High quality versions // of morkFile subclasses will create entirely new files which later // are renamed to become the old file, so that better transactional // behavior is exhibited by the file, so crashes protect old files. // Note that AcquireBud() is an illegal operation on readonly files. { NS_ENSURE_ARG(acquiredFile); MORK_USED_1(ioHeap); nsresult rv = NS_OK; morkFile* outFile = 0; morkEnv *ev = morkEnv::FromMdbEnv(mdbev); if ( this->IsOpenAndActiveFile() ) { FILE* file = (FILE*) mStdioFile_File; if ( file ) { //#ifdef MORK_WIN // truncate(file, /*eof*/ 0); //#else /*MORK_WIN*/ char* name = mFile_Name; if ( name ) { if ( MORK_FILECLOSE(file) >= 0 ) { this->SetFileActive(morkBool_kFalse); this->SetFileIoOpen(morkBool_kFalse); mStdioFile_File = 0; file = MORK_FILEOPEN(name, "wb+"); // open for write, discarding old content if ( file ) { mStdioFile_File = file; this->SetFileActive(morkBool_kTrue); this->SetFileIoOpen(morkBool_kTrue); this->SetFileFrozen(morkBool_kFalse); } else this->new_stdio_file_fault(ev); } else this->new_stdio_file_fault(ev); } else this->NilFileNameError(ev); //#endif /*MORK_WIN*/ if ( ev->Good() && this->AddStrongRef(ev->AsMdbEnv()) ) { outFile = this; AddRef(); } } else if ( mFile_Thief ) { rv = mFile_Thief->AcquireBud(ev->AsMdbEnv(), ioHeap, acquiredFile); } else this->NewMissingIoError(ev); } else this->NewFileDownError(ev); *acquiredFile = outFile; return rv; }
// Listener thread void ElListenerProc(THREAD *thread, void *param) { TCP_ACCEPTED_PARAM *data = (TCP_ACCEPTED_PARAM *)param; EL *e; SOCK *s; UCHAR rand[SHA1_SIZE]; UCHAR pass1[SHA1_SIZE], pass2[SHA1_SIZE]; // Validate arguments if (data == NULL || thread == NULL) { return; } e = (EL *)data->r->ThreadParam; s = data->s; AddRef(s->ref); SetTimeout(s, 5000); LockList(e->AdminThreadList); { AddRef(thread->ref); AddRef(s->ref); Insert(e->AdminThreadList, thread); Insert(e->AdminSockList, s); } UnlockList(e->AdminThreadList); NoticeThreadInit(thread); // Submit a challenge Rand(rand, sizeof(rand)); SendAll(s, rand, sizeof(rand), false); // Receive a response SecurePassword(pass1, e->HashedPassword, rand); Zero(pass2, sizeof(pass2)); RecvAll(s, pass2, sizeof(pass2), false); if (Cmp(pass1, pass2, SHA1_SIZE) != 0) { // Password incorrect bool code = false; code = Endian32(code); SendAll(s, &code, sizeof(code), false); } else { // Password match bool code = true; RPC *r; code = Endian32(code); SendAll(s, &code, sizeof(code), false); SetTimeout(s, INFINITE); // Start operation as a RPC server r = StartRpcServer(s, ElRpcServer, e); RpcServer(r); RpcFree(r); } Disconnect(s); ReleaseSock(s); LockList(e->AdminThreadList); { if (Delete(e->AdminThreadList, thread)) { ReleaseThread(thread); } if (Delete(e->AdminSockList, s)) { ReleaseSock(s); } } UnlockList(e->AdminThreadList); }
void eFilePushThread::sendEvent(int evt) { /* add a ref, to make sure the object is not destroyed while the messagepump contains unhandled messages */ AddRef(); m_messagepump.send(evt); }
CXFilterV2::CXFilterV2(): m_cRef(1) { AddRef(); }
STDAPI CTextService::QueryInterface(REFIID riid, void **ppvObj) { if(ppvObj == nullptr) { return E_INVALIDARG; } *ppvObj = nullptr; if(IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_ITfTextInputProcessor)) { *ppvObj = (ITfTextInputProcessor *)this; } else if(IsEqualIID(riid, IID_ITfTextInputProcessorEx)) { *ppvObj = (ITfTextInputProcessorEx *)this; } else if(IsEqualIID(riid, IID_ITfThreadMgrEventSink)) { *ppvObj = (ITfThreadMgrEventSink *)this; } else if(IsEqualIID(riid, IID_ITfThreadFocusSink)) { *ppvObj = (ITfThreadFocusSink *)this; } else if(IsEqualIID(riid, IID_ITfCompartmentEventSink)) { *ppvObj = (ITfCompartmentEventSink *)this; } else if(IsEqualIID(riid, IID_ITfTextEditSink)) { *ppvObj = (ITfTextEditSink *)this; } else if(IsEqualIID(riid, IID_ITfKeyEventSink)) { *ppvObj = (ITfKeyEventSink *)this; } else if(IsEqualIID(riid, IID_ITfCompositionSink)) { *ppvObj = (ITfKeyEventSink *)this; } else if(IsEqualIID(riid, IID_ITfDisplayAttributeProvider)) { *ppvObj = (ITfDisplayAttributeProvider *)this; } else if(IsEqualIID(riid, IID_ITfFunctionProvider)) { *ppvObj = (ITfFunctionProvider *)this; } else if(IsEqualIID(riid, IID_ITfFnConfigure)) { *ppvObj = (ITfFnConfigure *)this; } else if(IsEqualIID(riid, IID_ITfFnShowHelp)) { *ppvObj = (ITfFnShowHelp *)this; } else if(IsEqualIID(riid, IID_ITfFnReconversion)) { *ppvObj = (ITfFnReconversion *)this; } else if(IsEqualIID(riid, IID_ITfFnGetPreferredTouchKeyboardLayout)) { *ppvObj = (ITfFnGetPreferredTouchKeyboardLayout *)this; } if(*ppvObj) { AddRef(); return S_OK; } return E_NOINTERFACE; }
// Add a local-bridge void AddLocalBridge(CEDAR *c, char *hubname, char *devicename, bool local, bool monitor, bool tapmode, char *tapaddr, bool limit_broadcast) { UINT i; HUB *h = NULL; LOCALBRIDGE *br = NULL; // Validate arguments if (c == NULL || hubname == NULL || devicename == NULL) { return; } if (OS_IS_UNIX(GetOsInfo()->OsType) == false) { tapmode = false; } LockList(c->HubList); { LockList(c->LocalBridgeList); { bool exists = false; // Ensure that the same configuration local-bridge doesn't exist already for (i = 0;i < LIST_NUM(c->LocalBridgeList);i++) { LOCALBRIDGE *br = LIST_DATA(c->LocalBridgeList, i); if (StrCmpi(br->DeviceName, devicename) == 0) { if (StrCmpi(br->HubName, hubname) == 0) { if (br->TapMode == tapmode) { exists = true; } } } } if (exists == false) { // Add configuration br = ZeroMalloc(sizeof(LOCALBRIDGE)); StrCpy(br->HubName, sizeof(br->HubName), hubname); StrCpy(br->DeviceName, sizeof(br->DeviceName), devicename); br->Bridge = NULL; br->Local = local; br->TapMode = tapmode; br->LimitBroadcast = limit_broadcast; br->Monitor = monitor; if (br->TapMode) { if (tapaddr != NULL && IsZero(tapaddr, 6) == false) { Copy(br->TapMacAddress, tapaddr, 6); } else { GenMacAddress(br->TapMacAddress); } } Add(c->LocalBridgeList, br); // Find the hub for (i = 0;i < LIST_NUM(c->HubList);i++) { HUB *hub = LIST_DATA(c->HubList, i); if (StrCmpi(hub->Name, br->HubName) == 0) { h = hub; AddRef(h->ref); break; } } } } UnlockList(c->LocalBridgeList); } UnlockList(c->HubList); // Start the local-bridge immediately if (h != NULL && br != NULL && h->Type != HUB_TYPE_FARM_DYNAMIC) { Lock(h->lock_online); { if (h->Offline == false) { LockList(c->LocalBridgeList); { if (IsInList(c->LocalBridgeList, br)) { if (br->Bridge == NULL) { br->Bridge = BrNewBridge(h, br->DeviceName, NULL, br->Local, br->Monitor, br->TapMode, br->TapMacAddress, br->LimitBroadcast, br); } } } UnlockList(c->LocalBridgeList); } } Unlock(h->lock_online); } ReleaseHub(h); }
/*================================================================================================== @brief FTM driver open This API can be used to open the FTM driver. @param DriverHdl: Input - handle created in Audio_FTM_Attach AccessMode: Input - Read/Write/RD_WR ShareMode: Input - Exclusive or Share pClientHdl: Output - point to the returned Open handle @return return code, AUDIO_FTM_SUCCESS on successful completion, error code otherwise ==================================================================================================*/ AUDIO_FTM_STS_T audio_ftm_toneplay_open ( AUDIO_FTM_DRIVER_HANDLE_T pDriverContext , /* Input: driver handle */ AUD_FTM_ACCESS_MODE_T AccessMode, /* Input: Access mode */ AUD_FTM_SHARE_MODE_T ShareMode, /* Input: Share mode */ AUDIO_FTM_CLIENT_HANDLE_T * pClientContext /* Output: client handle */ ) { Aud_FTM_DrvCtxt_T * pDrvCxt = (Aud_FTM_DrvCtxt_T *)pDriverContext; Aud_FTM_ClientCtxt_T * pOpenContext = NULL; AUDIO_FTM_STS_T res; int16 i; uint32 dev_buf_size, fifo_buf_size; if (pDrvCxt == NULL) { DALSYS_Log_Err("%s: failed %d\n",__func__,__LINE__); return AUDIO_FTM_ERR_INVALID_PARAM; } DALSYS_SyncEnter(pDrvCxt->hClientSync); if((ShareMode == AUD_FTM_SHAREMODE_EXCLU ) && (DALSYS_atomic_read(&pDrvCxt->dwOpenCount) != 0)) /* ShareMode = 0: exclusive mode; =FILE_SHARE_READ: read only; =FILE_SHARE_WRITE: write only */ { DALSYS_SyncLeave(pDrvCxt->hClientSync); DALSYS_Log_Err("%s: failed %d\n",__func__,__LINE__); return AUDIO_FTM_ERROR; } if(DAL_SUCCESS != DALSYS_Malloc(sizeof(Aud_FTM_ClientCtxt_T), (void **)&pOpenContext)) { DALSYS_Log_Err("%s: failed %d\n",__func__,__LINE__); DALSYS_SyncLeave(pDrvCxt->hClientSync); return AUDIO_FTM_ERR_MEM_ALLOC_FAIL; } if (pOpenContext == NULL) { DALSYS_SyncLeave(pDrvCxt->hClientSync); DALSYS_Log_Err("%s: failed %d\n",__func__,__LINE__); return AUDIO_FTM_ERR_MEM_ALLOC_FAIL; } DALSYS_memset(pOpenContext,0,sizeof(Aud_FTM_ClientCtxt_T)); // Store device settings for future use pOpenContext->pDrvCtxt = pDrvCxt; pOpenContext->dwAccessCode = AccessMode; pOpenContext->dwShareMode = ShareMode; pOpenContext->dwClientID=DALSYS_atomic_read(&pDrvCxt->dwOpenCount); pDrvCxt->apClientCtxt[pOpenContext->dwClientID]=pOpenContext; #ifdef MSM8960_ALSA pDrvCxt->pDevCtxt->read_write_flag = PCM_OUT; #endif /***** open HW *****/ DALSYS_Log_Info("%s: open hw\n",__func__); pDrvCxt->pDevCtxt->playbackdevice = pDrvCxt->pDevCtxt->pDrvCtxt->client_param.device; res=audio_ftm_hw_open(pDrvCxt->pDevCtxt); if(res != AUDIO_FTM_SUCCESS) { DALSYS_Log_Err("%s: failed %d\n",__func__,__LINE__); DALSYS_SyncLeave(pDrvCxt->hClientSync); return AUDIO_FTM_ERROR; } audio_ftm_hw_iocontrol(pDrvCxt->pDevCtxt, IOCTL_AUDIO_FTM_RX_DEV_BUF_SIZE, NULL, 0, &dev_buf_size, sizeof(dev_buf_size), NULL); pDrvCxt->nRx_blk_convey_samples=dev_buf_size/sizeof(int16); /********* init circular buf ********/ fifo_buf_size=dev_buf_size*AUD_FTM_TONE_PLAY_FIFO_FACTOR+4; // reserve 4 bytes DALSYS_Log_Info("%s: init buf\n",__func__); aud_ftm_cbuf_init(&(pDrvCxt->fifo_data_buf), fifo_buf_size); if(DAL_SUCCESS != DALSYS_Malloc(dev_buf_size*AUD_FTM_TONE_PLAY_FIFO_FACTOR, (void **)&pTmpBuf)) /* buffer for DTMF data producing */ { DALSYS_SyncLeave(pDrvCxt->hClientSync); DALSYS_Log_Err(" pTmpBuf allocation fail\n"); return DAL_ERROR; } DALSYS_memset(pTmpBuf,0,dev_buf_size*AUD_FTM_TONE_PLAY_FIFO_FACTOR); if(DAL_SUCCESS != DALSYS_Malloc(dev_buf_size, (void **)&pAud_ftm_rx_buf)) /* buffer for fetch data from FIFO and pass to low layer driver for consuming */ { DALSYS_SyncLeave(pDrvCxt->hClientSync); DALSYS_Log_Err(" pAud_ftm_rx_buf allocation fail\n"); return DAL_ERROR; } DALSYS_memset(pAud_ftm_rx_buf,0,dev_buf_size); /***** prefill the circular buffer with DTMF data *****/ for(i=0; i<((dev_buf_size*AUD_FTM_TONE_PLAY_FIFO_FACTOR)/sizeof(int16)); i++) { *(pTmpBuf+i)=audio_ftm_dtmf_tone_sample_gen(&(pDrvCxt->dtmfGen),pDrvCxt->nDTMF_Gain); } aud_ftm_cbuf_write (&(pDrvCxt->fifo_data_buf),(uint8 *)pTmpBuf,(int32)(dev_buf_size*AUD_FTM_TONE_PLAY_FIFO_FACTOR)); // Increase opened device counter AddRef(&pDrvCxt->dwOpenCount); pDrvCxt->bOpened=TRUE; DALSYS_SyncLeave(pDrvCxt->hClientSync); *pClientContext= (AUDIO_FTM_CLIENT_HANDLE_T)pOpenContext; return AUDIO_FTM_SUCCESS; }
GNetUpdater() { AddRef(); }
void SItemPanel::OnFinalRelease() { AddRef();//防止重复进入该函数 SSendMessage(WM_DESTROY); __super::OnFinalRelease(); }
WidevineDecryptor::WidevineDecryptor() : mCallback(nullptr) { Log("WidevineDecryptor created this=%p", this); AddRef(); // Released in DecryptingComplete(). }
/** copy constructor (invoked also when initializing from another smart ptr) */ FORCEINLINE CCountedPtr(const CCountedPtr& src) : m_pT(src.m_pT) {AddRef();}
/** default (NULL) construct or construct from a raw pointer */ inline CCountedPtr(Tcls *pObj = NULL) : m_pT(pObj) { AddRef(); }
// AddIPDLReference and ReleaseIPDLReference are only to be called by CreateIPDLActor // and DestroyIPDLActor, respectively. We intentionally make them private to prevent misuse. // The purpose of these methods is to be aware of when the IPC system around this // actor goes down: mIPCOpen is then set to false. void AddIPDLReference() { MOZ_ASSERT(mIPCOpen == false); mIPCOpen = true; AddRef(); }
/** copy constructor (invoked also when initializing from another smart ptr) */ inline CCountedPtr(const CCountedPtr &src) : m_pT(src.m_pT) { AddRef(); }
// Layer-3 interface thread void L3IfThread(THREAD *t, void *param) { L3IF *f; CONNECTION *c; SESSION *s; POLICY *policy; char tmp[MAX_SIZE]; char name[MAX_SIZE]; char username[MAX_SIZE]; // Validate arguments if (t == NULL || param == NULL) { return; } f = (L3IF *)param; StrCpy(username, sizeof(username), L3_USERNAME); if (f->Switch != NULL) { StrCat(username, sizeof(username), f->Switch->Name); } // Create a connection c = NewServerConnection(f->Switch->Cedar, NULL, t); c->Protocol = CONNECTION_HUB_LAYER3; // Create a Session policy = ClonePolicy(GetDefaultPolicy()); // Not to limit the number of broadcast by policy policy->NoBroadcastLimiter = true; s = NewServerSession(f->Switch->Cedar, c, f->Hub, username, policy); c->Session = s; ReleaseConnection(c); // Determine the name of the session GetMachineHostName(tmp, sizeof(tmp)); if (f->Switch->Cedar->Server->ServerType == SERVER_TYPE_STANDALONE) { Format(name, sizeof(name), "SID-L3-%s-%u", f->Switch->Name, Inc(f->Hub->SessionCounter)); } else { Format(name, sizeof(name), "SID-L3-%s-%s-%u", tmp, f->Switch->Name, Inc(f->Hub->SessionCounter)); } ConvertSafeFileName(name, sizeof(name), name); StrUpper(name); Free(s->Name); s->Name = CopyStr(name); s->L3SwitchMode = true; s->L3If = f; if (s->Username != NULL) { Free(s->Username); } s->Username = CopyStr(username); StrCpy(s->UserNameReal, sizeof(s->UserNameReal), username); f->Session = s; AddRef(s->ref); // Notify the initialization completion NoticeThreadInit(t); // Session main process SessionMain(s); // Release the session ReleaseSession(s); }
STDMETHODIMP OrxScriptError::QueryInterface(REFIID riid, void **ppvObj) { HRESULT hResult = E_NOINTERFACE; OLECHAR cIID[100]; char *IIDName,TrulyUnknown[]="??????"; if (RunDestructor && logfile) { FPRINTF2(logfile,"\n"); } StringFromGUID2(riid, cIID, sizeof(cIID)); if (RunDestructor && logfile) { FPRINTF(logfile,"OrxScriptError::QueryInterface (ppvObj = %p,\n riid = %S \n",ppvObj,cIID); } // We should look this riid up in HKClass_Root\Interface\.... to print what it represents. <---- // a pointer to result storage must be supplied if (!ppvObj) { return ResultFromScode(E_INVALIDARG); } // set to NULL initiallly *ppvObj = NULL; if (RunDestructor && logfile) { FPRINTF2(logfile,"It is the ("); } // need to supply an IUnknown pointer? if (IsEqualIID(riid, IID_IUnknown)) { *ppvObj = (LPVOID)(IUnknown *)(IActiveScript *) this; if (RunDestructor && logfile) { FPRINTF3(logfile,"IUnknown"); } } // need to supply an IActiveScriptError pointer? else if (IsEqualIID(riid, IID_IActiveScriptError)) { *ppvObj = (LPVOID)(IActiveScriptError *) this; if (RunDestructor && logfile) { FPRINTF3(logfile,"IActiveScriptError"); } } else { if (!(IIDName = NameThatInterface((OLECHAR *)&cIID[0]))) { IIDName = &TrulyUnknown[0]; } if (RunDestructor && logfile) { FPRINTF3(logfile,"unsupported %s",IIDName); } if (IIDName != &TrulyUnknown[0]) { free(IIDName); } } if (RunDestructor && logfile) { FPRINTF3(logfile,") interface.\n\n"); } // on success, call AddRef() if (*ppvObj != NULL) { AddRef(); hResult = NOERROR; } return hResult; }
// Wait for connection request void AcWaitForRequest(AZURE_CLIENT *ac, SOCK *s, AZURE_PARAM *param) { // Validate arguments if (ac == NULL || s == NULL || param == NULL) { return; } while (ac->Halt == false) { UCHAR uc; // Receive 1 byte if (RecvAll(s, &uc, 1, false) == 0) { break; } if (uc != 0) { // Receive a Pack PACK *p = RecvPackWithHash(s); if (p == NULL) { break; } else { // Verify contents of Pack char opcode[MAX_SIZE]; char cipher_name[MAX_SIZE]; char hostname[MAX_SIZE]; PackGetStr(p, "opcode", opcode, sizeof(opcode)); PackGetStr(p, "cipher_name", cipher_name, sizeof(cipher_name)); PackGetStr(p, "hostname", hostname, sizeof(hostname)); if (StrCmpi(opcode, "relay") == 0) { IP client_ip, server_ip; UINT client_port; UINT server_port; UCHAR session_id[SHA1_SIZE]; if (PackGetIp(p, "client_ip", &client_ip) && PackGetIp(p, "server_ip", &server_ip) && PackGetData2(p, "session_id", session_id, sizeof(session_id))) { client_port = PackGetInt(p, "client_port"); server_port = PackGetInt(p, "server_port"); if (client_port != 0 && server_port != 0) { SOCK *ns; Debug("Connect Request from %r:%u\n", &client_ip, client_port); // Create new socket and connect VPN Azure Server if (ac->DDnsStatusCopy.InternetSetting.ProxyType == PROXY_DIRECT) { ns = ConnectEx2(ac->DDnsStatusCopy.CurrentAzureIp, AZURE_SERVER_PORT, 0, (bool *)&ac->Halt); } else { ns = WpcSockConnect2(ac->DDnsStatusCopy.CurrentAzureIp, AZURE_SERVER_PORT, &ac->DDnsStatusCopy.InternetSetting, NULL, AZURE_VIA_PROXY_TIMEOUT); } if (ns == NULL) { Debug("Connect Error.\n"); } else { Debug("Connected to the relay server.\n"); SetTimeout(ns, param->DataTimeout); if (StartSSLEx(ns, NULL, NULL, true, 0, NULL)) { // Check certification char server_cert_hash_str[MAX_SIZE]; UCHAR server_cert_hash[SHA1_SIZE]; Zero(server_cert_hash, sizeof(server_cert_hash)); GetXDigest(ns->RemoteX, server_cert_hash, true); BinToStr(server_cert_hash_str, sizeof(server_cert_hash_str), server_cert_hash, SHA1_SIZE); if (IsEmptyStr(ac->DDnsStatusCopy.AzureCertHash) || StrCmpi(server_cert_hash_str, ac->DDnsStatusCopy.AzureCertHash) == 0) { if (SendAll(ns, AZURE_PROTOCOL_DATA_SIANGTURE, 24, true)) { PACK *p2 = NewPack(); PackAddStr(p2, "hostname", hostname); PackAddData(p2, "session_id", session_id, sizeof(session_id)); if (SendPackWithHash(ns, p2)) { UCHAR uc; if (RecvAll(ns, &uc, 1, true) != false) { if (uc != 0) { SOCK *accept_sock = GetReverseListeningSock(ac->Cedar); if (accept_sock != NULL) { AddRef(ns->ref); SetTimeout(ns, INFINITE); Copy(&ns->Reverse_MyServerGlobalIp, &server_ip, sizeof(IP)); ns->Reverse_MyServerPort = server_port; InjectNewReverseSocketToAccept(accept_sock, ns, &client_ip, client_port); ReleaseSock(accept_sock); } } } } FreePack(p2); } } } ReleaseSock(ns); } } } } FreePack(p); } } // Send 1 byte uc = 0; if (SendAll(s, &uc, 1, false) == 0) { break; } } }
BOOL MSection::Lock(BOOL abExclusive, DWORD anTimeout/*=-1*/) { DWORD dwTID = GetCurrentThreadId(); // Может эта нить уже полностью заблокирована? if (mb_Exclusive && dwTID == mn_TID) { //111126 возвращался FALSE _ASSERTEX(!mb_Exclusive || dwTID != mn_TID); return TRUE; // Уже, но Unlock делать не нужно! } if (!abExclusive) { if (!mb_Exclusive) { // Быстрая блокировка, не запрещающая чтение другим нитям. // Запрещено только изменение (пересоздание буфера например) AddRef(dwTID); } // Если другая нить уже захватила exclusive else //if (mb_Exclusive) { _ASSERTEX(mb_Exclusive); //int nLeft = ReleaseRef(dwTID); // Иначе можем попасть на взаимную блокировку //if (nLeft > 0) //{ // // Нужно избегать этого. Значит выше по стеку в этой нити // // более одного раза был выполнен non exclusive lock // _ASSERTEX(nLeft == 0); //} #ifdef _DEBUG int nInThreadLeft = 0; for (int i=1; i<countof(mn_LockedTID); i++) { if (mn_LockedTID[i] == dwTID) { _ASSERTEX(mn_LockedCount[i]>=0); nInThreadLeft = mn_LockedCount[i]; break; } } if (nInThreadLeft > 0) { // Нужно избегать этого. Значит выше по стеку в этой нити // более одного раза был выполнен non exclusive lock _ASSERTEX(nInThreadLeft == 0); } #endif DEBUGSTR(L"!!! Failed non exclusive lock, trying to use CriticalSection\n"); bool lbEntered = MyEnterCriticalSection(anTimeout); // дождаться пока секцию отпустят // mb_Exclusive может быть выставлен, если сейчас другая нить пытается выполнить exclusive lock _ASSERTEX(!mb_Exclusive); // После LeaveCriticalSection mb_Exclusive УЖЕ должен быть сброшен AddRef(dwTID); // накрутить счетчик // Но поскольку нам нужен только nonexclusive lock if (lbEntered) m_cs.Leave(); } } else // abExclusive { // Требуется Exclusive Lock #ifdef _DEBUG if (mb_Exclusive) { // Этого надо стараться избегать DEBUGSTR(L"!!! Exclusive lock found in other thread\n"); } #endif // Если есть ExclusiveLock (в другой нити) - дождется сама EnterCriticalSection #ifdef _DEBUG BOOL lbPrev = mb_Exclusive; DWORD nPrevTID = mn_TID; #endif // Сразу установим mb_Exclusive, чтобы в других нитях случайно не прошел nonexclusive lock // иначе может получиться, что nonexclusive lock мешает выполнить exclusive lock (ждут друг друга) mb_Exclusive = TRUE; TODO("Need to check, if MyEnterCriticalSection failed on timeout!\n"); if (!MyEnterCriticalSection(anTimeout)) { // Пока поставил _ASSERTE, чтобы посмотреть, возникают ли Timeout-ы при блокировке _ASSERTEX(FALSE); if (mn_TID == 0) // поскольку заблокировать не удалось - сбросим флажок mb_Exclusive = FALSE; return FALSE; } // 120710 - добавил "|| (mn_TID==dwTID)". Это в том случае, если предыдущая ExclusiveThread была прибита. _ASSERTEX(!(lbPrev && mb_Exclusive) || (mn_TID==dwTID)); // После LeaveCriticalSection mb_Exclusive УЖЕ должен быть сброшен mn_TID = dwTID; // И запомним, в какой нити это произошло HANDLE h = mh_ExclusiveThread; mh_ExclusiveThread = OpenThread(SYNCHRONIZE, FALSE, dwTID); SafeCloseHandle(h); mb_Exclusive = TRUE; // Флаг могла сбросить другая нить, выполнившая Leave _ASSERTEX(mn_LockedTID[0] == 0 && mn_LockedCount[0] == 0); mn_LockedTID[0] = dwTID; mn_LockedCount[0] ++; // на [0] mn_Locked не распространяется /*if (abRelockExclusive) { ReleaseRef(dwTID); // Если до этого был nonexclusive lock }*/ // B если есть nonexclusive locks - дождаться их завершения if (mn_Locked) { //WARNING: Тут есть шанс наколоться, если сначала был NonExclusive, а потом в этой же нити - Exclusive // В таких случаях нужно вызывать с параметром abRelockExclusive WaitUnlocked(dwTID, anTimeout); } } return TRUE; }