예제 #1
0
static DWORD CALLBACK MMDevApiMsgProc(void *ptr)
{
    ThreadRequest *req = ptr;
    IMMDeviceEnumerator *Enumerator;
    ALuint deviceCount = 0;
    MMDevApiData *data;
    ALCdevice *device;
    HRESULT hr, cohr;
    MSG msg;

    TRACE("Starting message thread\n");

    cohr = CoInitialize(NULL);
    if(FAILED(cohr))
    {
        WARN("Failed to initialize COM: 0x%08lx\n", cohr);
        req->result = cohr;
        SetEvent(req->FinishedEvt);
        return 0;
    }

    hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
    if(FAILED(hr))
    {
        WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
        CoUninitialize();
        req->result = hr;
        SetEvent(req->FinishedEvt);
        return 0;
    }
    Enumerator = ptr;
    IMMDeviceEnumerator_Release(Enumerator);
    Enumerator = NULL;

    CoUninitialize();

    /* HACK: Force Windows to create a message queue for this thread before
     * returning success, otherwise PostThreadMessage may fail if it gets
     * called before GetMessage.
     */
    PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);

    TRACE("Message thread initialization complete\n");
    req->result = S_OK;
    SetEvent(req->FinishedEvt);

    TRACE("Starting message loop\n");
    while(GetMessage(&msg, NULL, WM_USER_First, WM_USER_Last))
    {
        TRACE("Got message %u\n", msg.message);
        switch(msg.message)
        {
        case WM_USER_OpenDevice:
            req = (ThreadRequest*)msg.wParam;
            device = (ALCdevice*)msg.lParam;
            data = device->ExtraData;

            hr = cohr = S_OK;
            if(++deviceCount == 1)
                hr = cohr = CoInitialize(NULL);
            if(SUCCEEDED(hr))
                hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
            if(SUCCEEDED(hr))
            {
                Enumerator = ptr;
                if(!data->devid)
                    hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint(Enumerator, eRender, eMultimedia, &data->mmdev);
                else
                    hr = IMMDeviceEnumerator_GetDevice(Enumerator, data->devid, &data->mmdev);
                IMMDeviceEnumerator_Release(Enumerator);
                Enumerator = NULL;
            }
            if(SUCCEEDED(hr))
                hr = IMMDevice_Activate(data->mmdev, &IID_IAudioClient, CLSCTX_INPROC_SERVER, NULL, &ptr);
            if(SUCCEEDED(hr))
            {
                data->client = ptr;
                device->DeviceName = get_device_name(data->mmdev);
            }

            if(FAILED(hr))
            {
                if(data->mmdev)
                    IMMDevice_Release(data->mmdev);
                data->mmdev = NULL;
                if(--deviceCount == 0 && SUCCEEDED(cohr))
                    CoUninitialize();
            }

            req->result = hr;
            SetEvent(req->FinishedEvt);
            continue;

        case WM_USER_ResetDevice:
            req = (ThreadRequest*)msg.wParam;
            device = (ALCdevice*)msg.lParam;

            req->result = DoReset(device);
            SetEvent(req->FinishedEvt);
            continue;

        case WM_USER_StartDevice:
            req = (ThreadRequest*)msg.wParam;
            device = (ALCdevice*)msg.lParam;
            data = device->ExtraData;

            ResetEvent(data->NotifyEvent);
            hr = IAudioClient_SetEventHandle(data->client, data->NotifyEvent);
            if(FAILED(hr))
                ERR("Failed to set event handle: 0x%08lx\n", hr);
            else
            {
                hr = IAudioClient_Start(data->client);
                if(FAILED(hr))
                    ERR("Failed to start audio client: 0x%08lx\n", hr);
            }

            if(SUCCEEDED(hr))
                hr = IAudioClient_GetService(data->client, &IID_IAudioRenderClient, &ptr);
            if(SUCCEEDED(hr))
            {
                data->render = ptr;
                if(!StartThread(&data->thread, MMDevApiProc, device))
                {
                    if(data->render)
                        IAudioRenderClient_Release(data->render);
                    data->render = NULL;
                    IAudioClient_Stop(data->client);
                    ERR("Failed to start thread\n");
                    hr = E_FAIL;
                }
            }

            req->result = hr;
            SetEvent(req->FinishedEvt);
            continue;

        case WM_USER_StopDevice:
            req = (ThreadRequest*)msg.wParam;
            device = (ALCdevice*)msg.lParam;
            data = device->ExtraData;

            if(data->thread)
            {
                data->killNow = 1;
                StopThread(data->thread);
                data->thread = NULL;

                data->killNow = 0;

                IAudioRenderClient_Release(data->render);
                data->render = NULL;
                IAudioClient_Stop(data->client);
            }

            req->result = S_OK;
            SetEvent(req->FinishedEvt);
            continue;

        case WM_USER_CloseDevice:
            req = (ThreadRequest*)msg.wParam;
            device = (ALCdevice*)msg.lParam;
            data = device->ExtraData;

            IAudioClient_Release(data->client);
            data->client = NULL;

            IMMDevice_Release(data->mmdev);
            data->mmdev = NULL;

            if(--deviceCount == 0)
                CoUninitialize();

            req->result = S_OK;
            SetEvent(req->FinishedEvt);
            continue;

        case WM_USER_Enumerate:
            req = (ThreadRequest*)msg.wParam;

            hr = cohr = S_OK;
            if(++deviceCount == 1)
                hr = cohr = CoInitialize(NULL);
            if(SUCCEEDED(hr))
                hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &IID_IMMDeviceEnumerator, &ptr);
            if(SUCCEEDED(hr))
            {
                EDataFlow flowdir;
                DevMap **devlist;
                ALuint *numdevs;
                ALuint i;

                Enumerator = ptr;
                if(msg.lParam == CAPTURE_DEVICE_PROBE)
                {
                    flowdir = eCapture;
                    devlist = &CaptureDeviceList;
                    numdevs = &NumCaptureDevices;
                }
                else
                {
                    flowdir = eRender;
                    devlist = &PlaybackDeviceList;
                    numdevs = &NumPlaybackDevices;
                }

                for(i = 0;i < *numdevs;i++)
                {
                    free((*devlist)[i].name);
                    free((*devlist)[i].devid);
                }
                free(*devlist);
                *devlist = NULL;
                *numdevs = 0;

                *devlist = ProbeDevices(Enumerator, flowdir, numdevs);

                IMMDeviceEnumerator_Release(Enumerator);
                Enumerator = NULL;
            }

            if(--deviceCount == 0 && SUCCEEDED(cohr))
                CoUninitialize();

            req->result = S_OK;
            SetEvent(req->FinishedEvt);
            continue;

        default:
            ERR("Unexpected message: %u\n", msg.message);
            continue;
        }
    }
    TRACE("Message loop finished\n");

    return 0;
}
예제 #2
0
Evas_Filter_Buffer *
evas_filter_buffer_scaled_get(Evas_Filter_Context *ctx,
                              Evas_Filter_Buffer *src,
                              unsigned w, unsigned h)
{
   Evas_Filter_Buffer *fb;
   Image_Entry *dstdata = NULL;
   Image_Entry *srcdata;
   void *drawctx;

   srcdata = evas_filter_buffer_backing_get(ctx, src->id);
   EINA_SAFETY_ON_NULL_RETURN_VAL(srcdata, NULL);

   if (src->alpha_only)
     {
        // There is no supporting function in Evas for alpha scaling...
        // but guess what? There is also no use case in the filters :)
        CRI("Alpha buffer scaling is not supported");
        return NULL;
     }

   fb = evas_filter_temporary_buffer_get(ctx, w, h, src->alpha_only);
   if (!fb) return NULL;

   dstdata = evas_filter_buffer_backing_get(ctx, fb->id);
   if (!dstdata)
     {
        CRI("No backing found for buffer %d", fb->id);
        return NULL;
     }

   if ((dstdata->w != w) || (dstdata->h != h))
     {
        CRI("Buffer size mismatch: got %dx%d requested %dx%d",
            dstdata->w, dstdata->h, w, h);
        return NULL;
     }

   if (ctx->gl_engine)
     {
        RGBA_Image *s = (RGBA_Image *) srcdata;
        RGBA_Image *d = (RGBA_Image *) dstdata;
        EINA_SAFETY_ON_NULL_RETURN_VAL(s->image.data, NULL);
        EINA_SAFETY_ON_NULL_RETURN_VAL(d->image.data, NULL);

        if (src->w == (int) w && src->h == (int) h)
          memcpy(d->image.data, s->image.data, w * h * 4);
        else
          {
             Eina_Bool ok;
             RGBA_Draw_Context dc;

             memset(&dc, 0, sizeof(dc));
             dc.sli.h = 1;
             dc.render_op = EVAS_RENDER_COPY;

             ok = evas_common_scale_rgba_in_to_out_clip_smooth
                   (s, d, &dc, 0, 0, src->w, src->h, 0, 0, w, h);
             if (!ok)
               {
                  ERR("RGBA Image scaling failed.");
                  return NULL;
               }
          }
     }
   else
     {
        drawctx = ENFN->context_new(ENDT);
        ENFN->context_color_set(ENDT, drawctx, 255, 255, 255, 255);
        ENFN->context_render_op_set(ENDT, drawctx, EVAS_RENDER_COPY);
        ENFN->image_draw(ENDT, drawctx, dstdata, srcdata,
                         0, 0, src->w, src->h, // src
                         0, 0, w, h, // dst
                         EINA_TRUE, // smooth
                         EINA_FALSE); // Not async
        ENFN->context_free(ENDT, drawctx);
     }

   return fb;
}
예제 #3
0
INT_PTR CALLBACK
CFileDefExt::GeneralPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_INITDIALOG:
        {
            LPPROPSHEETPAGEW ppsp = (LPPROPSHEETPAGEW)lParam;

            if (ppsp == NULL || !ppsp->lParam)
                break;

            TRACE("WM_INITDIALOG hwnd %p lParam %p ppsplParam %S\n", hwndDlg, lParam, ppsp->lParam);

            CFileDefExt *pFileDefExt = reinterpret_cast<CFileDefExt *>(ppsp->lParam);
            SetWindowLongPtr(hwndDlg, DWLP_USER, (LONG_PTR)pFileDefExt);
            pFileDefExt->InitGeneralPage(hwndDlg);
            break;
        }
        case WM_COMMAND:
            if (LOWORD(wParam) == 14024) /* Opens With - Change */
            {
                CFileDefExt *pFileDefExt = reinterpret_cast<CFileDefExt *>(GetWindowLongPtr(hwndDlg, DWLP_USER));
                OPENASINFO oainfo;
                oainfo.pcszFile = pFileDefExt->m_wszPath;
                oainfo.pcszClass = NULL;
                oainfo.oaifInFlags = OAIF_REGISTER_EXT|OAIF_FORCE_REGISTRATION;
                return SUCCEEDED(SHOpenWithDialog(hwndDlg, &oainfo));
            }
            else if (LOWORD(wParam) == 14021 || LOWORD(wParam) == 14022 || LOWORD(wParam) == 14023) /* checkboxes */
                PropSheet_Changed(GetParent(hwndDlg), hwndDlg);
            else if (LOWORD(wParam) == 14001) /* Name */
            {
                if (HIWORD(wParam) == EN_CHANGE)
                    PropSheet_Changed(GetParent(hwndDlg), hwndDlg);
            }
            break;
        case WM_NOTIFY:
        {
            LPPSHNOTIFY lppsn = (LPPSHNOTIFY)lParam;
            if (lppsn->hdr.code == PSN_APPLY)
            {
                CFileDefExt *pFileDefExt = reinterpret_cast<CFileDefExt *>(GetWindowLongPtr(hwndDlg, DWLP_USER));

                /* Update attributes first */
                DWORD dwAttr = GetFileAttributesW(pFileDefExt->m_wszPath);
                if (dwAttr)
                {
                    dwAttr &= ~(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_ARCHIVE);

                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14021, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_READONLY;
                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14022, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_HIDDEN;
                    if (BST_CHECKED == SendDlgItemMessageW(hwndDlg, 14023, BM_GETCHECK, 0, 0))
                        dwAttr |= FILE_ATTRIBUTE_ARCHIVE;

                    if (!SetFileAttributesW(pFileDefExt->m_wszPath, dwAttr))
                        ERR("SetFileAttributesW failed\n");
                }

                /* Update filename now */
                WCHAR wszBuf[MAX_PATH];
                StringCchCopyW(wszBuf, _countof(wszBuf), pFileDefExt->m_wszPath);
                LPWSTR pwszFilename = PathFindFileNameW(wszBuf);
                UINT cchFilenameMax = _countof(wszBuf) - (pwszFilename - wszBuf);
                if (GetDlgItemTextW(hwndDlg, 14001, pwszFilename, cchFilenameMax))
                {
                    if (!MoveFileW(pFileDefExt->m_wszPath, wszBuf))
                        ERR("MoveFileW failed\n");
                }

                SetWindowLongPtr(hwndDlg, DWL_MSGRESULT, PSNRET_NOERROR);
                return TRUE;
            }
            break;
        }
        default:
            break;
    }

    return FALSE;
}
예제 #4
0
파일: lsalpc.c 프로젝트: reactos/reactos
/*
 * @implemented
 */
NTSTATUS
NTAPI
LsaConnectUntrusted(
    OUT PHANDLE LsaHandle)
{
    UNICODE_STRING PortName;
    SECURITY_QUALITY_OF_SERVICE SecurityQos;
    LSA_CONNECTION_INFO ConnectInfo;
    ULONG ConnectInfoLength = sizeof(ConnectInfo);
    OBJECT_ATTRIBUTES ObjectAttributes;
    UNICODE_STRING EventName;
    HANDLE EventHandle;
    NTSTATUS Status;

    TRACE("LsaConnectUntrusted(%p)\n", LsaHandle);

    // TODO: we may need to impersonate ourselves before, because we are untrusted!

    /* Wait for the LSA authentication thread */
    RtlInitUnicodeString(&EventName,
                         L"\\SECURITY\\LSA_AUTHENTICATION_INITIALIZED");
    InitializeObjectAttributes(&ObjectAttributes,
                               &EventName,
                               OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
                               NULL,
                               NULL);
    Status = NtOpenEvent(&EventHandle,
                         SYNCHRONIZE,
                         &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        WARN("NtOpenEvent failed (Status 0x%08lx)\n", Status);

        Status = NtCreateEvent(&EventHandle,
                               SYNCHRONIZE,
                               &ObjectAttributes,
                               NotificationEvent,
                               FALSE);
        if (!NT_SUCCESS(Status))
        {
            WARN("NtCreateEvent failed (Status 0x%08lx)\n", Status);
            return Status;
        }
    }

    Status = NtWaitForSingleObject(EventHandle,
                                   TRUE,
                                   NULL);
    NtClose(EventHandle);
    if (!NT_SUCCESS(Status))
    {
        ERR("NtWaitForSingleObject failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    /* Connect to the authentication port */
    RtlInitUnicodeString(&PortName,
                         L"\\LsaAuthenticationPort");

    SecurityQos.Length              = sizeof(SecurityQos);
    SecurityQos.ImpersonationLevel  = SecurityIdentification;
    SecurityQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
    SecurityQos.EffectiveOnly       = TRUE;

    RtlZeroMemory(&ConnectInfo,
                  ConnectInfoLength);

    ConnectInfo.CreateContext = TRUE;

    Status = NtConnectPort(LsaHandle,
                           &PortName,
                           &SecurityQos,
                           NULL,
                           NULL,
                           NULL,
                           &ConnectInfo,
                           &ConnectInfoLength);
    if (!NT_SUCCESS(Status))
    {
        ERR("NtConnectPort failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    if (!NT_SUCCESS(ConnectInfo.Status))
    {
        ERR("ConnectInfo.Status: 0x%08lx\n", ConnectInfo.Status);
    }

    return ConnectInfo.Status;
}
예제 #5
0
LRESULT APIENTRY
co_IntCallWindowProc(WNDPROC Proc,
                     BOOLEAN IsAnsiProc,
                     HWND Wnd,
                     UINT Message,
                     WPARAM wParam,
                     LPARAM lParam,
                     INT lParamBufferSize)
{
   WINDOWPROC_CALLBACK_ARGUMENTS StackArguments;
   PWINDOWPROC_CALLBACK_ARGUMENTS Arguments;
   NTSTATUS Status;
   PVOID ResultPointer, pActCtx;
   PWND pWnd;
   ULONG ResultLength;
   ULONG ArgumentLength;
   LRESULT Result;

   TRACE("co_IntCallWindowProc(Proc %p, IsAnsiProc: %s, Wnd %p, Message %u, wParam %Iu, lParam %Id, lParamBufferSize %d)\n",
       Proc, IsAnsiProc ? "TRUE" : "FALSE", Wnd, Message, wParam, lParam, lParamBufferSize);

   /* Do not allow the desktop thread to do callback to user mode */
   ASSERT(PsGetCurrentThreadWin32Thread() != gptiDesktopThread);

   if (lParamBufferSize != -1)
   {
      ArgumentLength = sizeof(WINDOWPROC_CALLBACK_ARGUMENTS) + lParamBufferSize;
      Arguments = IntCbAllocateMemory(ArgumentLength);
      if (NULL == Arguments)
      {
         ERR("Unable to allocate buffer for window proc callback\n");
         return -1;
      }
      RtlMoveMemory((PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)),
                    (PVOID) lParam, lParamBufferSize);
   }
   else
   {
      Arguments = &StackArguments;
      ArgumentLength = sizeof(WINDOWPROC_CALLBACK_ARGUMENTS);
   }
   Arguments->Proc = Proc;
   Arguments->IsAnsiProc = IsAnsiProc;
   Arguments->Wnd = Wnd;
   Arguments->Msg = Message;
   Arguments->wParam = wParam;
   Arguments->lParam = lParam;
   Arguments->lParamBufferSize = lParamBufferSize;
   ResultPointer = NULL;
   ResultLength = ArgumentLength;

   IntSetTebWndCallback (&Wnd, &pWnd, &pActCtx);

   UserLeaveCo();

   Status = KeUserModeCallback(USER32_CALLBACK_WINDOWPROC,
                               Arguments,
                               ArgumentLength,
                               &ResultPointer,
                               &ResultLength);

   _SEH2_TRY
   {
      /* Simulate old behaviour: copy into our local buffer */
      RtlMoveMemory(Arguments, ResultPointer, ArgumentLength);
   }
   _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
   {
      ERR("Failed to copy result from user mode, Message %d lParam size %d!\n", Message, lParamBufferSize);
      Status = _SEH2_GetExceptionCode();
   }
   _SEH2_END;

   UserEnterCo();

   IntRestoreTebWndCallback (Wnd, pWnd, pActCtx);

   if (!NT_SUCCESS(Status))
   {
     ERR("Call to user mode failed! %p\n",Status);
      if (lParamBufferSize != -1)
      {
         IntCbFreeMemory(Arguments);
      }
      return -1;
   }
   Result = Arguments->Result;

   if (lParamBufferSize != -1)
   {
      PTHREADINFO pti = PsGetCurrentThreadWin32Thread();
      // Is this message being processed from inside kernel space?
      BOOL InSendMessage = (pti->pcti->CTI_flags & CTI_INSENDMESSAGE);

      TRACE("Copy lParam Message %d lParam %d!\n", Message, lParam);
      switch (Message)
      {
          default:
            TRACE("Don't copy lParam, Message %d Size %d lParam %d!\n", Message, lParamBufferSize, lParam);
            break;
          // Write back to user/kernel space. Also see g_MsgMemory.
          case WM_CREATE:
          case WM_GETMINMAXINFO:
          case WM_GETTEXT:
          case WM_NCCALCSIZE:
          case WM_NCCREATE:
          case WM_STYLECHANGING:
          case WM_WINDOWPOSCHANGING:
          case WM_SIZING:
          case WM_MOVING:
            TRACE("Copy lParam, Message %d Size %d lParam %d!\n", Message, lParamBufferSize, lParam);
            if (InSendMessage)
               // Copy into kernel space.
               RtlMoveMemory((PVOID) lParam,
                             (PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)),
                              lParamBufferSize);
            else
            {
             _SEH2_TRY
             { // Copy into user space.
               RtlMoveMemory((PVOID) lParam,
                             (PVOID) ((char *) Arguments + sizeof(WINDOWPROC_CALLBACK_ARGUMENTS)),
                              lParamBufferSize);
             }
             _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
             {
                ERR("Failed to copy lParam to user space, Message %d!\n", Message);
             }
             _SEH2_END;
            }
            break;
      }
      IntCbFreeMemory(Arguments);
   }
예제 #6
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_header_check -- (internal) validate header of a single pool set file
 */
static int
util_header_check(struct pool_set *set, unsigned repidx, unsigned partidx,
	const char *sig, uint32_t major, uint32_t compat, uint32_t incompat,
	uint32_t ro_compat)
{
	LOG(3, "set %p repidx %u partidx %u sig %.8s major %u "
		"compat %#x incompat %#x ro_comapt %#x",
		set, repidx, partidx, sig, major, compat, incompat, ro_compat);

	struct pool_replica *rep = set->replica[repidx];

	/* opaque info lives at the beginning of mapped memory pool */
	struct pool_hdr *hdrp = rep->part[partidx].hdr;
	struct pool_hdr hdr;

	memcpy(&hdr, hdrp, sizeof (hdr));

	if (!util_convert_hdr(&hdr)) {
		errno = EINVAL;
		return -1;
	}

	/* valid header found */
	if (memcmp(hdr.signature, sig, POOL_HDR_SIG_LEN)) {
		ERR("wrong pool type: \"%.8s\"", hdr.signature);
		errno = EINVAL;
		return -1;
	}

	if (hdr.major != major) {
		ERR("pool version %d (library expects %d)",
			hdr.major, major);
		errno = EINVAL;
		return -1;
	}

	if (util_check_arch_flags(&hdr.arch_flags)) {
		ERR("wrong architecture flags");
		errno = EINVAL;
		return -1;
	}

	/* check pool set UUID */
	if (memcmp(HDR(REP(set, 0), 0)->poolset_uuid, hdr.poolset_uuid,
						POOL_HDR_UUID_LEN)) {
		ERR("wrong pool set UUID");
		errno = EINVAL;
		return -1;
	}

	/* check pool set linkage */
	if (memcmp(HDR(rep, partidx - 1)->uuid, hdr.prev_part_uuid,
						POOL_HDR_UUID_LEN) ||
	    memcmp(HDR(rep, partidx + 1)->uuid, hdr.next_part_uuid,
						POOL_HDR_UUID_LEN)) {
		ERR("wrong part UUID");
		errno = EINVAL;
		return -1;
	}

	/* check format version */
	if (HDR(rep, 0)->major != hdrp->major) {
		ERR("incompatible pool format");
		errno = EINVAL;
		return -1;
	}

	/* check compatibility features */
	if (HDR(rep, 0)->compat_features != hdrp->compat_features ||
	    HDR(rep, 0)->incompat_features != hdrp->incompat_features ||
	    HDR(rep, 0)->ro_compat_features != hdrp->ro_compat_features) {
		ERR("incompatible feature flags");
		errno = EINVAL;
		return -1;
	}

	rep->part[partidx].rdonly = 0;

	int retval = util_feature_check(&hdr, incompat, ro_compat, compat);
	if (retval < 0)
		return -1;
	else if (retval == 0)
		rep->part[partidx].rdonly = 1;

	return 0;
}
예제 #7
0
파일: register.c 프로젝트: reactos/reactos
/***********************************************************************
 *              DllRegisterServer (WINTRUST.@)
 */
HRESULT WINAPI DllRegisterServer(void)
{
    static const CHAR SpcPeImageDataEncode[]           = "WVTAsn1SpcPeImageDataEncode";
    static const CHAR SpcPeImageDataDecode[]           = "WVTAsn1SpcPeImageDataDecode";
    static const CHAR SpcLinkEncode[]                  = "WVTAsn1SpcLinkEncode";
    static const CHAR SpcLinkDecode[]                  = "WVTAsn1SpcLinkDecode";
    static const CHAR SpcSigInfoEncode[]               = "WVTAsn1SpcSigInfoEncode";
    static const CHAR SpcSigInfoDecode[]               = "WVTAsn1SpcSigInfoDecode";
    static const CHAR SpcIndirectDataContentEncode[]   = "WVTAsn1SpcIndirectDataContentEncode";
    static const CHAR SpcIndirectDataContentDecode[]   = "WVTAsn1SpcIndirectDataContentDecode";
    static const CHAR SpcSpAgencyInfoEncode[]          = "WVTAsn1SpcSpAgencyInfoEncode";
    static const CHAR SpcSpAgencyInfoDecode[]          = "WVTAsn1SpcSpAgencyInfoDecode";
    static const CHAR SpcMinimalCriteriaInfoEncode[]   = "WVTAsn1SpcMinimalCriteriaInfoEncode";
    static const CHAR SpcMinimalCriteriaInfoDecode[]   = "WVTAsn1SpcMinimalCriteriaInfoDecode";
    static const CHAR SpcFinancialCriteriaInfoEncode[] = "WVTAsn1SpcFinancialCriteriaInfoEncode";
    static const CHAR SpcFinancialCriteriaInfoDecode[] = "WVTAsn1SpcFinancialCriteriaInfoDecode";
    static const CHAR SpcStatementTypeEncode[]         = "WVTAsn1SpcStatementTypeEncode";
    static const CHAR SpcStatementTypeDecode[]         = "WVTAsn1SpcStatementTypeDecode";
    static const CHAR CatNameValueEncode[]             = "WVTAsn1CatNameValueEncode";
    static const CHAR CatNameValueDecode[]             = "WVTAsn1CatNameValueDecode";
    static const CHAR CatMemberInfoEncode[]            = "WVTAsn1CatMemberInfoEncode";
    static const CHAR CatMemberInfoDecode[]            = "WVTAsn1CatMemberInfoDecode";
    static const CHAR SpcSpOpusInfoEncode[]            = "WVTAsn1SpcSpOpusInfoEncode";
    static const CHAR SpcSpOpusInfoDecode[]            = "WVTAsn1SpcSpOpusInfoDecode";
    static GUID Unknown1 = { 0xDE351A42, 0x8E59, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static GUID Unknown2 = { 0xC689AABA, 0x8E78, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static GUID Unknown3 = { 0xC689AAB8, 0x8E78, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static GUID Unknown4 = { 0xC689AAB9, 0x8E78, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static GUID Unknown5 = { 0xDE351A43, 0x8E59, 0x11D0, { 0x8C,0x47,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static GUID Unknown6 = { 0x9BA61D3F, 0xE73A, 0x11D0, { 0x8C,0xD2,0x00,0xC0,0x4F,0xC2,0x95,0xEE }};
    static WCHAR MagicNumber2[] = {'M','S','C','F', 0};
    static WCHAR MagicNumber3[] = {'0','x','0','0','0','0','4','5','5','0', 0};
    static WCHAR CafeBabe[] = {'0','x','c','a','f','e','b','a','b','e', 0};

    HRESULT CryptRegisterRes = S_OK;
    HRESULT TrustProviderRes = S_OK;
    HRESULT SIPAddProviderRes = S_OK;
    HCRYPTPROV crypt_provider;
    BOOL ret;

    TRACE("\n");

    /* Testing on native shows that when an error is encountered in one of the CryptRegisterOIDFunction calls
     * the rest of these calls are skipped. Registering is however continued for the trust providers.
     *
     * We are not totally in line with native as all decoding functions are registered after all encoding
     * functions there.
     */
#define WINTRUST_REGISTEROID( oid, encode_funcname, decode_funcname ) \
    do { \
        if (!CryptRegisterOIDFunction(X509_ASN_ENCODING, CRYPT_OID_ENCODE_OBJECT_FUNC, oid, SP_POLICY_PROVIDER_DLL_NAME, encode_funcname)) \
        {                                                               \
            CryptRegisterRes = HRESULT_FROM_WIN32(GetLastError());      \
            goto add_trust_providers;                                   \
        }                                                               \
        if (!CryptRegisterOIDFunction(X509_ASN_ENCODING, CRYPT_OID_DECODE_OBJECT_FUNC, oid, SP_POLICY_PROVIDER_DLL_NAME, decode_funcname)) \
        {                                                               \
            CryptRegisterRes = HRESULT_FROM_WIN32(GetLastError());      \
            goto add_trust_providers;                                   \
        }                                                               \
    } while (0)

    WINTRUST_REGISTEROID(SPC_PE_IMAGE_DATA_OBJID, SpcPeImageDataEncode, SpcPeImageDataDecode);
    WINTRUST_REGISTEROID(SPC_PE_IMAGE_DATA_STRUCT, SpcPeImageDataEncode, SpcPeImageDataDecode);
    WINTRUST_REGISTEROID(SPC_CAB_DATA_OBJID, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_CAB_DATA_STRUCT, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_JAVA_CLASS_DATA_OBJID, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_JAVA_CLASS_DATA_STRUCT, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_LINK_OBJID, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_LINK_STRUCT, SpcLinkEncode, SpcLinkDecode);
    WINTRUST_REGISTEROID(SPC_SIGINFO_OBJID, SpcSigInfoEncode, SpcSigInfoDecode);
    WINTRUST_REGISTEROID(SPC_SIGINFO_STRUCT, SpcSigInfoEncode, SpcSigInfoDecode);
    WINTRUST_REGISTEROID(SPC_INDIRECT_DATA_OBJID, SpcIndirectDataContentEncode, SpcIndirectDataContentDecode);
    WINTRUST_REGISTEROID(SPC_INDIRECT_DATA_CONTENT_STRUCT, SpcIndirectDataContentEncode, SpcIndirectDataContentDecode);
    WINTRUST_REGISTEROID(SPC_SP_AGENCY_INFO_OBJID, SpcSpAgencyInfoEncode, SpcSpAgencyInfoDecode);
    WINTRUST_REGISTEROID(SPC_SP_AGENCY_INFO_STRUCT, SpcSpAgencyInfoEncode, SpcSpAgencyInfoDecode);
    WINTRUST_REGISTEROID(SPC_MINIMAL_CRITERIA_OBJID, SpcMinimalCriteriaInfoEncode, SpcMinimalCriteriaInfoDecode);
    WINTRUST_REGISTEROID(SPC_MINIMAL_CRITERIA_STRUCT, SpcMinimalCriteriaInfoEncode, SpcMinimalCriteriaInfoDecode);
    WINTRUST_REGISTEROID(SPC_FINANCIAL_CRITERIA_OBJID, SpcFinancialCriteriaInfoEncode, SpcFinancialCriteriaInfoDecode);
    WINTRUST_REGISTEROID(SPC_FINANCIAL_CRITERIA_STRUCT, SpcFinancialCriteriaInfoEncode, SpcFinancialCriteriaInfoDecode);
    WINTRUST_REGISTEROID(SPC_STATEMENT_TYPE_OBJID, SpcStatementTypeEncode, SpcStatementTypeDecode);
    WINTRUST_REGISTEROID(SPC_STATEMENT_TYPE_STRUCT, SpcStatementTypeEncode, SpcStatementTypeDecode);
    WINTRUST_REGISTEROID(CAT_NAMEVALUE_OBJID, CatNameValueEncode, CatNameValueDecode);
    WINTRUST_REGISTEROID(CAT_NAMEVALUE_STRUCT, CatNameValueEncode, CatNameValueDecode);
    WINTRUST_REGISTEROID(CAT_MEMBERINFO_OBJID, CatMemberInfoEncode, CatMemberInfoDecode);
    WINTRUST_REGISTEROID(CAT_MEMBERINFO_STRUCT, CatMemberInfoEncode, CatMemberInfoDecode);
    WINTRUST_REGISTEROID(SPC_SP_OPUS_INFO_OBJID, SpcSpOpusInfoEncode, SpcSpOpusInfoDecode);
    WINTRUST_REGISTEROID(SPC_SP_OPUS_INFO_STRUCT, SpcSpOpusInfoEncode,  SpcSpOpusInfoDecode);

#undef WINTRUST_REGISTEROID

add_trust_providers:

    /* Testing on W2K3 shows:
     * All registry writes are tried. If one fails this part will return S_FALSE.
     *
     * Last error is set to the last error encountered, regardless if the first
     * part failed or not.
     */

    /* Create the necessary action registry structures */
    WINTRUST_InitRegStructs();

    /* Register several Trust Provider actions */
    if (!WINTRUST_RegisterGenVerifyV2())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterPublishedSoftware())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterPublishedSoftwareNoBadUi())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterGenCertVerify())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterTrustProviderTest())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterHttpsProv())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterOfficeSignVerify())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterDriverVerify())
        TrustProviderRes = S_FALSE;
    if (!WINTRUST_RegisterGenChainVerify())
        TrustProviderRes = S_FALSE;

    /* Free the registry structures */
    WINTRUST_FreeRegStructs();

    /* Testing on W2K3 shows:
     * All registry writes are tried. If one fails this part will return S_FALSE.
     *
     * Last error is set to the last error encountered, regardless if the previous
     * parts failed or not.
     */

    if (!WINTRUST_SIPPAddProvider(&Unknown1, NULL))
        SIPAddProviderRes = S_FALSE;
    if (!WINTRUST_SIPPAddProvider(&Unknown2, MagicNumber2))
        SIPAddProviderRes = S_FALSE;
    if (!WINTRUST_SIPPAddProvider(&Unknown3, MagicNumber3))
        SIPAddProviderRes = S_FALSE;
    if (!WINTRUST_SIPPAddProvider(&Unknown4, CafeBabe))
        SIPAddProviderRes = S_FALSE;
    if (!WINTRUST_SIPPAddProvider(&Unknown5, CafeBabe))
        SIPAddProviderRes = S_FALSE;
    if (!WINTRUST_SIPPAddProvider(&Unknown6, CafeBabe))
        SIPAddProviderRes = S_FALSE;

    /* Native does a CryptSIPRemoveProvider here for {941C2937-1292-11D1-85BE-00C04FC295EE}.
     * This SIP Provider is however not found on up-to-date window install and native will
     * set the last error to ERROR_FILE_NOT_FOUND.
     * Wine has the last error set to ERROR_INVALID_PARAMETER. There shouldn't be an app
     * depending on this last error though so there is no need to imitate native to the full extent.
     *
     * (The ERROR_INVALID_PARAMETER for Wine it totally valid as we (and native) do register
     * a trust provider without a diagnostic policy).
     */

    /* Create a dummy context to force creation of the MachineGuid registry key. */
    ret = CryptAcquireContextW(&crypt_provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    if (ret) CryptReleaseContext(crypt_provider, 0);
    else ERR("Failed to acquire cryptographic context: %u\n", GetLastError());

    /* If CryptRegisterRes is not S_OK it will always overrule the return value. */
    if (CryptRegisterRes != S_OK)
        return CryptRegisterRes;
    else if (SIPAddProviderRes == S_OK)
        return TrustProviderRes;
    else 
        return SIPAddProviderRes;
}
예제 #8
0
파일: input.c 프로젝트: RPG-7/reactos
/*
 * NtUserSendInput
 *
 * Generates input events from software
 */
UINT
APIENTRY
NtUserSendInput(
    UINT nInputs,
    LPINPUT pInput,
    INT cbSize)
{
    PTHREADINFO pti;
    UINT uRet = 0;

    TRACE("Enter NtUserSendInput\n");
    UserEnterExclusive();

    pti = PsGetCurrentThreadWin32Thread();
    ASSERT(pti);

    if (!pti->rpdesk)
    {
        goto cleanup;
    }

    if (!nInputs || !pInput || cbSize != sizeof(INPUT))
    {
        EngSetLastError(ERROR_INVALID_PARAMETER);
        goto cleanup;
    }

    /*
     * FIXME: Check access rights of the window station
     *        e.g. services running in the service window station cannot block input
     */
    if (!ThreadHasInputAccess(pti) ||
        !IntIsActiveDesktop(pti->rpdesk))
    {
        EngSetLastError(ERROR_ACCESS_DENIED);
        goto cleanup;
    }

    while (nInputs--)
    {
        INPUT SafeInput;
        NTSTATUS Status;

        Status = MmCopyFromCaller(&SafeInput, pInput++, sizeof(INPUT));
        if (!NT_SUCCESS(Status))
        {
            SetLastNtError(Status);
            goto cleanup;
        }

        switch (SafeInput.type)
        {
            case INPUT_MOUSE:
                if (UserSendMouseInput(&SafeInput.mi, TRUE))
                    uRet++;
                break;
            case INPUT_KEYBOARD:
                if (UserSendKeyboardInput(&SafeInput.ki, TRUE))
                    uRet++;
                break;
            case INPUT_HARDWARE:
                FIXME("INPUT_HARDWARE not supported!");
                break;
            default:
                ERR("SendInput(): Invalid input type: 0x%x\n", SafeInput.type);
                break;
        }
    }

cleanup:
    TRACE("Leave NtUserSendInput, ret=%u\n", uRet);
    UserLeave();
    return uRet;
}
예제 #9
0
static UINT ITERATE_RegisterFonts(MSIRECORD *row, LPVOID param)
{
    MSIPACKAGE *package = param;
    LPWSTR name;
    LPCWSTR filename;
    MSIFILE *file;
    static const WCHAR regfont1[] =
        {'S','o','f','t','w','a','r','e','\\',
         'M','i','c','r','o','s','o','f','t','\\',
         'W','i','n','d','o','w','s',' ','N','T','\\',
         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
         'F','o','n','t','s',0};
    static const WCHAR regfont2[] =
        {'S','o','f','t','w','a','r','e','\\',
         'M','i','c','r','o','s','o','f','t','\\',
         'W','i','n','d','o','w','s','\\',
         'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
         'F','o','n','t','s',0};
    HKEY hkey1;
    HKEY hkey2;
    MSIRECORD *uirow;
    LPWSTR uipath, p;

    filename = MSI_RecordGetString( row, 1 );
    file = get_loaded_file( package, filename );
    if (!file)
    {
        ERR("Unable to load file\n");
        return ERROR_SUCCESS;
    }

    /* check to make sure that component is installed */
    if (!ACTION_VerifyComponentForAction( file->Component, INSTALLSTATE_LOCAL))
    {
        TRACE("Skipping: Component not scheduled for install\n");
        return ERROR_SUCCESS;
    }

    RegCreateKeyW(HKEY_LOCAL_MACHINE,regfont1,&hkey1);
    RegCreateKeyW(HKEY_LOCAL_MACHINE,regfont2,&hkey2);

    if (MSI_RecordIsNull(row,2))
        name = load_ttfname_from( file->TargetPath );
    else
        name = msi_dup_record_field(row,2);

    if (name)
    {
        msi_reg_set_val_str( hkey1, name, file->TargetPath);
        msi_reg_set_val_str( hkey2, name, file->TargetPath);
    }

    msi_free(name);
    RegCloseKey(hkey1);
    RegCloseKey(hkey2);

    /* the UI chunk */
    uirow = MSI_CreateRecord( 1 );
    uipath = strdupW( file->TargetPath );
    p = strrchrW(uipath,'\\');
    if (p) p++;
    else p = uipath;
    MSI_RecordSetStringW( uirow, 1, p );
    ui_actiondata( package, szRegisterFonts, uirow);
    msiobj_release( &uirow->hdr );
    msi_free( uipath );
    /* FIXME: call ui_progress? */

    return ERROR_SUCCESS;
}
예제 #10
0
파일: input.c 프로젝트: RPG-7/reactos
/*
 * RawInputThreadMain
 *
 * Reads data from input devices and supports win32 timers
 */
VOID NTAPI
RawInputThreadMain()
{
    NTSTATUS MouStatus = STATUS_UNSUCCESSFUL, KbdStatus = STATUS_UNSUCCESSFUL, Status;
    IO_STATUS_BLOCK MouIosb, KbdIosb;
    PFILE_OBJECT pKbdDevice = NULL, pMouDevice = NULL;
    LARGE_INTEGER ByteOffset;
    //LARGE_INTEGER WaitTimeout;
    PVOID WaitObjects[3], pSignaledObject = NULL;
    ULONG cWaitObjects = 0, cMaxWaitObjects = 1;
    MOUSE_INPUT_DATA MouseInput;
    KEYBOARD_INPUT_DATA KeyInput;

    ByteOffset.QuadPart = (LONGLONG)0;
    //WaitTimeout.QuadPart = (LONGLONG)(-10000000);

    ptiRawInput = GetW32ThreadInfo();
    ptiRawInput->TIF_flags |= TIF_SYSTEMTHREAD;
    ptiRawInput->pClientInfo->dwTIFlags = ptiRawInput->TIF_flags;

    TRACE("Raw Input Thread %p\n", ptiRawInput);

    KeSetPriorityThread(&PsGetCurrentThread()->Tcb,
                        LOW_REALTIME_PRIORITY + 3);

    UserEnterExclusive();
    StartTheTimers();
    UserLeave();

    for (;;)
    {
        if (!ghMouseDevice)
        {
            /* Check if mouse device already exists */
            Status = OpenInputDevice(&ghMouseDevice, &pMouDevice, L"\\Device\\PointerClass0" );
            if (NT_SUCCESS(Status))
            {
                ++cMaxWaitObjects;
                TRACE("Mouse connected!\n");
            }
        }
        if (!ghKeyboardDevice)
        {
            /* Check if keyboard device already exists */
            Status = OpenInputDevice(&ghKeyboardDevice, &pKbdDevice, L"\\Device\\KeyboardClass0");
            if (NT_SUCCESS(Status))
            {
                ++cMaxWaitObjects;
                TRACE("Keyboard connected!\n");
                // Get and load keyboard attributes.
                UserInitKeyboard(ghKeyboardDevice);
                UserEnterExclusive();
                // Register the Window hotkey.
                UserRegisterHotKey(PWND_BOTTOM, IDHK_WINKEY, MOD_WIN, 0);
                // Register the debug hotkeys.
                StartDebugHotKeys();
                UserLeave();
            }
        }

        /* Reset WaitHandles array */
        cWaitObjects = 0;
        WaitObjects[cWaitObjects++] = MasterTimer;

        if (ghMouseDevice)
        {
            /* Try to read from mouse if previous reading is not pending */
            if (MouStatus != STATUS_PENDING)
            {
                MouStatus = ZwReadFile(ghMouseDevice,
                                       NULL,
                                       NULL,
                                       NULL,
                                       &MouIosb,
                                       &MouseInput,
                                       sizeof(MOUSE_INPUT_DATA),
                                       &ByteOffset,
                                       NULL);
            }

            if (MouStatus == STATUS_PENDING)
                WaitObjects[cWaitObjects++] = &pMouDevice->Event;
        }

        if (ghKeyboardDevice)
        {
            /* Try to read from keyboard if previous reading is not pending */
            if (KbdStatus != STATUS_PENDING)
            {
                KbdStatus = ZwReadFile(ghKeyboardDevice,
                                       NULL,
                                       NULL,
                                       NULL,
                                       &KbdIosb,
                                       &KeyInput,
                                       sizeof(KEYBOARD_INPUT_DATA),
                                       &ByteOffset,
                                       NULL);

            }
            if (KbdStatus == STATUS_PENDING)
                WaitObjects[cWaitObjects++] = &pKbdDevice->Event;
        }

        /* If all objects are pending, wait for them */
        if (cWaitObjects == cMaxWaitObjects)
        {
            Status = KeWaitForMultipleObjects(cWaitObjects,
                                              WaitObjects,
                                              WaitAny,
                                              UserRequest,
                                              KernelMode,
                                              TRUE,
                                              NULL,//&WaitTimeout,
                                              NULL);

            if ((Status >= STATUS_WAIT_0) &&
                (Status < (STATUS_WAIT_0 + (LONG)cWaitObjects)))
            {
                /* Some device has finished reading */
                pSignaledObject = WaitObjects[Status - STATUS_WAIT_0];

                /* Check if it is mouse or keyboard and update status */
                if (pSignaledObject == &pMouDevice->Event)
                    MouStatus = MouIosb.Status;
                else if (pSignaledObject == &pKbdDevice->Event)
                    KbdStatus = KbdIosb.Status;
                else if (pSignaledObject == MasterTimer)
                {
                    ProcessTimers();
                }
                else ASSERT(FALSE);
            }
        }

        /* Have we successed reading from mouse? */
        if (NT_SUCCESS(MouStatus) && MouStatus != STATUS_PENDING)
        {
            TRACE("MouseEvent\n");

            /* Set LastInputTick */
            IntLastInputTick(TRUE);

            /* Process data */
            UserEnterExclusive();
            UserProcessMouseInput(&MouseInput);
            UserLeave();
        }
        else if (MouStatus != STATUS_PENDING)
            ERR("Failed to read from mouse: %x.\n", MouStatus);

        /* Have we successed reading from keyboard? */
        if (NT_SUCCESS(KbdStatus) && KbdStatus != STATUS_PENDING)
        {
            TRACE("KeyboardEvent: %s %04x\n",
                  (KeyInput.Flags & KEY_BREAK) ? "up" : "down",
                  KeyInput.MakeCode);

            /* Set LastInputTick */
            IntLastInputTick(TRUE);

            /* Process data */
            UserEnterExclusive();
            UserProcessKeyboardInput(&KeyInput);
            UserLeave();
        }
        else if (KbdStatus != STATUS_PENDING)
            ERR("Failed to read from keyboard: %x.\n", KbdStatus);
    }
    ERR("Raw Input Thread Exit!\n");
}
예제 #11
0
파일: input.c 프로젝트: RPG-7/reactos
NTSTATUS FASTCALL
UserAttachThreadInput(PTHREADINFO ptiFrom, PTHREADINFO ptiTo, BOOL fAttach)
{
    MSG msg;
    PATTACHINFO pai;

    /* Can not be the same thread. */
    if (ptiFrom == ptiTo) return STATUS_INVALID_PARAMETER;

    /* Do not attach to system threads or between different desktops. */
    if (ptiFrom->TIF_flags & TIF_DONTATTACHQUEUE ||
        ptiTo->TIF_flags & TIF_DONTATTACHQUEUE ||
        ptiFrom->rpdesk != ptiTo->rpdesk)
        return STATUS_ACCESS_DENIED;

    /* MSDN Note:
       Keyboard and mouse events received by both threads are processed by the thread specified by the idAttachTo.
     */

    /* If Attach set, allocate and link. */
    if (fAttach)
    {
        pai = ExAllocatePoolWithTag(PagedPool, sizeof(ATTACHINFO), USERTAG_ATTACHINFO);
        if (!pai) return STATUS_NO_MEMORY;

        pai->paiNext = gpai;
        pai->pti1 = ptiFrom;
        pai->pti2 = ptiTo;
        gpai = pai;
        paiCount++;
        ERR("Attach Allocated! ptiFrom 0x%p  ptiTo 0x%p paiCount %d\n",ptiFrom,ptiTo,paiCount);

        if (ptiTo->MessageQueue != ptiFrom->MessageQueue)
        {

           ptiTo->MessageQueue->iCursorLevel -= ptiFrom->iCursorLevel;

           // FIXME: conditions?
           if (ptiTo->MessageQueue == gpqForeground)
           {
              ERR("ptiTo is Foreground\n");
           }
           else
           {
              ERR("ptiTo NOT Foreground\n");
           }

           if (ptiFrom->MessageQueue == gpqForeground)
           {
              ERR("ptiFrom is Foreground\n");
              ptiTo->MessageQueue->spwndActive  = ptiFrom->MessageQueue->spwndActive;
              ptiTo->MessageQueue->spwndFocus   = ptiFrom->MessageQueue->spwndFocus;
              ptiTo->MessageQueue->CursorObject = ptiFrom->MessageQueue->CursorObject;
              ptiTo->MessageQueue->spwndCapture = ptiFrom->MessageQueue->spwndCapture;
              ptiTo->MessageQueue->QF_flags    ^= ((ptiTo->MessageQueue->QF_flags ^ ptiFrom->MessageQueue->QF_flags) & QF_CAPTURELOCKED);
              ptiTo->MessageQueue->CaretInfo    = ptiFrom->MessageQueue->CaretInfo;
              IntSetFocusMessageQueue(NULL);
              IntSetFocusMessageQueue(ptiTo->MessageQueue);
              gptiForeground = ptiTo;
           }
           else
           {
              ERR("ptiFrom NOT Foreground\n");
           }

           MsqDestroyMessageQueue(ptiFrom);

           ptiFrom->MessageQueue = ptiTo->MessageQueue;

           ptiFrom->MessageQueue->cThreads++;
           ERR("ptiTo S Share count %d\n", ptiFrom->MessageQueue->cThreads);

           IntReferenceMessageQueue(ptiTo->MessageQueue);
        }
        else
        {
           ERR("Attach Threads are already associated!\n");
        }
    }
    else /* If clear, unlink and free it. */
    {
        BOOL Hit = FALSE;
        PATTACHINFO *ppai;

        if (!gpai) return STATUS_INVALID_PARAMETER;

        /* Search list and free if found or return false. */
        ppai = &gpai;
        while (*ppai != NULL)
        {
           if ( (*ppai)->pti2 == ptiTo && (*ppai)->pti1 == ptiFrom )
           {
              pai = *ppai;
              /* Remove it from the list */
              *ppai = (*ppai)->paiNext;
              ExFreePoolWithTag(pai, USERTAG_ATTACHINFO);
              paiCount--;
              Hit = TRUE;
              break;
           }
           ppai = &((*ppai)->paiNext);
        }

        if (!Hit) return STATUS_INVALID_PARAMETER;
 
        ERR("Attach Free! ptiFrom 0x%p  ptiTo 0x%p paiCount %d\n",ptiFrom,ptiTo,paiCount);
 
        if (ptiTo->MessageQueue == ptiFrom->MessageQueue)
        {
           if (gptiForeground == ptiFrom)
           {
              ERR("ptiTo is now pti FG.\n");
              // MessageQueue foreground is set so switch threads.
              gptiForeground = ptiTo;
           }
           ptiTo->MessageQueue->cThreads--;
           ERR("ptiTo E Share count %d\n", ptiTo->MessageQueue->cThreads);
           ASSERT(ptiTo->MessageQueue->cThreads >= 1);

           IntDereferenceMessageQueue(ptiTo->MessageQueue);

           ptiFrom->MessageQueue = MsqCreateMessageQueue(ptiFrom);

           ptiTo->MessageQueue->iCursorLevel -= ptiFrom->iCursorLevel;
        }
        else
        {
           ERR("Detaching Threads are not associated!\n");
        }
    }
    /* Note that key state, which can be ascertained by calls to the GetKeyState
       or GetKeyboardState function, is reset after a call to AttachThreadInput.
       ATM which one?
     */
    RtlCopyMemory(ptiTo->MessageQueue->afKeyState, gafAsyncKeyState, sizeof(gafAsyncKeyState));

    /* Generate mouse move message */
    msg.message = WM_MOUSEMOVE;
    msg.wParam = UserGetMouseButtonsState();
    msg.lParam = MAKELPARAM(gpsi->ptCursor.x, gpsi->ptCursor.y);
    msg.pt = gpsi->ptCursor;
    co_MsqInsertMouseMessage(&msg, 0, 0, TRUE);

    return STATUS_SUCCESS;
}
예제 #12
0
static NTSTATUS hash_finish( struct hash *hash, UCHAR *output, ULONG size )
{
    ERR( "support for hashes not available at build time\n" );
    return STATUS_NOT_IMPLEMENTED;
}
예제 #13
0
static NTSTATUS hash_init( struct hash *hash )
{
    ERR( "support for hashes not available at build time\n" );
    return STATUS_NOT_IMPLEMENTED;
}
예제 #14
0
static ALCenum MMDevApiOpenPlayback(ALCdevice *device, const ALCchar *deviceName)
{
    MMDevApiData *data = NULL;
    HRESULT hr;

    //Initialise requested device
    data = calloc(1, sizeof(MMDevApiData));
    if(!data)
        return ALC_OUT_OF_MEMORY;
    device->ExtraData = data;

    hr = S_OK;
    data->NotifyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    data->MsgEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if(data->NotifyEvent == NULL || data->MsgEvent == NULL)
    {
        ERR("Failed to create message events: %lu\n", GetLastError());
        hr = E_FAIL;
    }

    if(SUCCEEDED(hr))
    {
        if(deviceName)
        {
            ALuint i;

            if(!PlaybackDeviceList)
            {
                ThreadRequest req = { data->MsgEvent, 0 };
                if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, ALL_DEVICE_PROBE))
                    (void)WaitForResponse(&req);
            }

            hr = E_FAIL;
            for(i = 0;i < NumPlaybackDevices;i++)
            {
                if(strcmp(deviceName, PlaybackDeviceList[i].name) == 0)
                {
                    data->devid = strdupW(PlaybackDeviceList[i].devid);
                    hr = S_OK;
                    break;
                }
            }
            if(FAILED(hr))
                WARN("Failed to find device name matching \"%s\"\n", deviceName);
        }
    }

    if(SUCCEEDED(hr))
    {
        ThreadRequest req = { data->MsgEvent, 0 };

        hr = E_FAIL;
        if(PostThreadMessage(ThreadID, WM_USER_OpenDevice, (WPARAM)&req, (LPARAM)device))
            hr = WaitForResponse(&req);
        else
            ERR("Failed to post thread message: %lu\n", GetLastError());
    }

    if(FAILED(hr))
    {
        if(data->NotifyEvent != NULL)
            CloseHandle(data->NotifyEvent);
        data->NotifyEvent = NULL;
        if(data->MsgEvent != NULL)
            CloseHandle(data->MsgEvent);
        data->MsgEvent = NULL;

        free(data->devid);
        data->devid = NULL;

        free(data);
        device->ExtraData = NULL;

        ERR("Device init failed: 0x%08lx\n", hr);
        return ALC_INVALID_VALUE;
    }

    return ALC_NO_ERROR;
}
예제 #15
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_poolset_open -- (internal) open memory pool set
 *
 * On success returns 0 and a pointer to a newly allocated structure
 * containing the info of all the parts of the pool set and replicas.
 */
static int
util_poolset_open(struct pool_set **setp, const char *path, size_t minsize)
{
	LOG(3, "setp %p path %s minsize %zu", setp, path, minsize);

	int oerrno;
	int ret = 0;
	int fd;
	size_t size = 0;

	/* do not check minsize */
	if ((fd = util_file_open(path, &size, 0, O_RDONLY)) == -1)
		return -1;

	char signature[POOLSET_HDR_SIG_LEN];
	/*
	 * read returns ssize_t, but we know it will return value between -1
	 * and POOLSET_HDR_SIG_LEN (11), so we can safely cast it to int
	 */
	ret = (int)read(fd, signature, POOLSET_HDR_SIG_LEN);
	if (ret < 0) {
		ERR("!read %d", fd);
		goto err;
	}

	if (ret < POOLSET_HDR_SIG_LEN ||
	    strncmp(signature, POOLSET_HDR_SIG, POOLSET_HDR_SIG_LEN)) {
		LOG(4, "not a pool set header");

		if (size < minsize) {
			ERR("size %zu smaller than %zu", size, minsize);
			errno = EINVAL;
			ret = -1;
			goto err;
		}

		/* close the file and open with O_RDWR */
		(void) close(fd);
		size = 0;
		if ((fd = util_file_open(path, &size, 0, O_RDWR)) == -1)
			return -1;

		*setp = util_poolset_single(path, size, fd, 0);
		if (*setp == NULL) {
			ret = -1;
			goto err;
		}

		/* do not close the file */
		return 0;
	}

	ret = util_poolset_parse(path, fd, setp);
	if (ret != 0)
		goto err;

	ret = util_poolset_files(*setp, minsize, 0);
	if (ret != 0)
		util_poolset_close(*setp, 0);

err:
	oerrno = errno;
	(void) close(fd);
	errno = oerrno;
	return ret;
}
예제 #16
0
/*
 * Code based off of code located here
 * http://www.codeproject.com/gdi/fontnamefromfile.asp
 *
 * Using string index 4 (full font name) instead of 1 (family name)
 */
static LPWSTR load_ttfname_from(LPCWSTR filename)
{
    TT_TABLE_DIRECTORY tblDir;
    BOOL bFound = FALSE;
    TT_OFFSET_TABLE ttOffsetTable;
    TT_NAME_TABLE_HEADER ttNTHeader;
    TT_NAME_RECORD ttRecord;
    DWORD dwRead;
    HANDLE handle;
    LPWSTR ret = NULL;
    int i;

    handle = CreateFileW(filename ,GENERIC_READ, 0, NULL, OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL, 0 );
    if (handle == INVALID_HANDLE_VALUE)
    {
        ERR("Unable to open font file %s\n", debugstr_w(filename));
        return NULL;
    }

    if (!ReadFile(handle,&ttOffsetTable, sizeof(TT_OFFSET_TABLE),&dwRead,NULL))
        goto end;

    ttOffsetTable.uNumOfTables = SWAPWORD(ttOffsetTable.uNumOfTables);
    ttOffsetTable.uMajorVersion = SWAPWORD(ttOffsetTable.uMajorVersion);
    ttOffsetTable.uMinorVersion = SWAPWORD(ttOffsetTable.uMinorVersion);

    if (ttOffsetTable.uMajorVersion != 1 || ttOffsetTable.uMinorVersion != 0)
        goto end;

    for (i=0; i< ttOffsetTable.uNumOfTables; i++)
    {
        if (!ReadFile(handle,&tblDir, sizeof(TT_TABLE_DIRECTORY),&dwRead,NULL))
            break;
        if (memcmp(tblDir.szTag,"name",4)==0)
        {
            bFound = TRUE;
            tblDir.uLength = SWAPLONG(tblDir.uLength);
            tblDir.uOffset = SWAPLONG(tblDir.uOffset);
            break;
        }
    }

    if (!bFound)
        goto end;

    SetFilePointer(handle, tblDir.uOffset, NULL, FILE_BEGIN);
    if (!ReadFile(handle,&ttNTHeader, sizeof(TT_NAME_TABLE_HEADER), &dwRead,NULL))
        goto end;

    ttNTHeader.uNRCount = SWAPWORD(ttNTHeader.uNRCount);
    ttNTHeader.uStorageOffset = SWAPWORD(ttNTHeader.uStorageOffset);
    bFound = FALSE;
    for(i=0; i<ttNTHeader.uNRCount; i++)
    {
        if (!ReadFile(handle,&ttRecord, sizeof(TT_NAME_RECORD),&dwRead,NULL))
            break;

        ttRecord.uNameID = SWAPWORD(ttRecord.uNameID);
        /* 4 is the Full Font Name */
        if(ttRecord.uNameID == 4)
        {
            int nPos;
            LPSTR buf;
            static const char tt[] = " (TrueType)";

            ttRecord.uStringLength = SWAPWORD(ttRecord.uStringLength);
            ttRecord.uStringOffset = SWAPWORD(ttRecord.uStringOffset);
            nPos = SetFilePointer(handle, 0, NULL, FILE_CURRENT);
            SetFilePointer(handle, tblDir.uOffset +
                            ttRecord.uStringOffset +
                            ttNTHeader.uStorageOffset,
                            NULL, FILE_BEGIN);
            buf = msi_alloc_zero( ttRecord.uStringLength + 1 + strlen(tt) );
            ReadFile(handle, buf, ttRecord.uStringLength, &dwRead, NULL);
            if (strlen(buf) > 0)
            {
                strcat(buf,tt);
                ret = strdupAtoW(buf);
                msi_free(buf);
                break;
            }

            msi_free(buf);
            SetFilePointer(handle,nPos, NULL, FILE_BEGIN);
        }
    }

end:
    CloseHandle(handle);

    TRACE("Returning fontname %s\n",debugstr_w(ret));
    return ret;
}
예제 #17
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_header_create -- (internal) create header of a single pool set file
 */
static int
util_header_create(struct pool_set *set, unsigned repidx, unsigned partidx,
	size_t hdrsize, const char *sig, uint32_t major, uint32_t compat,
	uint32_t incompat, uint32_t ro_compat)
{
	LOG(3, "set %p repidx %u partidx %u hdrsize %zu sig %.8s major %u "
		"compat %#x incompat %#x ro_comapt %#x",
		set, repidx, partidx, hdrsize,
		sig, major, compat, incompat, ro_compat);

	struct pool_replica *rep = set->replica[repidx];

	/* opaque info lives at the beginning of mapped memory pool */
	struct pool_hdr *hdrp = rep->part[partidx].hdr;

	/* check if the pool header is all zeros */
	if (!util_is_zeroed(hdrp, sizeof (*hdrp))) {
		ERR("Non-empty file detected");
		errno = EINVAL;
		return -1;
	}

	/*
	 * Zero out the pool descriptor - just in case we fail right after
	 * header checksum is stored.
	 */
	void *descp = (void *)((uintptr_t)hdrp + sizeof (*hdrp));
	memset(descp, 0, hdrsize - sizeof (*hdrp));
	pmem_msync(descp, hdrsize - sizeof (*hdrp));

	/* create pool's header */
	memcpy(hdrp->signature, sig, POOL_HDR_SIG_LEN);
	hdrp->major = htole32(major);
	hdrp->compat_features = htole32(compat);
	hdrp->incompat_features = htole32(incompat);
	hdrp->ro_compat_features = htole32(ro_compat);

	memcpy(hdrp->poolset_uuid, set->uuid, POOL_HDR_UUID_LEN);

	memcpy(hdrp->uuid, PART(rep, partidx).uuid, POOL_HDR_UUID_LEN);

	/* link parts */
	memcpy(hdrp->prev_part_uuid, PART(rep, partidx - 1).uuid,
							POOL_HDR_UUID_LEN);
	memcpy(hdrp->next_part_uuid, PART(rep, partidx + 1).uuid,
							POOL_HDR_UUID_LEN);

	/* link replicas */
	memcpy(hdrp->prev_repl_uuid, PART(REP(set, repidx - 1), 0).uuid,
							POOL_HDR_UUID_LEN);
	memcpy(hdrp->next_repl_uuid, PART(REP(set, repidx + 1), 0).uuid,
							POOL_HDR_UUID_LEN);

	hdrp->crtime = htole64((uint64_t)time(NULL));

	if (util_get_arch_flags(&hdrp->arch_flags)) {
		ERR("Reading architecture flags failed\n");
		errno = EINVAL;
		return -1;
	}

	hdrp->arch_flags.alignment_desc =
		htole64(hdrp->arch_flags.alignment_desc);
	hdrp->arch_flags.e_machine =
		htole16(hdrp->arch_flags.e_machine);

	util_checksum(hdrp, sizeof (*hdrp), &hdrp->checksum, 1);

	/* store pool's header */
	pmem_msync(hdrp, sizeof (*hdrp));

	return 0;
}
예제 #18
0
static int get_comp(str* res, int local, int issuer, int nid, sip_msg_t* msg)
{
    static char buf[1024];
    X509* cert;
    struct tcp_connection* c;
    X509_NAME* name;
    X509_NAME_ENTRY* e;
    ASN1_STRING* asn1;
    int index, text_len;
    char* elem;
    unsigned char* text_s;

    text_s = 0;

    if (get_cert(&cert, &c, msg, local) < 0) return -1;

    name = issuer ? X509_get_issuer_name(cert) : X509_get_subject_name(cert);
    if (!name) {
        ERR("Cannot extract subject or issuer name from peer certificate\n");
        goto err;
    }

    index = X509_NAME_get_index_by_NID(name, nid, -1);
    if (index == -1) {
        switch(nid) {
        case NID_commonName:
            elem = "CommonName";
            break;
        case NID_organizationName:
            elem = "OrganizationName";
            break;
        case NID_organizationalUnitName:
            elem = "OrganizationalUnitUname";
            break;
        case NID_countryName:
            elem = "CountryName";
            break;
        case NID_stateOrProvinceName:
            elem = "StateOrProvinceName";
            break;
        case NID_localityName:
            elem = "LocalityName";
            break;
        default:
            elem = "Unknown";
            break;
        }
        DBG("Element %s not found in certificate subject/issuer\n", elem);
        goto err;
    }

    e = X509_NAME_get_entry(name, index);
    asn1 = X509_NAME_ENTRY_get_data(e);
    text_len = ASN1_STRING_to_UTF8(&text_s, asn1);
    if (text_len < 0 || text_len >= 1024) {
        ERR("Error converting ASN1 string\n");
        goto err;
    }
    memcpy(buf, text_s, text_len);
    res->s = buf;
    res->len = text_len;

    OPENSSL_free(text_s);
    if (!local) X509_free(cert);
    tcpconn_put(c);
    return 0;

err:
    if (text_s) OPENSSL_free(text_s);
    if (!local) X509_free(cert);
    tcpconn_put(c);
    return -1;
}
예제 #19
0
파일: regexec.c 프로젝트: samuelan/postgres
/*
 * cfindloop - the heart of cfind
 */
static int
cfindloop(struct vars * v,
		  struct cnfa * cnfa,
		  struct colormap * cm,
		  struct dfa * d,
		  struct dfa * s,
		  chr **coldp)			/* where to put coldstart pointer */
{
	chr		   *begin;
	chr		   *end;
	chr		   *cold;
	chr		   *open;			/* open and close of range of possible starts */
	chr		   *close;
	chr		   *estart;
	chr		   *estop;
	int			er;
	int			shorter = v->g->tree->flags & SHORTER;
	int			hitend;

	assert(d != NULL && s != NULL);
	cold = NULL;
	close = v->search_start;
	do
	{
		MDEBUG(("\ncsearch at %ld\n", LOFF(close)));
		close = shortest(v, s, close, close, v->stop, &cold, (int *) NULL);
		if (close == NULL)
			break;				/* NOTE BREAK */
		assert(cold != NULL);
		open = cold;
		cold = NULL;
		MDEBUG(("cbetween %ld and %ld\n", LOFF(open), LOFF(close)));
		for (begin = open; begin <= close; begin++)
		{
			MDEBUG(("\ncfind trying at %ld\n", LOFF(begin)));
			estart = begin;
			estop = v->stop;
			for (;;)
			{
				if (shorter)
					end = shortest(v, d, begin, estart,
								   estop, (chr **) NULL, &hitend);
				else
					end = longest(v, d, begin, estop,
								  &hitend);
				if (hitend && cold == NULL)
					cold = begin;
				if (end == NULL)
					break;		/* NOTE BREAK OUT */
				MDEBUG(("tentative end %ld\n", LOFF(end)));
				zapallsubs(v->pmatch, v->nmatch);
				er = cdissect(v, v->g->tree, begin, end);
				if (er == REG_OKAY)
				{
					if (v->nmatch > 0)
					{
						v->pmatch[0].rm_so = OFF(begin);
						v->pmatch[0].rm_eo = OFF(end);
					}
					*coldp = cold;
					return REG_OKAY;
				}
				if (er != REG_NOMATCH)
				{
					ERR(er);
					*coldp = cold;
					return er;
				}
				/* try next shorter/longer match with same begin point */
				if (shorter)
				{
					if (end == estop)
						break;	/* NOTE BREAK OUT */
					estart = end + 1;
				}
				else
				{
					if (end == begin)
						break;	/* NOTE BREAK OUT */
					estop = end - 1;
				}
			}					/* end loop over endpoint positions */
		}						/* end loop over beginning positions */
	} while (close < v->stop);

	*coldp = cold;
	return REG_NOMATCH;
}
예제 #20
0
static int get_alt(str* res, int local, int type, sip_msg_t* msg)
{
    static char buf[1024];
    int n, found = 0;
    STACK_OF(GENERAL_NAME)* names = 0;
    GENERAL_NAME* nm;
    X509* cert;
    struct tcp_connection* c;
    str text;
    struct ip_addr ip;

    if (get_cert(&cert, &c, msg, local) < 0) return -1;

    names = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
    if (!names) {
        DBG("Cannot get certificate alternative subject\n");
        goto err;

    }

    for (n = 0; n < sk_GENERAL_NAME_num(names); n++) {
        nm = sk_GENERAL_NAME_value(names, n);
        if (nm->type != type) continue;
        switch(type) {
        case GEN_EMAIL:
        case GEN_DNS:
        case GEN_URI:
            text.s = (char*)nm->d.ia5->data;
            text.len = nm->d.ia5->length;
            if (text.len >= 1024) {
                ERR("Alternative subject text too long\n");
                goto err;
            }
            memcpy(buf, text.s, text.len);
            res->s = buf;
            res->len = text.len;
            found = 1;
            break;

        case GEN_IPADD:
            ip.len = nm->d.iPAddress->length;
            ip.af = (ip.len == 16) ? AF_INET6 : AF_INET;
            memcpy(ip.u.addr, nm->d.iPAddress->data, ip.len);
            text.s = ip_addr2a(&ip);
            text.len = strlen(text.s);
            memcpy(buf, text.s, text.len);
            res->s = buf;
            res->len = text.len;
            found = 1;
            break;
        }
        break;
    }
    if (!found) goto err;

    if (names) sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
    if (!local) X509_free(cert);
    tcpconn_put(c);
    return 0;
err:
    if (names) sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
    if (!local) X509_free(cert);
    tcpconn_put(c);
    return -1;
}
예제 #21
0
파일: d3d10_main.c 프로젝트: devyn/wine
HRESULT WINAPI D3D10CreateDeviceAndSwapChain(IDXGIAdapter *adapter, D3D10_DRIVER_TYPE driver_type,
        HMODULE swrast, UINT flags, UINT sdk_version, DXGI_SWAP_CHAIN_DESC *swapchain_desc,
        IDXGISwapChain **swapchain, ID3D10Device **device)
{
    IDXGIDevice *dxgi_device;
    IDXGIFactory *factory;
    HRESULT hr;

    TRACE("adapter %p, driver_type %s, swrast %p, flags %#x, sdk_version %d,\n"
            "\tswapchain_desc %p, swapchain %p, device %p\n",
            adapter, debug_d3d10_driver_type(driver_type), swrast, flags, sdk_version,
            swapchain_desc, swapchain, device);

    hr = D3D10CreateDevice(adapter, driver_type, swrast, flags, sdk_version, device);
    if (FAILED(hr))
    {
        WARN("Failed to create a device, returning %#x\n", hr);
        *device = NULL;
        return hr;
    }

    TRACE("Created ID3D10Device %p\n", *device);

    hr = ID3D10Device_QueryInterface(*device, &IID_IDXGIDevice, (void **)&dxgi_device);
    if (FAILED(hr))
    {
        ERR("Failed to get a dxgi device from the d3d10 device, returning %#x\n", hr);
        ID3D10Device_Release(*device);
        *device = NULL;
        return hr;
    }

    hr = IDXGIDevice_GetAdapter(dxgi_device, &adapter);
    IDXGIDevice_Release(dxgi_device);
    if (FAILED(hr))
    {
        ERR("Failed to get the device adapter, returning %#x\n", hr);
        ID3D10Device_Release(*device);
        *device = NULL;
        return hr;
    }

    hr = IDXGIAdapter_GetParent(adapter, &IID_IDXGIFactory, (void **)&factory);
    IDXGIAdapter_Release(adapter);
    if (FAILED(hr))
    {
        ERR("Failed to get the adapter factory, returning %#x\n", hr);
        ID3D10Device_Release(*device);
        *device = NULL;
        return hr;
    }

    hr = IDXGIFactory_CreateSwapChain(factory, (IUnknown *)*device, swapchain_desc, swapchain);
    IDXGIFactory_Release(factory);
    if (FAILED(hr))
    {
        ID3D10Device_Release(*device);
        *device = NULL;

        WARN("Failed to create a swapchain, returning %#x\n", hr);
        return hr;
    }

    TRACE("Created IDXGISwapChain %p\n", *swapchain);

    return S_OK;
}
예제 #22
0
MeshLib::Mesh* addLayerToMesh(MeshLib::Mesh const& mesh, double thickness,
    std::string const& name,
    bool on_top)
{
    INFO("Extracting top surface of mesh \"%s\" ... ", mesh.getName().c_str());
    int const flag = (on_top) ? -1 : 1;
    const MathLib::Vector3 dir(0, 0, flag);
    double const angle(90);
    std::unique_ptr<MeshLib::Mesh> sfc_mesh (nullptr);

    std::string const prop_name("OriginalSubsurfaceNodeIDs");

    if (mesh.getDimension() == 3)
        sfc_mesh.reset(MeshLib::MeshSurfaceExtraction::getMeshSurface(
            mesh, dir, angle, prop_name));
    else {
        sfc_mesh = (on_top) ? std::unique_ptr<MeshLib::Mesh>(new MeshLib::Mesh(mesh)) :
                              std::unique_ptr<MeshLib::Mesh>(MeshLib::createFlippedMesh(mesh));
        // add property storing node ids
        boost::optional<MeshLib::PropertyVector<std::size_t>&> pv(
            sfc_mesh->getProperties().createNewPropertyVector<std::size_t>(
                prop_name, MeshLib::MeshItemType::Node, 1));
        if (pv) {
            pv->resize(sfc_mesh->getNumberOfNodes());
            std::iota(pv->begin(), pv->end(), 0);
        } else {
            ERR("Could not create and initialize property.");
            return nullptr;
        }
    }
    INFO("done.");

    // *** add new surface nodes
    std::vector<MeshLib::Node*> subsfc_nodes =
        MeshLib::copyNodeVector(mesh.getNodes());
    std::vector<MeshLib::Element*> subsfc_elements =
        MeshLib::copyElementVector(mesh.getElements(), subsfc_nodes);

    std::size_t const n_subsfc_nodes(subsfc_nodes.size());

    std::vector<MeshLib::Node*> const& sfc_nodes(sfc_mesh->getNodes());
    std::size_t const n_sfc_nodes(sfc_nodes.size());

    // fetch subsurface node ids PropertyVector
    boost::optional<MeshLib::PropertyVector<std::size_t> const&> opt_node_id_pv(
        sfc_mesh->getProperties().getPropertyVector<std::size_t>(prop_name));
    if (!opt_node_id_pv) {
        ERR(
            "Need subsurface node ids, but the property \"%s\" is not "
            "available.",
            prop_name.c_str());
        return nullptr;
    }

    MeshLib::PropertyVector<std::size_t> const& node_id_pv(*opt_node_id_pv);
    // *** copy sfc nodes to subsfc mesh node
    std::map<std::size_t, std::size_t> subsfc_sfc_id_map;
    for (std::size_t k(0); k<n_sfc_nodes; ++k) {
        std::size_t const subsfc_id(node_id_pv[k]);
        std::size_t const sfc_id(k+n_subsfc_nodes);
        subsfc_sfc_id_map.insert(std::make_pair(subsfc_id, sfc_id));
        MeshLib::Node const& node(*sfc_nodes[k]);
        subsfc_nodes.push_back(new MeshLib::Node(
            node[0], node[1], node[2] - (flag * thickness), sfc_id));
    }

    // *** insert new layer elements into subsfc_mesh
    std::vector<MeshLib::Element*> const& sfc_elements(sfc_mesh->getElements());
    std::size_t const n_sfc_elements(sfc_elements.size());
    for (std::size_t k(0); k<n_sfc_elements; ++k)
        subsfc_elements.push_back(extrudeElement(subsfc_nodes, *sfc_elements[k],
                                                 node_id_pv,
                                                 subsfc_sfc_id_map));

    auto new_mesh = new MeshLib::Mesh(name, subsfc_nodes, subsfc_elements);

    boost::optional<MeshLib::PropertyVector<int> const&> opt_materials(
        mesh.getProperties().getPropertyVector<int>("MaterialIDs")
    );

    if (opt_materials) {
        boost::optional<PropertyVector<int> &> new_materials(
        new_mesh->getProperties().createNewPropertyVector<int>("MaterialIDs",
            MeshLib::MeshItemType::Cell, 1));
        if (!new_materials) {
            ERR("Can not set material properties for new layer");
        } else {
            new_materials->reserve(subsfc_elements.size());
            int new_layer_id (*(std::max_element(opt_materials->cbegin(), opt_materials->cend()))+1);
            std::copy(opt_materials->cbegin(), opt_materials->cend(), std::back_inserter(*new_materials));
            auto const n_new_props(subsfc_elements.size()-mesh.getNumberOfElements());
            std::fill_n(std::back_inserter(*new_materials), n_new_props, new_layer_id);
        }
    } else {
        ERR(
            "Could not copy the property \"MaterialIDs\" since the original "
            "mesh does not contain such a property.");
    }

    return new_mesh;
}
예제 #23
0
파일: lsalpc.c 프로젝트: reactos/reactos
/*
 * @unimplemented
 */
NTSTATUS
NTAPI
LsaGetLogonSessionData(
    PLUID LogonId,
    PSECURITY_LOGON_SESSION_DATA *ppLogonSessionData)
{
    LSA_API_MSG ApiMessage;
    PSECURITY_LOGON_SESSION_DATA SessionData;
    NTSTATUS Status;

    TRACE("LsaGetLogonSessionData(%p %p)\n", LogonId, ppLogonSessionData);

    Status = LsapOpenLsaPort();
    if (!NT_SUCCESS(Status))
        return Status;

    ApiMessage.ApiNumber = LSASS_REQUEST_GET_LOGON_SESSION_DATA;
    ApiMessage.h.u1.s1.DataLength = LSA_PORT_DATA_SIZE(ApiMessage.GetLogonSessionData);
    ApiMessage.h.u1.s1.TotalLength = LSA_PORT_MESSAGE_SIZE;
    ApiMessage.h.u2.ZeroInit = 0;

    RtlCopyLuid(&ApiMessage.GetLogonSessionData.Request.LogonId,
                LogonId);

    Status = NtRequestWaitReplyPort(LsaPortHandle,
                                    (PPORT_MESSAGE)&ApiMessage,
                                    (PPORT_MESSAGE)&ApiMessage);
    if (!NT_SUCCESS(Status))
    {
        ERR("NtRequestWaitReplyPort() failed (Status 0x%08lx)\n", Status);
        return Status;
    }

    if (!NT_SUCCESS(ApiMessage.Status))
    {
        ERR("NtRequestWaitReplyPort() failed (ApiMessage.Status 0x%08lx)\n", ApiMessage.Status);
        return ApiMessage.Status;
    }

    SessionData = ApiMessage.GetLogonSessionData.Reply.SessionDataBuffer;

    TRACE("UserName: %p\n", SessionData->UserName.Buffer);
    if (SessionData->UserName.Buffer != NULL)
        SessionData->UserName.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->UserName.Buffer);

    TRACE("LogonDomain: %p\n", SessionData->LogonDomain.Buffer);
    if (SessionData->LogonDomain.Buffer != NULL)
        SessionData->LogonDomain.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->LogonDomain.Buffer);

    TRACE("AuthenticationPackage: %p\n", SessionData->AuthenticationPackage.Buffer);
    if (SessionData->AuthenticationPackage.Buffer != NULL)
        SessionData->AuthenticationPackage.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->AuthenticationPackage.Buffer);

    TRACE("Sid: %p\n", SessionData->Sid);
    if (SessionData->Sid != NULL)
        SessionData->Sid = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->Sid);

    TRACE("LogonServer: %p\n", SessionData->LogonServer.Buffer);
    if (SessionData->LogonServer.Buffer != NULL)
        SessionData->LogonServer.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->LogonServer.Buffer);

    TRACE("DnsDomainName: %p\n", SessionData->DnsDomainName.Buffer);
    if (SessionData->DnsDomainName.Buffer != NULL)
        SessionData->DnsDomainName.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->DnsDomainName.Buffer);

    TRACE("Upn: %p\n", SessionData->Upn.Buffer);
    if (SessionData->Upn.Buffer != NULL)
        SessionData->Upn.Buffer = (LPWSTR)((ULONG_PTR)SessionData + (ULONG_PTR)SessionData->Upn.Buffer);

    *ppLogonSessionData = SessionData;

    return Status;
}
예제 #24
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_replica_open -- (internal) open a memory pool replica
 */
static int
util_replica_open(struct pool_set *set, unsigned repidx, int flags,
	size_t hdrsize)
{
	LOG(3, "set %p repidx %u flags %d hdrsize %zu\n",
		set, repidx, flags, hdrsize);

	struct pool_replica *rep = set->replica[repidx];

	rep->repsize -= (rep->nparts - 1) * hdrsize;

	/* determine a hint address for mmap() */
	void *addr = util_map_hint(rep->repsize, 0);
	if (addr == NULL) {
		ERR("cannot find a contiguous region of given size");
		return -1;
	}

	/* map the first part and reserve space for remaining parts */
	if (util_map_part(&rep->part[0], addr, rep->repsize, 0, flags) != 0) {
		LOG(2, "pool mapping failed - part #0");
		return -1;
	}

	VALGRIND_REGISTER_PMEM_MAPPING(rep->part[0].addr, rep->part[0].size);
	VALGRIND_REGISTER_PMEM_FILE(rep->part[0].fd,
				rep->part[0].addr, rep->part[0].size, 0);

	/* map all headers - don't care about the address */
	for (unsigned p = 0; p < rep->nparts; p++) {
		if (util_map_hdr(&rep->part[p], hdrsize, flags) != 0) {
			LOG(2, "header mapping failed - part #%d", p);
			goto err;
		}
	}

	size_t mapsize = rep->part[0].filesize & ~(Pagesize - 1);
	addr = (char *)rep->part[0].addr + mapsize;

	/*
	 * map the remaining parts of the usable pool space
	 * (4K-aligned)
	 */
	for (unsigned p = 1; p < rep->nparts; p++) {
		/* map data part */
		if (util_map_part(&rep->part[p], addr, 0, hdrsize,
				flags | MAP_FIXED) != 0) {
			LOG(2, "usable space mapping failed - part #%d", p);
			goto err;
		}

		VALGRIND_REGISTER_PMEM_FILE(rep->part[p].fd,
			rep->part[p].addr, rep->part[p].size, hdrsize);

		mapsize += rep->part[p].size;
		addr = (char *)addr + rep->part[p].size;
	}

	rep->is_pmem = pmem_is_pmem(rep->part[0].addr, rep->part[0].size);

	ASSERTeq(mapsize, rep->repsize);

	/* calculate pool size - choose the smallest replica size */
	if (rep->repsize < set->poolsize)
		set->poolsize = rep->repsize;

	LOG(3, "replica addr %p", rep->part[0].addr);

	return 0;
err:
	LOG(4, "error clean up");
	int oerrno = errno;
	for (unsigned p = 0; p < rep->nparts; p++)
		util_unmap_hdr(&rep->part[p]);
	util_unmap_part(&rep->part[0]);
	errno = oerrno;
	return -1;
}
예제 #25
0
int
main()
{
   int ncid, pres_varid, temp_varid;
   int lat_varid, lon_varid;

   /* We will read surface temperature and pressure fields. */
   float pres_in[NLAT][NLON];
   float temp_in[NLAT][NLON];

   /* For the lat lon coordinate variables. */
   float lats_in[NLAT], lons_in[NLON];

   /* To check the units attributes. */
   char pres_units_in[MAX_ATT_LEN], temp_units_in[MAX_ATT_LEN];
   char lat_units_in[MAX_ATT_LEN], lon_units_in[MAX_ATT_LEN];

   /* We will learn about the data file and store results in these
      program variables. */
   int ndims_in, nvars_in, ngatts_in, unlimdimid_in;

   /* Loop indexes. */
   int lat, lon;

   /* Error handling. */
   int retval;

   /* Open the file. */
   if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
      ERR(retval);

   /* There are a number of inquiry functions in netCDF which can be
      used to learn about an unknown netCDF file. NC_INQ tells how
      many netCDF variables, dimensions, and global attributes are in
      the file; also the dimension id of the unlimited dimension, if
      there is one. */
   if ((retval = nc_inq(ncid, &ndims_in, &nvars_in, &ngatts_in, 
			&unlimdimid_in)))
      ERR(retval);

   /* In this case we know that there are 2 netCDF dimensions, 4
      netCDF variables, no global attributes, and no unlimited
      dimension. */
   if (ndims_in != 2 || nvars_in != 4 || ngatts_in != 0 || 
       unlimdimid_in != -1) return 2;

   /* Get the varids of the latitude and longitude coordinate
    * variables. */
   if ((retval = nc_inq_varid(ncid, LAT_NAME, &lat_varid)))
      ERR(retval);
   if ((retval = nc_inq_varid(ncid, LON_NAME, &lon_varid)))
      ERR(retval);

   /* Read the coordinate variable data. */
   if ((retval = nc_get_var_float(ncid, lat_varid, &lats_in[0])))
      ERR(retval);
   if ((retval = nc_get_var_float(ncid, lon_varid, &lons_in[0])))
      ERR(retval);

   /* Check the coordinate variable data. */
   for (lat = 0; lat < NLAT; lat++)
      if (lats_in[lat] != START_LAT + 5.*lat)
	 return 2;
   for (lon = 0; lon < NLON; lon++)
      if (lons_in[lon] != START_LON + 5.*lon)
	 return 2;

   /* Get the varids of the pressure and temperature netCDF
    * variables. */
   if ((retval = nc_inq_varid(ncid, PRES_NAME, &pres_varid)))
      ERR(retval);
   if ((retval = nc_inq_varid(ncid, TEMP_NAME, &temp_varid)))
      ERR(retval);

   /* Read the data. Since we know the contents of the file we know
    * that the data arrays in this program are the correct size to
    * hold all the data. */
   if ((retval = nc_get_var_float(ncid, pres_varid, &pres_in[0][0])))
      ERR(retval);
   if ((retval = nc_get_var_float(ncid, temp_varid, &temp_in[0][0])))
      ERR(retval);

   /* Check the data. */
   for (lat = 0; lat < NLAT; lat++)
      for (lon = 0; lon < NLON; lon++)
	 if (pres_in[lat][lon] != SAMPLE_PRESSURE + (lon * NLAT + lat) ||
	     temp_in[lat][lon] != SAMPLE_TEMP + .25 * (lon * NLAT + lat))
	    return 2;

   /* Each of the netCDF variables has a "units" attribute. Let's read
      them and check them. */
   if ((retval = nc_get_att_text(ncid, lat_varid, UNITS, lat_units_in)))
      ERR(retval);
   if (strncmp(lat_units_in, LAT_UNITS, strlen(LAT_UNITS))) 
      return 2;

   if ((retval = nc_get_att_text(ncid, lon_varid, UNITS, lon_units_in)))
      ERR(retval);
   if (strncmp(lon_units_in, LON_UNITS, strlen(LON_UNITS))) 
      return 2;

   if ((retval = nc_get_att_text(ncid, pres_varid, UNITS, pres_units_in)))
      ERR(retval);
   if (strncmp(pres_units_in, PRES_UNITS, strlen(PRES_UNITS)))
      return 2;

   if ((retval = nc_get_att_text(ncid, temp_varid, UNITS, temp_units_in)))
      ERR(retval);
   if (strncmp(temp_units_in, TEMP_UNITS, strlen(TEMP_UNITS))) return 2;

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      ERR(retval);

   printf("*** SUCCESS reading example file sfc_pres_temp.nc!\n");
   return 0;
}
예제 #26
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_pool_open -- open a memory pool (set or a single file)
 *
 * This routine does all the work, but takes a rdonly flag so internal
 * calls can map a read-only pool if required.
 */
int
util_pool_open(struct pool_set **setp, const char *path, int rdonly,
	size_t minsize, size_t hdrsize, const char *sig,
	uint32_t major, uint32_t compat, uint32_t incompat, uint32_t ro_compat)
{
	LOG(3, "setp %p path %s rdonly %d minsize %zu "
		"hdrsize %zu sig %.8s major %u "
		"compat %#x incompat %#x ro_comapt %#x",
		setp, path, rdonly, minsize, hdrsize,
		sig, major, compat, incompat, ro_compat);

	int flags = rdonly ? MAP_PRIVATE|MAP_NORESERVE : MAP_SHARED;

	int ret = util_poolset_open(setp, path, minsize);
	if (ret < 0) {
		LOG(2, "cannot open pool set");
		return -1;
	}

	struct pool_set *set = *setp;

	ASSERT(set->nreplicas > 0);

	set->rdonly = 0;
	set->poolsize = SIZE_MAX;

	for (unsigned r = 0; r < set->nreplicas; r++) {
		if (util_replica_open(set, r, flags, hdrsize) != 0) {
			LOG(2, "replica open failed");
			goto err;
		}
	}

	/* check headers, check UUID's, check replicas linkage */
	for (unsigned r = 0; r < set->nreplicas; r++) {
		struct pool_replica *rep = set->replica[r];
		for (unsigned p = 0; p < rep->nparts; p++) {
			if (util_header_check(set, r, p,  sig, major,
					compat, incompat, ro_compat) != 0) {
				LOG(2, "header check failed - part #%d", p);
				goto err;
			}

			set->rdonly |= rep->part[p].rdonly;
		}

		if (memcmp(HDR(REP(set, r - 1), 0)->uuid,
					HDR(REP(set, r), 0)->prev_repl_uuid,
					POOL_HDR_UUID_LEN) ||
		    memcmp(HDR(REP(set, r + 1), 0)->uuid,
					HDR(REP(set, r), 0)->next_repl_uuid,
					POOL_HDR_UUID_LEN)) {
			ERR("wrong replica UUID");
			errno = EINVAL;
			goto err;
		}
	}

	/* unmap all headers */
	for (unsigned r = 0; r < set->nreplicas; r++) {
		struct pool_replica *rep = set->replica[r];
		for (unsigned p = 0; p < rep->nparts; p++)
			util_unmap_hdr(&rep->part[p]);
	}

	return 0;

err:
	LOG(4, "error clean up");
	int oerrno = errno;
	for (unsigned r = 0; r < set->nreplicas; r++)
		util_replica_close(set, r);

	util_poolset_close(set, 0);
	errno = oerrno;
	return -1;
}
예제 #27
0
VOID
CFileDefExt::InitOpensWithField(HWND hwndDlg)
{
    WCHAR wszBuf[MAX_PATH] = L"";
    WCHAR wszPath[MAX_PATH] = L"";
    DWORD dwSize = sizeof(wszBuf);
    BOOL bUnknownApp = TRUE;
    LPCWSTR pwszExt = PathFindExtensionW(m_wszPath);

    if (RegGetValueW(HKEY_CLASSES_ROOT, pwszExt, L"", RRF_RT_REG_SZ, NULL, wszBuf, &dwSize) == ERROR_SUCCESS)
    {
        bUnknownApp = FALSE;
        StringCbCatW(wszBuf, sizeof(wszBuf), L"\\shell\\open\\command");
        dwSize = sizeof(wszPath);
        if (RegGetValueW(HKEY_CLASSES_ROOT, wszBuf, L"", RRF_RT_REG_SZ, NULL, wszPath, &dwSize) == ERROR_SUCCESS)
        {
            /* Get path from command line */
            ExpandEnvironmentStringsW(wszPath, wszBuf, _countof(wszBuf));
            PathRemoveArgs(wszBuf);
            PathUnquoteSpacesW(wszBuf);
            PathSearchAndQualify(wszBuf, wszPath, _countof(wszPath));

            HICON hIcon;
            if (ExtractIconExW(wszPath, 0, NULL, &hIcon, 1))
            {
                HWND hIconCtrl = GetDlgItem(hwndDlg, 14025);
                HWND hDescrCtrl = GetDlgItem(hwndDlg, 14007);
                ShowWindow(hIconCtrl, SW_SHOW);
                RECT rcIcon, rcDescr;
                GetWindowRect(hIconCtrl, &rcIcon);
                if (rcIcon.left == rcIcon.right)
                    ERR("Icon control has invalid width: %d-%d\n", rcIcon.left, rcIcon.right);
                MapWindowPoints(NULL, hwndDlg, (LPPOINT)&rcIcon, 2);
                GetWindowRect(hDescrCtrl, &rcDescr);
                MapWindowPoints(NULL, hwndDlg, (LPPOINT)&rcDescr, 2);
                INT cxOffset = rcIcon.right + 2 - rcDescr.left;
                SetWindowPos(hDescrCtrl, NULL,
                             rcDescr.left + cxOffset, rcDescr.top,
                             rcDescr.right - rcDescr.left - cxOffset, rcDescr.bottom - rcDescr.top,
                             SWP_NOZORDER);
                SendMessageW(hIconCtrl, STM_SETICON, (WPARAM)hIcon, 0);
            } else
                ERR("Failed to extract icon\n");

            if (PathFileExistsW(wszPath))
            {
                /* Get file description */
                CFileVersionInfo VerInfo;
                VerInfo.Load(wszPath);
                LPCWSTR pwszDescr = VerInfo.GetString(L"FileDescription");
                if (pwszDescr)
                    SetDlgItemTextW(hwndDlg, 14007, pwszDescr);
                else
                {
                    /* File has no description - display filename */
                    LPWSTR pwszFilename = PathFindFileNameW(wszPath);
                    PathRemoveExtension(pwszFilename);
                    pwszFilename[0] = towupper(pwszFilename[0]);
                    SetDlgItemTextW(hwndDlg, 14007, pwszFilename);
                }
            }
            else
                bUnknownApp = TRUE;
        } else
            WARN("RegGetValueW %ls failed\n", wszBuf);
    } else
        WARN("RegGetValueW %ls failed\n", pwszExt);

    if (bUnknownApp)
    {
        /* Unknown application */
        LoadStringW(shell32_hInstance, IDS_UNKNOWN_APP, wszBuf, _countof(wszBuf));
        SetDlgItemTextW(hwndDlg, 14007, wszBuf);
    }
}
예제 #28
0
파일: set.c 프로젝트: andreas-bluemle/nvml
/*
 * util_poolset_parse -- (internal) parse pool set config file
 *
 * Returns 1 if the file is a valid pool set config file, 0 if the file
 * is not a pool set header, and -1 in case of any error.
 *
 * XXX: use memory mapped file
 */
int
util_poolset_parse(const char *path, int fd, struct pool_set **setp)
{
	LOG(3, "path %s fd %d setp %p", path, fd, setp);

	struct pool_set *set;
	enum parser_codes result;
	char line[PARSER_MAX_LINE];
	char *s;
	char *ppath;
	char *cp;
	size_t psize;
	FILE *fs;

	if (lseek(fd, 0, SEEK_SET) != 0) {
		ERR("!lseek %d", fd);
		return -1;
	}

	fd = dup(fd);
	if (fd < 0) {
		ERR("!dup");
		return -1;
	}

	/* associate a stream with the file descriptor */
	if ((fs = fdopen(fd, "r")) == NULL) {
		ERR("!fdopen %d", fd);
		close(fd);
		return -1;
	}

	unsigned nlines = 0;
	unsigned nparts = 0; /* number of parts in current replica */

	/* read the first line */
	s = fgets(line, PARSER_MAX_LINE, fs);
	nlines++;

	set = Malloc(sizeof (struct pool_set));
	if (set == NULL) {
		ERR("!Malloc for pool set");
		goto err;
	}
	memset(set, 0, sizeof (struct pool_set));

	/* check also if the last character is '\n' */
	if (s && strncmp(line, POOLSET_HDR_SIG, POOLSET_HDR_SIG_LEN) == 0 &&
	    line[POOLSET_HDR_SIG_LEN] == '\n') {
		/* 'PMEMPOOLSET' signature detected */
		LOG(10, "PMEMPOOLSET");

		int ret = util_parse_add_replica(&set);
		if (ret != 0)
			goto err;

		nparts = 0;
		result = PARSER_CONTINUE;
	} else {
		result = PARSER_PMEMPOOLSET;
	}

	while (result == PARSER_CONTINUE) {
		/* read next line */
		s = fgets(line, PARSER_MAX_LINE, fs);
		nlines++;

		if (s) {
			/* chop off newline and comments */
			if ((cp = strchr(line, '\n')) != NULL)
				*cp = '\0';
			if (cp != s && (cp = strchr(line, '#')) != NULL)
				*cp = '\0';

			/* skip comments and blank lines */
			if (cp == s)
				continue;
		}

		if (!s) {
			if (nparts >= 1) {
				result = PARSER_FORMAT_OK;
			} else {
				if (set->nreplicas == 1)
					result = PARSER_SET_NO_PARTS;
				else
					result = PARSER_REP_NO_PARTS;
			}
		} else if (strncmp(line, POOLSET_REPLICA_SIG,
					POOLSET_REPLICA_SIG_LEN) == 0) {
			if (line[POOLSET_REPLICA_SIG_LEN] != '\0') {
				/* something more than 'REPLICA' */
				result = PARSER_REPLICA;
			} else if (nparts >= 1) {
				/* 'REPLICA' signature detected */
				LOG(10, "REPLICA");

				int ret = util_parse_add_replica(&set);
				if (ret != 0)
					goto err;

				nparts = 0;
				result = PARSER_CONTINUE;
			} else {
				if (set->nreplicas == 1)
					result = PARSER_SET_NO_PARTS;
				else
					result = PARSER_REP_NO_PARTS;
			}
		} else {
			/* read size and path */
			result = parser_read_line(line, &psize, &ppath);
			if (result == PARSER_CONTINUE) {
				/* add a new pool's part to the list */
				int ret = util_parse_add_part(set,
					ppath, psize);
				if (ret != 0)
					goto err;
				nparts++;
			}
		}
	}

	if (result == PARSER_FORMAT_OK) {
		LOG(4, "set file format correct (%s)", path);
		(void) fclose(fs);
		*setp = set;
		return 0;
	} else {
		ERR("%s [%s:%d]", path, parser_errstr[result], nlines);
	}

err:
	(void) fclose(fs);
	if (set)
		util_poolset_free(set);
	return -1;
}
예제 #29
0
BOOL
CFileDefExt::CountFolderAndFiles(HWND hwndDlg, LPWSTR pwszBuf, UINT cchBufMax, DWORD *ticks)
{
    /* Find filename position */
    UINT cchBuf = wcslen(pwszBuf);
    WCHAR *pwszFilename = pwszBuf + cchBuf;
    size_t cchFilenameMax = cchBufMax - cchBuf;
    if (!cchFilenameMax)
        return FALSE;
    *(pwszFilename++) = '\\';
    --cchFilenameMax;

    /* Find all files, FIXME: shouldn't be "*"? */
    StringCchCopyW(pwszFilename, cchFilenameMax, L"*");

    WIN32_FIND_DATAW wfd;
    HANDLE hFind = FindFirstFileW(pwszBuf, &wfd);
    if (hFind == INVALID_HANDLE_VALUE)
    {
        ERR("FindFirstFileW %ls failed\n", pwszBuf);
        return FALSE;
    }

    BOOL root = FALSE;
    if (*ticks == 0) {
        *ticks = GetTickCount();
        root = TRUE;
    }

    do
    {
        if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
            /* Don't process "." and ".." items */
            if (!wcscmp(wfd.cFileName, L".") || !wcscmp(wfd.cFileName, L".."))
                continue;

            ++m_cFolders;

            StringCchCopyW(pwszFilename, cchFilenameMax, wfd.cFileName);
            CountFolderAndFiles(hwndDlg, pwszBuf, cchBufMax, ticks);
        }
        else
        {
            m_cFiles++;

            ULARGE_INTEGER FileSize;
            FileSize.u.LowPart  = wfd.nFileSizeLow;
            FileSize.u.HighPart = wfd.nFileSizeHigh;
            m_DirSize.QuadPart += FileSize.QuadPart;
        }
        if (GetTickCount() - *ticks > (DWORD) 300)
        {
            /* FIXME Using IsWindow is generally ill advised */
            if (IsWindow(hwndDlg))
            {
                WCHAR wszBuf[MAX_PATH];

                if (SH_FormatFileSizeWithBytes(&m_DirSize, wszBuf, _countof(wszBuf)))
                    SetDlgItemTextW(hwndDlg, 14011, wszBuf);

                /* Display files and folders count */
                WCHAR wszFormat[256];
                LoadStringW(shell32_hInstance, IDS_FILE_FOLDER, wszFormat, _countof(wszFormat));
                StringCchPrintfW(wszBuf, _countof(wszBuf), wszFormat, m_cFiles, m_cFolders);
                SetDlgItemTextW(hwndDlg, 14027, wszBuf);
                *ticks = GetTickCount();
            }
            else
                break;
        }
    } while(FindNextFileW(hFind, &wfd));

    if (root && IsWindow(hwndDlg))
    {
        WCHAR wszBuf[MAX_PATH];

        if (SH_FormatFileSizeWithBytes(&m_DirSize, wszBuf, _countof(wszBuf)))
            SetDlgItemTextW(hwndDlg, 14011, wszBuf);

        /* Display files and folders count */
        WCHAR wszFormat[256];
        LoadStringW(shell32_hInstance, IDS_FILE_FOLDER, wszFormat, _countof(wszFormat));
        StringCchPrintfW(wszBuf, _countof(wszBuf), wszFormat, m_cFiles, m_cFolders);
        SetDlgItemTextW(hwndDlg, 14027, wszBuf);
    }

    FindClose(hFind);
    return TRUE;
}
예제 #30
0
static HRESULT DoReset(ALCdevice *device)
{
    MMDevApiData *data = device->ExtraData;
    WAVEFORMATEXTENSIBLE OutputType;
    WAVEFORMATEX *wfx = NULL;
    REFERENCE_TIME min_per, buf_time;
    UINT32 buffer_len, min_len;
    HRESULT hr;

    hr = IAudioClient_GetMixFormat(data->client, &wfx);
    if(FAILED(hr))
    {
        ERR("Failed to get mix format: 0x%08lx\n", hr);
        return hr;
    }

    if(!MakeExtensible(&OutputType, wfx))
    {
        CoTaskMemFree(wfx);
        return E_FAIL;
    }
    CoTaskMemFree(wfx);
    wfx = NULL;

    buf_time = ((REFERENCE_TIME)device->UpdateSize*device->NumUpdates*10000000 +
                                device->Frequency-1) / device->Frequency;

    if(!(device->Flags&DEVICE_FREQUENCY_REQUEST))
        device->Frequency = OutputType.Format.nSamplesPerSec;
    if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
    {
        if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
            device->FmtChans = DevFmtMono;
        else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
            device->FmtChans = DevFmtStereo;
        else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
            device->FmtChans = DevFmtQuad;
        else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
            device->FmtChans = DevFmtX51;
        else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1SIDE)
            device->FmtChans = DevFmtX51Side;
        else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
            device->FmtChans = DevFmtX61;
        else if(OutputType.Format.nChannels == 8 && OutputType.dwChannelMask == X7DOT1)
            device->FmtChans = DevFmtX71;
        else
            ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
    }

    switch(device->FmtChans)
    {
        case DevFmtMono:
            OutputType.Format.nChannels = 1;
            OutputType.dwChannelMask = MONO;
            break;
        case DevFmtStereo:
            OutputType.Format.nChannels = 2;
            OutputType.dwChannelMask = STEREO;
            break;
        case DevFmtQuad:
            OutputType.Format.nChannels = 4;
            OutputType.dwChannelMask = QUAD;
            break;
        case DevFmtX51:
            OutputType.Format.nChannels = 6;
            OutputType.dwChannelMask = X5DOT1;
            break;
        case DevFmtX51Side:
            OutputType.Format.nChannels = 6;
            OutputType.dwChannelMask = X5DOT1SIDE;
            break;
        case DevFmtX61:
            OutputType.Format.nChannels = 7;
            OutputType.dwChannelMask = X6DOT1;
            break;
        case DevFmtX71:
            OutputType.Format.nChannels = 8;
            OutputType.dwChannelMask = X7DOT1;
            break;
    }
    switch(device->FmtType)
    {
        case DevFmtByte:
            device->FmtType = DevFmtUByte;
            /* fall-through */
        case DevFmtUByte:
            OutputType.Format.wBitsPerSample = 8;
            OutputType.Samples.wValidBitsPerSample = 8;
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
            break;
        case DevFmtUShort:
            device->FmtType = DevFmtShort;
            /* fall-through */
        case DevFmtShort:
            OutputType.Format.wBitsPerSample = 16;
            OutputType.Samples.wValidBitsPerSample = 16;
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
            break;
        case DevFmtUInt:
            device->FmtType = DevFmtInt;
            /* fall-through */
        case DevFmtInt:
            OutputType.Format.wBitsPerSample = 32;
            OutputType.Samples.wValidBitsPerSample = 32;
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
            break;
        case DevFmtFloat:
            OutputType.Format.wBitsPerSample = 32;
            OutputType.Samples.wValidBitsPerSample = 32;
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
            break;
    }
    OutputType.Format.nSamplesPerSec = device->Frequency;

    OutputType.Format.nBlockAlign = OutputType.Format.nChannels *
                                    OutputType.Format.wBitsPerSample / 8;
    OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
                                        OutputType.Format.nBlockAlign;

    hr = IAudioClient_IsFormatSupported(data->client, AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
    if(FAILED(hr))
    {
        ERR("Failed to check format support: 0x%08lx\n", hr);
        hr = IAudioClient_GetMixFormat(data->client, &wfx);
    }
    if(FAILED(hr))
    {
        ERR("Failed to find a supported format: 0x%08lx\n", hr);
        return hr;
    }

    if(wfx != NULL)
    {
        if(!MakeExtensible(&OutputType, wfx))
        {
            CoTaskMemFree(wfx);
            return E_FAIL;
        }
        CoTaskMemFree(wfx);
        wfx = NULL;

        device->Frequency = OutputType.Format.nSamplesPerSec;
        if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
            device->FmtChans = DevFmtMono;
        else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
            device->FmtChans = DevFmtStereo;
        else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
            device->FmtChans = DevFmtQuad;
        else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
            device->FmtChans = DevFmtX51;
        else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1SIDE)
            device->FmtChans = DevFmtX51Side;
        else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
            device->FmtChans = DevFmtX61;
        else if(OutputType.Format.nChannels == 8 && OutputType.dwChannelMask == X7DOT1)
            device->FmtChans = DevFmtX71;
        else
        {
            ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
            device->FmtChans = DevFmtStereo;
            OutputType.Format.nChannels = 2;
            OutputType.dwChannelMask = STEREO;
        }

        if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_PCM))
        {
            if(OutputType.Format.wBitsPerSample == 8)
                device->FmtType = DevFmtUByte;
            else if(OutputType.Format.wBitsPerSample == 16)
                device->FmtType = DevFmtShort;
            else if(OutputType.Format.wBitsPerSample == 32)
                device->FmtType = DevFmtInt;
            else
            {
                device->FmtType = DevFmtShort;
                OutputType.Format.wBitsPerSample = 16;
            }
        }
        else if(IsEqualGUID(&OutputType.SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
        {
            device->FmtType = DevFmtFloat;
            OutputType.Format.wBitsPerSample = 32;
        }
        else
        {
            ERR("Unhandled format sub-type\n");
            device->FmtType = DevFmtShort;
            OutputType.Format.wBitsPerSample = 16;
            OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
        }
        OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
    }

    SetDefaultWFXChannelOrder(device);

    hr = IAudioClient_Initialize(data->client, AUDCLNT_SHAREMODE_SHARED,
                                 AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
                                 buf_time, 0, &OutputType.Format, NULL);
    if(FAILED(hr))
    {
        ERR("Failed to initialize audio client: 0x%08lx\n", hr);
        return hr;
    }

    hr = IAudioClient_GetDevicePeriod(data->client, &min_per, NULL);
    if(SUCCEEDED(hr))
    {
        min_len = (UINT32)((min_per*device->Frequency + 10000000-1) / 10000000);
        /* Find the nearest multiple of the period size to the update size */
        if(min_len < device->UpdateSize)
            min_len *= (device->UpdateSize + min_len/2)/min_len;
        hr = IAudioClient_GetBufferSize(data->client, &buffer_len);
    }
    if(FAILED(hr))
    {
        ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
        return hr;
    }

    device->UpdateSize = min_len;
    device->NumUpdates = buffer_len / device->UpdateSize;
    if(device->NumUpdates <= 1)
    {
        ERR("Audio client returned buffer_len < period*2; expect break up\n");
        device->NumUpdates = 2;
        device->UpdateSize = buffer_len / device->NumUpdates;
    }

    return hr;
}