Example #1
0
PSP_DEVICE_INTERFACE_DETAIL_DATA
get_device_ancestors(HDEVINFO hDevInfo, DWORD index, PyObject *candidates, BOOL *iterate, BOOL ddebug) {
    SP_DEVICE_INTERFACE_DATA            interfaceData;
    SP_DEVINFO_DATA						devInfoData;
    BOOL                                status;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    interfaceDetailData;
    DWORD                               interfaceDetailDataSize,
                                        reqSize;
    DEVINST                             parent, pos;
    wchar_t                             temp[BUFSIZE];
    int                                 i;
    PyObject                            *devid;

    interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);
    devInfoData.cbSize   = sizeof (SP_DEVINFO_DATA);

    status = SetupDiEnumDeviceInterfaces (
                hDevInfo,               // Interface Device Info handle
                NULL,                   // Device Info data
                (LPGUID)&GUID_DEVINTERFACE_VOLUME, // Interface registered by driver
                index,                  // Member
                &interfaceData          // Device Interface Data
                );
    if ( status == FALSE ) {
        *iterate = FALSE;
        return NULL;
    }
    SetupDiGetDeviceInterfaceDetail (
                hDevInfo,           // Interface Device info handle
                &interfaceData,     // Interface data for the event class
                NULL,               // Checking for buffer size
                0,                  // Checking for buffer size
                &reqSize,           // Buffer size required to get the detail data
                NULL                // Checking for buffer size
    );

    interfaceDetailDataSize = reqSize;
    interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)PyMem_Malloc(interfaceDetailDataSize+50);
    if ( interfaceDetailData == NULL ) {
        PyErr_NoMemory();
        return NULL;
    }
    interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    status = SetupDiGetDeviceInterfaceDetail (
                  hDevInfo,                 // Interface Device info handle
                  &interfaceData,           // Interface data for the event class
                  interfaceDetailData,      // Interface detail data
                  interfaceDetailDataSize,  // Interface detail data size
                  &reqSize,                 // Buffer size required to get the detail data
                  &devInfoData);            // Interface device info
    if (ddebug) printf("Getting ancestors\n"); fflush(stdout);

    if ( status == FALSE ) {PyErr_SetFromWindowsErr(0); PyMem_Free(interfaceDetailData); return NULL;}

    pos = devInfoData.DevInst;

    for(i = 0; i < 10; i++) {
        // Get the device instance of parent.
        if (CM_Get_Parent(&parent, pos, 0) != CR_SUCCESS) break;
        if (CM_Get_Device_ID(parent, temp, BUFSIZE, 0) == CR_SUCCESS) {
            if (ddebug) console_out(L"device id: %s\n", temp);
            devid = PyUnicode_FromWideChar(temp, wcslen(temp));
            if (devid) {
                PyList_Append(candidates, devid);
                Py_DECREF(devid);
            }
        }
        pos = parent;
    }

    return interfaceDetailData;
}
Example #2
0
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObjects(
    PyObject *exc,
    int ierr,
    PyObject *filenameObject,
    PyObject *filenameObject2)
{
    int len;
    WCHAR *s_buf = NULL; /* Free via LocalFree */
    PyObject *message;
    PyObject *args, *v;
    DWORD err = (DWORD)ierr;
    if (err==0) err = GetLastError();
    len = FormatMessageW(
        /* Error API error */
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,           /* no message source */
        err,
        MAKELANGID(LANG_NEUTRAL,
        SUBLANG_DEFAULT), /* Default language */
        (LPWSTR) &s_buf,
        0,              /* size not used */
        NULL);          /* no args */
    if (len==0) {
        /* Only seen this in out of mem situations */
        message = PyUnicode_FromFormat("Windows Error 0x%x", err);
        s_buf = NULL;
    } else {
        /* remove trailing cr/lf and dots */
        while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
            s_buf[--len] = L'\0';
        message = PyUnicode_FromWideChar(s_buf, len);
    }

    if (message == NULL)
    {
        LocalFree(s_buf);
        return NULL;
    }

    if (filenameObject == NULL) {
        assert(filenameObject2 == NULL);
        filenameObject = filenameObject2 = Py_None;
    }
    else if (filenameObject2 == NULL)
        filenameObject2 = Py_None;
    /* This is the constructor signature for OSError.
       The POSIX translation will be figured out by the constructor. */
    args = Py_BuildValue("(iOOiO)", 0, message, filenameObject, err, filenameObject2);
    Py_DECREF(message);

    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            PyErr_SetObject((PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
    }
    LocalFree(s_buf);
    return NULL;
}
Example #3
0
JSOBJ Object_newString(wchar_t *start, wchar_t *end)
{
    return PyUnicode_FromWideChar (start, (end - start));
}
Example #4
0
/*
 * returns a Python list representing the arguments for the process
 * with given pid or NULL on error.
 */
PyObject*
psutil_get_arg_list(long pid)
{
    int nArgs, i;
    LPWSTR *szArglist = NULL;
    HANDLE hProcess = NULL;
    PVOID pebAddress;
    PVOID rtlUserProcParamsAddress;
    UNICODE_STRING commandLine;
    WCHAR *commandLineContents = NULL;
    PyObject *arg = NULL;
    PyObject *arg_from_wchar = NULL;
    PyObject *argList = NULL;

    hProcess = psutil_handle_from_pid(pid);
    if(hProcess == NULL) {
        return NULL;
    }

    pebAddress = psutil_get_peb_address(hProcess);

    /* get the address of ProcessParameters */
#ifdef _WIN64
    if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 32,
        &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#else
    if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 0x10,
        &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#endif
    {
        ////printf("Could not read the address of ProcessParameters!\n");
        PyErr_SetFromWindowsErr(0);
        goto error;
    }

    /* read the CommandLine UNICODE_STRING structure */
#ifdef _WIN64
    if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 112,
        &commandLine, sizeof(commandLine), NULL))
#else
    if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40,
        &commandLine, sizeof(commandLine), NULL))
#endif
    {
        ////printf("Could not read CommandLine!\n");
        PyErr_SetFromWindowsErr(0);
        goto error;
    }


    /* allocate memory to hold the command line */
    commandLineContents = (WCHAR *)malloc(commandLine.Length+1);
    if (commandLineContents == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    /* read the command line */
    if (!ReadProcessMemory(hProcess, commandLine.Buffer,
        commandLineContents, commandLine.Length, NULL))
    {
        ////printf("Could not read the command line string!\n");
        PyErr_SetFromWindowsErr(0);
        goto error;
    }

    /* print the commandline */
    ////printf("%.*S\n", commandLine.Length / 2, commandLineContents);

    // null-terminate the string to prevent wcslen from returning incorrect length
    // the length specifier is in characters, but commandLine.Length is in bytes
    commandLineContents[(commandLine.Length/sizeof(WCHAR))] = '\0';

    // attemempt tp parse the command line using Win32 API, fall back on string
    // cmdline version otherwise
    szArglist = CommandLineToArgvW(commandLineContents, &nArgs);
    if (NULL == szArglist) {
        // failed to parse arglist
        // encode as a UTF8 Python string object from WCHAR string
        arg_from_wchar = PyUnicode_FromWideChar(commandLineContents,
                                                commandLine.Length / 2);
        if (arg_from_wchar == NULL)
            goto error;
        #if PY_MAJOR_VERSION >= 3
            argList = Py_BuildValue("N", PyUnicode_AsUTF8String(arg_from_wchar));
        #else
            argList = Py_BuildValue("N", PyUnicode_FromObject(arg_from_wchar));
        #endif
        if (!argList)
            goto error;
    }
    else {
        // arglist parsed as array of UNICODE_STRING, so convert each to Python
        // string object and add to arg list
        argList = Py_BuildValue("[]");
        if (argList == NULL)
            goto error;
        for(i=0; i<nArgs; i++) {
            arg_from_wchar = NULL;
            arg = NULL;
            ////printf("%d: %.*S (%d characters)\n", i, wcslen(szArglist[i]),
            //                  szArglist[i], wcslen(szArglist[i]));
            arg_from_wchar = PyUnicode_FromWideChar(szArglist[i],
                                                    wcslen(szArglist[i])
                                                    );
            if (arg_from_wchar == NULL)
                goto error;
            #if PY_MAJOR_VERSION >= 3
                arg = PyUnicode_FromObject(arg_from_wchar);
            #else
                arg = PyUnicode_AsUTF8String(arg_from_wchar);
            #endif
            if (arg == NULL)
                goto error;
            Py_XDECREF(arg_from_wchar);
            if (PyList_Append(argList, arg))
                goto error;
            Py_XDECREF(arg);
        }
    }

    if (szArglist != NULL)
        LocalFree(szArglist);
    free(commandLineContents);
    CloseHandle(hProcess);
    return argList;

error:
    Py_XDECREF(arg);
    Py_XDECREF(arg_from_wchar);
    Py_XDECREF(argList);
    if (hProcess != NULL)
        CloseHandle(hProcess);
    if (commandLineContents != NULL)
        free(commandLineContents);
    if (szArglist != NULL)
        LocalFree(szArglist);
    return NULL;
}
Example #5
0
PyObject *
PyErr_SetFromErrnoWithFilenameObjects(PyObject *exc, PyObject *filenameObject, PyObject *filenameObject2)
{
    PyObject *message;
    PyObject *v, *args;
    int i = errno;
#ifdef MS_WINDOWS
    WCHAR *s_buf = NULL;
#endif /* Unix/Windows */

#ifdef EINTR
    if (i == EINTR && PyErr_CheckSignals())
        return NULL;
#endif

#ifndef MS_WINDOWS
    if (i != 0) {
        char *s = strerror(i);
        message = PyUnicode_DecodeLocale(s, "surrogateescape");
    }
    else {
        /* Sometimes errno didn't get set */
        message = PyUnicode_FromString("Error");
    }
#else
    if (i == 0)
        message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */
    else
    {
        /* Note that the Win32 errors do not lineup with the
           errno error.  So if the error is in the MSVC error
           table, we use it, otherwise we assume it really _is_
           a Win32 error code
        */
        if (i > 0 && i < _sys_nerr) {
            message = PyUnicode_FromString(_sys_errlist[i]);
        }
        else {
            int len = FormatMessageW(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,                   /* no message source */
                i,
                MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_DEFAULT),
                           /* Default language */
                (LPWSTR) &s_buf,
                0,                      /* size not used */
                NULL);                  /* no args */
            if (len==0) {
                /* Only ever seen this in out-of-mem
                   situations */
                s_buf = NULL;
                message = PyUnicode_FromFormat("Windows Error 0x%x", i);
            } else {
                /* remove trailing cr/lf and dots */
                while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.'))
                    s_buf[--len] = L'\0';
                message = PyUnicode_FromWideChar(s_buf, len);
            }
        }
    }
#endif /* Unix/Windows */

    if (message == NULL)
    {
#ifdef MS_WINDOWS
        LocalFree(s_buf);
#endif
        return NULL;
    }

    if (filenameObject != NULL) {
        if (filenameObject2 != NULL)
            args = Py_BuildValue("(iOOiO)", i, message, filenameObject, 0, filenameObject2);
        else
            args = Py_BuildValue("(iOO)", i, message, filenameObject);
    } else {
        assert(filenameObject2 == NULL);
        args = Py_BuildValue("(iO)", i, message);
    }
    Py_DECREF(message);

    if (args != NULL) {
        v = PyObject_Call(exc, args, NULL);
        Py_DECREF(args);
        if (v != NULL) {
            PyErr_SetObject((PyObject *) Py_TYPE(v), v);
            Py_DECREF(v);
        }
    }
#ifdef MS_WINDOWS
    LocalFree(s_buf);
#endif
    return NULL;
}
static PyObject *
py_get_clipboard_data(PyObject* self, PyObject* args)
{

  PyObject *ret;

  // @pyparm int|format|CF_TEXT|Specifies a clipboard format. For a description of
  // the standard clipboard formats, see Standard Clipboard Formats.
  // In Unicode builds (ie, python 3k), the default is CF_UNICODETEXT.
#ifdef UNICODE
  int format = CF_UNICODETEXT;
#else
  int format = CF_TEXT;
#endif
  if (!PyArg_ParseTuple(args, "|i:GetClipboardData:",
                        &format)) {
    return NULL;
  }

  if (!IsClipboardFormatAvailable(format)){
      PyErr_SetString(PyExc_TypeError, "Specified clipboard format is not available");
      return NULL;
  }
  HANDLE handle;
  WCHAR *filename=NULL;
  PyObject* obfilename = NULL;
  UINT filecnt=0, fileind=0, filenamesize=0;
  HDROP hdrop;
  Py_BEGIN_ALLOW_THREADS;
  handle = GetClipboardData((UINT)format);
  Py_END_ALLOW_THREADS;


  if (!handle) {
    return ReturnAPIError("GetClipboardData");
  }

  void * cData = NULL;
  size_t size;
  DWORD dwordsize;
  switch (format) {
    case CF_BITMAP:
      break;
    case CF_HDROP:
		hdrop = (HDROP)GlobalLock(handle);
        break;
    case CF_ENHMETAFILE:
      dwordsize = GetEnhMetaFileBits((HENHMETAFILE)handle, 0, NULL);
      if (!dwordsize)
        return ReturnAPIError("GetClipboardData:GetEnhMetafileBits(NULL)");
      // allocate a temporary buffer for enhanced metafile
      cData = malloc(dwordsize);
      if (cData == NULL)
        return ReturnAPIError("GetClipboardData:malloc");
      // copy enhanced metafile into the temporary buffer
      if (0 == GetEnhMetaFileBits((HENHMETAFILE)handle, dwordsize, (LPBYTE)cData)) {
        free(cData);
        return ReturnAPIError("GetClipboardData:GetEnhMetafileBits");
      }
	  size=dwordsize;
      break;
    case CF_METAFILEPICT:
      // @todo CF_METAFILEPICT format returns a pointer to a METAFILEPICT struct which contains the metafile handle,
      //	rather than returning the handle directly.  This code currently fails with
      //	error: (6, 'GetClipboardData:GetMetafileBitsEx(NULL)', 'The handle is invalid.')
      dwordsize = GetMetaFileBitsEx((HMETAFILE)handle, 0, NULL);
      if (!dwordsize)
        return ReturnAPIError("GetClipboardData:GetMetafileBitsEx(NULL)");
      // allocate a temporary buffer for metafile
      cData = malloc(dwordsize);
      if (cData == NULL)
        return ReturnAPIError("GetClipboardData:malloc");
      // copy metafile into the temporary buffer
      if (0 == GetMetaFileBitsEx((HMETAFILE)handle, dwordsize, cData)) {
        free(cData);
        return ReturnAPIError("GetClipboardData:GetMetafileBitsEx");
      }
	  size=dwordsize;
      break;
    // All other formats simply return the data as a blob.
    default:
      cData = GlobalLock(handle);
      if (!cData) {
        GlobalUnlock(handle);
        return ReturnAPIError("GetClipboardData:GlobalLock");
      }
      size  = GlobalSize(cData);
      if (!size) {
        GlobalUnlock(handle);
        return ReturnAPIError("GetClipboardData:GlobalSize");
      }
      break;
  }
  switch (format) {
    case CF_BITMAP:
        ret = PyWinLong_FromHANDLE(handle);
        break;
    case CF_HDROP:
        filecnt = DragQueryFileW(hdrop, 0xFFFFFFFF, NULL, NULL);
        ret = PyTuple_New(filecnt);
        if (!ret) return PyErr_NoMemory();
        for (fileind=0;fileind<filecnt;fileind++){
            filenamesize = DragQueryFileW(hdrop, fileind, NULL, NULL);
            filename = (WCHAR *)malloc((filenamesize+1)*sizeof(WCHAR));
            if (!filename) {
                Py_DECREF(ret);
                return PyErr_NoMemory();
            }
            filenamesize = DragQueryFileW(hdrop, fileind, filename, filenamesize+1);
            obfilename=PyWinObject_FromWCHAR(filename);
            PyTuple_SetItem(ret,fileind,obfilename);
            free (filename);
        }
        GlobalUnlock(handle);
        break;
    case CF_UNICODETEXT:
      ret = PyUnicode_FromWideChar((wchar_t *)cData, (size / sizeof(wchar_t))-1);
      GlobalUnlock(handle);
      break;
    // For the text formats, strip the null!
    case CF_TEXT:
    case CF_OEMTEXT:
      ret = PyString_FromStringAndSize((char *)cData, size-1);
      GlobalUnlock(handle);
      break;
    default:
      assert(cData);
      if (!cData) {
          ret = Py_None;
          Py_INCREF(ret);
      } else
        ret = PyString_FromStringAndSize((char *)cData, size);
      GlobalUnlock(handle);
      break;
  }
  return ret;

  // @comm An application can enumerate the available formats in advance by
  // using the EnumClipboardFormats function.<nl>
  // The clipboard controls the handle that the GetClipboardData function
  // returns, not the application. The application should copy the data
  // immediately. The application cannot rely on being able to make long-term
  // use of the handle. The application must not free the handle nor leave it
  // locked.<nl>
  // The system performs implicit data format conversions between certain
  // clipboard formats when an application calls the GetClipboardData function.
  // For example, if the CF_OEMTEXT format is on the clipboard, a window can
  // retrieve data in the CF_TEXT format. The format on the clipboard is
  // converted to the requested format on demand. For more information, see
  // Synthesized Clipboard Formats. 

  // @pyseeapi GetClipboardData
  // @pyseeapi Standard Clipboard Formats

  // @rdesc If the function fails, the standard win32api.error exception 
  // is raised.  If the function succeeds, the return value is as 
  // described in the following table:
  // @flagh Format|Result type
  // @flag CF_HDROP|A tuple of Unicode filenames.
  // @flag CF_UNICODETEXT|A unicode object.
  // @flag CF_OEMTEXT|A string object.
  // @flag CF_TEXT|A string object.
  // @flag CF_ENHMETAFILE|A string with binary data obtained from GetEnhMetaFileBits
  // @flag CF_METAFILEPICT|A string with binary data obtained from GetMetaFileBitsEx (currently broken)
  // @flag CF_BITMAP|An integer handle to the bitmap.
  // @flag All other formats|A string with binary data obtained directly from the 
  // global memory referenced by the handle.
}
Example #7
0
/*
 * returns a Python list representing the arguments for the process
 * with given pid or NULL on error.
 */
PyObject *
psutil_get_cmdline(long pid) {
    int nArgs, i;
    LPWSTR *szArglist = NULL;
    HANDLE hProcess = NULL;
    PVOID pebAddress;
    PVOID rtlUserProcParamsAddress;
    UNICODE_STRING commandLine;
    WCHAR *commandLineContents = NULL;
    PyObject *py_unicode = NULL;
    PyObject *py_retlist = NULL;

    hProcess = psutil_handle_from_pid(pid);
    if (hProcess == NULL)
        return NULL;
    pebAddress = psutil_get_peb_address(hProcess);

    // get the address of ProcessParameters
#ifdef _WIN64
    if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 32,
                           &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#else
    if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 0x10,
                           &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
#endif
    {
        ////printf("Could not read the address of ProcessParameters!\n");
        PyErr_SetFromWindowsErr(0);
        goto error;
    }

    // read the CommandLine UNICODE_STRING structure
#ifdef _WIN64
    if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 112,
                           &commandLine, sizeof(commandLine), NULL))
#else
    if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40,
                           &commandLine, sizeof(commandLine), NULL))
#endif
    {
        PyErr_SetFromWindowsErr(0);
        goto error;
    }


    // allocate memory to hold the command line
    commandLineContents = (WCHAR *)malloc(commandLine.Length + 1);
    if (commandLineContents == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    // read the command line
    if (!ReadProcessMemory(hProcess, commandLine.Buffer,
                           commandLineContents, commandLine.Length, NULL))
    {
        PyErr_SetFromWindowsErr(0);
        goto error;
    }

    // Null-terminate the string to prevent wcslen from returning
    // incorrect length the length specifier is in characters, but
    // commandLine.Length is in bytes.
    commandLineContents[(commandLine.Length / sizeof(WCHAR))] = '\0';

    // attempt to parse the command line using Win32 API, fall back
    // on string cmdline version otherwise
    szArglist = CommandLineToArgvW(commandLineContents, &nArgs);
    if (szArglist == NULL) {
        PyErr_SetFromWindowsErr(0);
        goto error;
    }
    else {
        // arglist parsed as array of UNICODE_STRING, so convert each to
        // Python string object and add to arg list
        py_retlist = Py_BuildValue("[]");
        if (py_retlist == NULL)
            goto error;
        for (i = 0; i < nArgs; i++) {
            py_unicode = PyUnicode_FromWideChar(
                szArglist[i], wcslen(szArglist[i]));
            if (py_unicode == NULL)
                goto error;
            if (PyList_Append(py_retlist, py_unicode))
                goto error;
            Py_XDECREF(py_unicode);
        }
    }

    if (szArglist != NULL)
        LocalFree(szArglist);
    free(commandLineContents);
    CloseHandle(hProcess);
    return py_retlist;

error:
    Py_XDECREF(py_unicode);
    Py_XDECREF(py_retlist);
    if (hProcess != NULL)
        CloseHandle(hProcess);
    if (commandLineContents != NULL)
        free(commandLineContents);
    if (szArglist != NULL)
        LocalFree(szArglist);
    return NULL;
}
Example #8
0
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const time_char *fmt;
#ifdef HAVE_WCSFTIME
    wchar_t *format;
#else
    PyObject *format;
#endif
    PyObject *format_arg;
    size_t fmtlen, buflen;
    time_char *outbuf = NULL;
    size_t i;
    PyObject *ret = NULL;

    memset((void *) &buf, '\0', sizeof(buf));

    /* Will always expect a unicode string to be passed as format.
       Given that there's no str type anymore in py3k this seems safe.
    */
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        if (pylocaltime(&tt, &buf) == -1)
            return NULL;
    }
    else if (!gettmarg(tup, &buf) || !checktm(&buf))
        return NULL;

#if defined(_MSC_VER) || defined(sun) || defined(_AIX)
    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
        PyErr_SetString(PyExc_ValueError,
                        "strftime() requires year in [1; 9999]");
        return NULL;
    }
#endif

    /* Normalize tm_isdst just in case someone foolishly implements %Z
       based on the assumption that tm_isdst falls within the range of
       [-1, 1] */
    if (buf.tm_isdst < -1)
        buf.tm_isdst = -1;
    else if (buf.tm_isdst > 1)
        buf.tm_isdst = 1;

#ifdef HAVE_WCSFTIME
    format = PyUnicode_AsWideCharString(format_arg, NULL);
    if (format == NULL)
        return NULL;
    fmt = format;
#else
    /* Convert the unicode string to an ascii one */
    format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
    if (format == NULL)
        return NULL;
    fmt = PyBytes_AS_STRING(format);
#endif

#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
    /* check that the format string contains only valid directives */
    for(outbuf = strchr(fmt, '%');
        outbuf != NULL;
        outbuf = strchr(outbuf+2, '%'))
    {
        if (outbuf[1]=='#')
            ++outbuf; /* not documented by python, */
        if (outbuf[1]=='\0' ||
            !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
        {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            Py_DECREF(format);
            return NULL;
        }
    }
#endif

    fmtlen = time_strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        int err;
#endif
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
        if (outbuf == NULL) {
            PyErr_NoMemory();
            break;
        }
        buflen = format_time(outbuf, i, fmt, &buf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        err = errno;
#endif
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
#ifdef HAVE_WCSFTIME
            ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
            ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen,
                                                "surrogateescape");
#endif
            PyMem_Free(outbuf);
            break;
        }
        PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && err == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            break;
        }
#endif
    }
#ifdef HAVE_WCSFTIME
    PyMem_Free(format);
#else
    Py_DECREF(format);
#endif
    return ret;
}
PYTHON_METHOD_DEFINITION_NOARGS(ptVaultTextNoteNode, getTextW)
{
    std::wstring retVal = self->fThis->Note_GetTextW();
    return PyUnicode_FromWideChar(retVal.c_str(), retVal.length());
}
Example #10
0
/* Encode a (wide) character string to the locale encoding with the
   surrogateescape error handler (characters in range U+DC80..U+DCFF are
   converted to bytes 0x80..0xFF).

   This function is the reverse of _Py_char2wchar().

   Return a pointer to a newly allocated byte string (use PyMem_Free() to free
   the memory), or NULL on encoding or memory allocation error.

   If error_pos is not NULL: *error_pos is the index of the invalid character
   on encoding error, or (size_t)-1 otherwise. */
char*
_Py_wchar2char(const wchar_t *text, size_t *error_pos)
{
#ifdef __APPLE__
    Py_ssize_t len;
    PyObject *unicode, *bytes = NULL;
    char *cpath;

    unicode = PyUnicode_FromWideChar(text, wcslen(text));
    if (unicode == NULL)
        return NULL;

    bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape");
    Py_DECREF(unicode);
    if (bytes == NULL) {
        PyErr_Clear();
        if (error_pos != NULL)
            *error_pos = (size_t)-1;
        return NULL;
    }

    len = PyBytes_GET_SIZE(bytes);
    cpath = PyMem_Malloc(len+1);
    if (cpath == NULL) {
        PyErr_Clear();
        Py_DECREF(bytes);
        if (error_pos != NULL)
            *error_pos = (size_t)-1;
        return NULL;
    }
    memcpy(cpath, PyBytes_AsString(bytes), len + 1);
    Py_DECREF(bytes);
    return cpath;
#else   /* __APPLE__ */
    const size_t len = wcslen(text);
    char *result = NULL, *bytes = NULL;
    size_t i, size, converted;
    wchar_t c, buf[2];

#ifndef MS_WINDOWS
    if (force_ascii == -1)
        force_ascii = check_force_ascii();

    if (force_ascii)
        return encode_ascii_surrogateescape(text, error_pos);
#endif

    /* The function works in two steps:
       1. compute the length of the output buffer in bytes (size)
       2. outputs the bytes */
    size = 0;
    buf[1] = 0;
    while (1) {
        for (i=0; i < len; i++) {
            c = text[i];
            if (c >= 0xdc80 && c <= 0xdcff) {
                /* UTF-8b surrogate */
                if (bytes != NULL) {
                    *bytes++ = c - 0xdc00;
                    size--;
                }
                else
                    size++;
                continue;
            }
            else {
                buf[0] = c;
                if (bytes != NULL)
                    converted = wcstombs(bytes, buf, size);
                else
                    converted = wcstombs(NULL, buf, 0);
                if (converted == (size_t)-1) {
                    if (result != NULL)
                        PyMem_Free(result);
                    if (error_pos != NULL)
                        *error_pos = i;
                    return NULL;
                }
                if (bytes != NULL) {
                    bytes += converted;
                    size -= converted;
                }
                else
                    size += converted;
            }
        }
        if (result != NULL) {
            *bytes = '\0';
            break;
        }

        size += 1; /* nul byte at the end */
        result = PyMem_Malloc(size);
        if (result == NULL) {
            if (error_pos != NULL)
                *error_pos = (size_t)-1;
            return NULL;
        }
        bytes = result;
    }
    return result;
#endif   /* __APPLE__ */
}
Example #11
0
static PyObject *
u_get(void *ptr, Py_ssize_t size)
{
    return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
}
Example #12
0
//-------------------------------------------------------------------------------------
PyObject* ClientApp::__py_listPathRes(PyObject* self, PyObject* args)
{
	int argCount = PyTuple_Size(args);
	if (argCount < 1 || argCount > 2)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
		PyErr_PrintEx(0);
		S_Return;
	}

	std::wstring wExtendName = L"*";
	PyObject* pathobj = NULL;
	PyObject* path_argsobj = NULL;

	if (argCount == 1)
	{
		if (PyArg_ParseTuple(args, "O", &pathobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
			PyErr_PrintEx(0);
			S_Return;
		}
	}
	else
	{
		if (PyArg_ParseTuple(args, "O|O", &pathobj, &path_argsobj) == -1)
		{
			PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
			PyErr_PrintEx(0);
			S_Return;
		}

		if (PyUnicode_Check(path_argsobj))
		{
			wchar_t* fargs = NULL;
			fargs = PyUnicode_AsWideCharString(path_argsobj, NULL);
			wExtendName = fargs;
			PyMem_Free(fargs);
		}
		else
		{
			if (PySequence_Check(path_argsobj))
			{
				wExtendName = L"";
				Py_ssize_t size = PySequence_Size(path_argsobj);
				for (int i = 0; i<size; ++i)
				{
					PyObject* pyobj = PySequence_GetItem(path_argsobj, i);
					if (!PyUnicode_Check(pyobj))
					{
						PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path, pathargs=\'*.*\'] is error!");
						PyErr_PrintEx(0);
						S_Return;
					}

					wchar_t* wtemp = NULL;
					wtemp = PyUnicode_AsWideCharString(pyobj, NULL);
					wExtendName += wtemp;
					wExtendName += L"|";
					PyMem_Free(wtemp);
				}
			}
			else
			{
				PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is error!");
				PyErr_PrintEx(0);
				S_Return;
			}
		}
	}

	if (!PyUnicode_Check(pathobj))
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is error!");
		PyErr_PrintEx(0);
		S_Return;
	}

	if (PyUnicode_GET_LENGTH(pathobj) == 0)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!");
		PyErr_PrintEx(0);
		S_Return;
	}

	if (wExtendName.size() == 0)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[pathargs] is NULL!");
		PyErr_PrintEx(0);
		S_Return;
	}

	if (wExtendName[0] == '.')
		wExtendName.erase(wExtendName.begin());

	if (wExtendName.size() == 0)
		wExtendName = L"*";

	wchar_t* respath = PyUnicode_AsWideCharString(pathobj, NULL);
	if (respath == NULL)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::listPathRes(): args[path] is NULL!");
		PyErr_PrintEx(0);
		S_Return;
	}

	char* cpath = strutil::wchar2char(respath);
	std::string foundPath = Resmgr::getSingleton().matchPath(cpath);
	free(cpath);
	PyMem_Free(respath);

	respath = strutil::char2wchar(foundPath.c_str());

	std::vector<std::wstring> results;
	Resmgr::getSingleton().listPathRes(respath, wExtendName, results);
	PyObject* pyresults = PyTuple_New(results.size());

	std::vector<std::wstring>::iterator iter = results.begin();
	int i = 0;

	for (; iter != results.end(); ++iter)
	{
		PyTuple_SET_ITEM(pyresults, i++, PyUnicode_FromWideChar((*iter).c_str(), (*iter).size()));
	}

	free(respath);
	return pyresults;
}
Example #13
0
static char *GetPythonImport (HINSTANCE hModule)
{
    unsigned char *dllbase, *import_data, *import_name;
    DWORD pe_offset, opt_offset;
    WORD opt_magic;
    int num_dict_off, import_off;

    /* Safety check input */
    if (hModule == NULL) {
        return NULL;
    }

    /* Module instance is also the base load address.  First portion of
       memory is the MS-DOS loader, which holds the offset to the PE
       header (from the load base) at 0x3C */
    dllbase = (unsigned char *)hModule;
    pe_offset = DWORD_AT(dllbase + 0x3C);

    /* The PE signature must be "PE\0\0" */
    if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
        return NULL;
    }

    /* Following the PE signature is the standard COFF header (20
       bytes) and then the optional header.  The optional header starts
       with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
       uses 64-bits for some fields).  It might also be 0x107 for a ROM
       image, but we don't process that here.

       The optional header ends with a data dictionary that directly
       points to certain types of data, among them the import entries
       (in the second table entry). Based on the header type, we
       determine offsets for the data dictionary count and the entry
       within the dictionary pointing to the imports. */

    opt_offset = pe_offset + 4 + 20;
    opt_magic = WORD_AT(dllbase+opt_offset);
    if (opt_magic == 0x10B) {
        /* PE32 */
        num_dict_off = 92;
        import_off   = 104;
    } else if (opt_magic == 0x20B) {
        /* PE32+ */
        num_dict_off = 108;
        import_off   = 120;
    } else {
        /* Unsupported */
        return NULL;
    }

    /* Now if an import table exists, offset to it and walk the list of
       imports.  The import table is an array (ending when an entry has
       empty values) of structures (20 bytes each), which contains (at
       offset 12) a relative address (to the module base) at which a
       string constant holding the import name is located. */

    if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
        /* We have at least 2 tables - the import table is the second
           one.  But still it may be that the table size is zero */
        if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
            return NULL;
        import_data = dllbase + DWORD_AT(dllbase +
                                         opt_offset +
                                         import_off);
        while (DWORD_AT(import_data)) {
            import_name = dllbase + DWORD_AT(import_data+12);
            if (strlen(import_name) >= 6 &&
                !strncmp(import_name,"python",6)) {
                char *pch;

#ifndef _DEBUG
                /* In a release version, don't claim that python3.dll is
                   a Python DLL. */
                if (strcmp(import_name, "python3.dll") == 0) {
                    import_data += 20;
                    continue;
                }
#endif

                /* Ensure python prefix is followed only
                   by numbers to the end of the basename */
                pch = import_name + 6;
#ifdef _DEBUG
                while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
#else
                while (*pch && *pch != '.') {
#endif
                    if (*pch >= '0' && *pch <= '9') {
                        pch++;
                    } else {
                        pch = NULL;
                        break;
                    }
                }

                if (pch) {
                    /* Found it - return the name */
                    return import_name;
                }
            }
            import_data += 20;
        }
    }

    return NULL;
}

dl_funcptr _PyImport_GetDynLoadWindows(const char *shortname,
                                       PyObject *pathname, FILE *fp)
{
    dl_funcptr p;
    char funcname[258], *import_python;
    wchar_t *wpathname;

#ifndef _DEBUG
    _Py_CheckPython3();
#endif

    wpathname = PyUnicode_AsUnicode(pathname);
    if (wpathname == NULL)
        return NULL;

    PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);

    {
        HINSTANCE hDLL = NULL;
        unsigned int old_mode;
#if HAVE_SXS
        ULONG_PTR cookie = 0;
#endif

        /* Don't display a message box when Python can't load a DLL */
        old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);

#if HAVE_SXS
        cookie = _Py_ActivateActCtx();
#endif
        /* We use LoadLibraryEx so Windows looks for dependent DLLs
            in directory of pathname first. */
        /* XXX This call doesn't exist in Windows CE */
        hDLL = LoadLibraryExW(wpathname, NULL,
                              LOAD_WITH_ALTERED_SEARCH_PATH);
#if HAVE_SXS
        _Py_DeactivateActCtx(cookie);
#endif

        /* restore old error mode settings */
        SetErrorMode(old_mode);

        if (hDLL==NULL){
            PyObject *message;
            unsigned int errorCode;

            /* Get an error string from Win32 error code */
            wchar_t theInfo[256]; /* Pointer to error text
                                  from system */
            int theLength; /* Length of error text */

            errorCode = GetLastError();

            theLength = FormatMessageW(
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
                NULL, /* message source */
                errorCode, /* the message (error) ID */
                MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_DEFAULT),
                           /* Default language */
                theInfo, /* the buffer */
                sizeof(theInfo), /* the buffer size */
                NULL); /* no additional format args. */

            /* Problem: could not get the error message.
               This should not happen if called correctly. */
            if (theLength == 0) {
                message = PyUnicode_FromFormat(
                    "DLL load failed with error code %d",
                    errorCode);
            } else {
                /* For some reason a \r\n
                   is appended to the text */
                if (theLength >= 2 &&
                    theInfo[theLength-2] == '\r' &&
                    theInfo[theLength-1] == '\n') {
                    theLength -= 2;
                    theInfo[theLength] = '\0';
                }
                message = PyUnicode_FromString(
                    "DLL load failed: ");

                PyUnicode_AppendAndDel(&message,
                    PyUnicode_FromWideChar(
                        theInfo,
                        theLength));
            }
            if (message != NULL) {
                PyErr_SetImportError(message, PyUnicode_FromString(shortname),
                                     pathname);
                Py_DECREF(message);
            }
            return NULL;
        } else {
            char buffer[256];

            PyOS_snprintf(buffer, sizeof(buffer),
#ifdef _DEBUG
                          "python%d%d_d.dll",
#else
                          "python%d%d.dll",
#endif
                          PY_MAJOR_VERSION,PY_MINOR_VERSION);
            import_python = GetPythonImport(hDLL);

            if (import_python &&
                strcasecmp(buffer,import_python)) {
                PyErr_Format(PyExc_ImportError,
                             "Module use of %.150s conflicts "
                             "with this version of Python.",
                             import_python);
                FreeLibrary(hDLL);
                return NULL;
            }
        }
        p = GetProcAddress(hDLL, funcname);
    }

    return p;
}
Example #14
0
/* Compute argv[0] which will be prepended to sys.argv */
PyObject*
_PyPathConfig_ComputeArgv0(int argc, wchar_t **argv)
{
    wchar_t *argv0;
    wchar_t *p = NULL;
    Py_ssize_t n = 0;
    int have_script_arg = 0;
    int have_module_arg = 0;
#ifdef HAVE_READLINK
    wchar_t link[MAXPATHLEN+1];
    wchar_t argv0copy[2*MAXPATHLEN+1];
    int nr = 0;
#endif
#if defined(HAVE_REALPATH)
    wchar_t fullpath[MAXPATHLEN];
#elif defined(MS_WINDOWS)
    wchar_t fullpath[MAX_PATH];
#endif

    argv0 = argv[0];
    if (argc > 0 && argv0 != NULL) {
        have_module_arg = (wcscmp(argv0, L"-m") == 0);
        have_script_arg = !have_module_arg && (wcscmp(argv0, L"-c") != 0);
    }

    if (have_module_arg) {
        #if defined(HAVE_REALPATH) || defined(MS_WINDOWS)
            _Py_wgetcwd(fullpath, Py_ARRAY_LENGTH(fullpath));
            argv0 = fullpath;
            n = wcslen(argv0);
        #else
            argv0 = L".";
            n = 1;
        #endif
    }

#ifdef HAVE_READLINK
    if (have_script_arg)
        nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
    if (nr > 0) {
        /* It's a symlink */
        link[nr] = '\0';
        if (link[0] == SEP)
            argv0 = link; /* Link to absolute path */
        else if (wcschr(link, SEP) == NULL)
            ; /* Link without path */
        else {
            /* Must join(dirname(argv0), link) */
            wchar_t *q = wcsrchr(argv0, SEP);
            if (q == NULL)
                argv0 = link; /* argv0 without path */
            else {
                /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
                wcsncpy(argv0copy, argv0, MAXPATHLEN);
                q = wcsrchr(argv0copy, SEP);
                wcsncpy(q+1, link, MAXPATHLEN);
                q[MAXPATHLEN + 1] = L'\0';
                argv0 = argv0copy;
            }
        }
    }
#endif /* HAVE_READLINK */

#if SEP == '\\'
    /* Special case for Microsoft filename syntax */
    if (have_script_arg) {
        wchar_t *q;
#if defined(MS_WINDOWS)
        /* Replace the first element in argv with the full path. */
        wchar_t *ptemp;
        if (GetFullPathNameW(argv0,
                           Py_ARRAY_LENGTH(fullpath),
                           fullpath,
                           &ptemp)) {
            argv0 = fullpath;
        }
#endif
        p = wcsrchr(argv0, SEP);
        /* Test for alternate separator */
        q = wcsrchr(p ? p : argv0, '/');
        if (q != NULL)
            p = q;
        if (p != NULL) {
            n = p + 1 - argv0;
            if (n > 1 && p[-1] != ':')
                n--; /* Drop trailing separator */
        }
    }
#else /* All other filename syntaxes */
    if (have_script_arg) {
#if defined(HAVE_REALPATH)
        if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
            argv0 = fullpath;
        }
#endif
        p = wcsrchr(argv0, SEP);
    }
    if (p != NULL) {
        n = p + 1 - argv0;
#if SEP == '/' /* Special case for Unix filename syntax */
        if (n > 1)
            n--; /* Drop trailing separator */
#endif /* Unix */
    }
#endif /* All others */

    return PyUnicode_FromWideChar(argv0, n);
}
Example #15
0
static PyObject *
winutil_get_removable_drives(PyObject *self, PyObject *args) {
    HDEVINFO hDevInfo;
	BOOL  iterate = TRUE, ddebug = FALSE;
	PSP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData;
    DWORD i;
    unsigned int j;
    size_t length;
    WCHAR volume[BUFSIZE];
    struct tagDrives g_drives[MAX_DRIVES];
    PyObject *volumes, *key, *candidates, *pdebug = Py_False, *temp;

    if (!PyArg_ParseTuple(args, "|O", &pdebug)) {
    	return NULL;
    }

    // Find all removable drives
    for (j = 0; j < MAX_DRIVES; j++) g_drives[j].letter = 0;
    if (!get_all_removable_disks(g_drives)) return NULL;

    volumes = PyDict_New();
    if (volumes == NULL) return PyErr_NoMemory();
    ddebug = PyObject_IsTrue(pdebug);

    hDevInfo = create_device_info_set((LPGUID)&GUID_DEVINTERFACE_VOLUME,
                            NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
    if (hDevInfo == INVALID_HANDLE_VALUE) { Py_DECREF(volumes); return NULL; }

    // Enumerate through the set
    for (i=0; iterate; i++) {
        candidates = PyList_New(0);
        if (candidates == NULL) { Py_DECREF(volumes); return PyErr_NoMemory();}

        interfaceDetailData = get_device_ancestors(hDevInfo, i, candidates, &iterate, ddebug);
        if (interfaceDetailData == NULL) {
            PyErr_Print(); 
            Py_DECREF(candidates); candidates = NULL; 
            continue;
        }

        length = wcslen(interfaceDetailData->DevicePath);
        interfaceDetailData->DevicePath[length] = L'\\';
        interfaceDetailData->DevicePath[length+1] = 0;

        if (ddebug) console_out(L"Device path: %s\n", interfaceDetailData->DevicePath);
        // On Vista+ DevicePath contains the information we need.
        temp = PyUnicode_FromWideChar(interfaceDetailData->DevicePath, length);
        if (temp == NULL) return PyErr_NoMemory();
        PyList_Append(candidates, temp);
        Py_DECREF(temp);
        if(GetVolumeNameForVolumeMountPointW(interfaceDetailData->DevicePath, volume, BUFSIZE)) {
            if (ddebug) console_out(L"Volume: %s\n", volume);
            
            for(j = 0; j < MAX_DRIVES; j++) {
                if(g_drives[j].letter != 0 && wcscmp(g_drives[j].volume, volume)==0) {
                    if (ddebug) printf("Found drive: %c\n", (char)g_drives[j].letter); fflush(stdout);
                    key = PyBytes_FromFormat("%c", (char)g_drives[j].letter);
                    if (key == NULL) return PyErr_NoMemory();
                    PyDict_SetItem(volumes, key, candidates);
                    Py_DECREF(key); key = NULL;
                    break;
                }
            }

        }
        Py_XDECREF(candidates); candidates = NULL;
        PyMem_Free(interfaceDetailData);
    } //for

    SetupDiDestroyDeviceInfoList(hDevInfo);
    return volumes;
}
PYTHON_METHOD_DEFINITION_NOARGS(ptGUIControlMultiLineEdit, getStringW)
{
    const wchar_t* text = self->fThis->GetTextW();
    return PyUnicode_FromWideChar(text, wcslen(text));
}
Example #17
0
static PyObject *
winutil_strftime(PyObject *self, PyObject *args)
{
	PyObject *tup = NULL;
	struct tm buf;
	const char *_fmt;
	size_t fmtlen, buflen;
	wchar_t *outbuf = NULL, *fmt = NULL;
	size_t i;
    memset((void *) &buf, '\0', sizeof(buf));

	if (!PyArg_ParseTuple(args, "s|O:strftime", &_fmt, &tup))
		return NULL;

    if (mbstowcs_s(&fmtlen, NULL, 0, _fmt, strlen(_fmt)) != 0) {
        PyErr_SetString(PyExc_ValueError, "Failed to convert fmt to wchar");
        return NULL;
    }
    fmt = (wchar_t *)PyMem_Malloc((fmtlen+2)*sizeof(wchar_t));
    if (fmt == NULL) return PyErr_NoMemory();
    if (mbstowcs_s(&fmtlen, fmt, fmtlen+2, _fmt, strlen(_fmt)) != 0) {
        PyErr_SetString(PyExc_ValueError, "Failed to convert fmt to wchar");
        goto end;
    }

	if (tup == NULL) {
		time_t tt = time(NULL);
		if(localtime_s(&buf, &tt) != 0) {
            PyErr_SetString(PyExc_ValueError, "Failed to get localtime()");
            goto end;
        }
	} else if (!gettmarg(tup, &buf))
	    goto end;

	if (buf.tm_mon == -1)
	    buf.tm_mon = 0;
	else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
            PyErr_SetString(PyExc_ValueError, "month out of range");
            goto end;
        }
	if (buf.tm_mday == 0)
	    buf.tm_mday = 1;
	else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
            PyErr_SetString(PyExc_ValueError, "day of month out of range");
            goto end;
        }
        if (buf.tm_hour < 0 || buf.tm_hour > 23) {
            PyErr_SetString(PyExc_ValueError, "hour out of range");
            goto end;
        }
        if (buf.tm_min < 0 || buf.tm_min > 59) {
            PyErr_SetString(PyExc_ValueError, "minute out of range");
            goto end;
        }
        if (buf.tm_sec < 0 || buf.tm_sec > 61) {
            PyErr_SetString(PyExc_ValueError, "seconds out of range");
            goto end;
        }
        /* tm_wday does not need checking of its upper-bound since taking
        ``% 7`` in gettmarg() automatically restricts the range. */
        if (buf.tm_wday < 0) {
            PyErr_SetString(PyExc_ValueError, "day of week out of range");
            goto end;
        }
	if (buf.tm_yday == -1)
	    buf.tm_yday = 0;
	else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
            PyErr_SetString(PyExc_ValueError, "day of year out of range");
            goto end;
        }
        if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
            PyErr_SetString(PyExc_ValueError,
                            "daylight savings flag out of range");
            goto end;
        }

	for (i = 5*fmtlen; ; i += i) {
		outbuf = (wchar_t *)PyMem_Malloc(i*sizeof(wchar_t));
		if (outbuf == NULL) {
			PyErr_NoMemory(); goto end;
		}
		buflen = wcsftime(outbuf, i, fmt, &buf);
		if (buflen > 0 || i >= 256 * fmtlen) {
			/* If the buffer is 256 times as long as the format,
			   it's probably not failing for lack of room!
			   More likely, the format yields an empty result,
			   e.g. an empty format, or %Z when the timezone
			   is unknown. */
			PyObject *ret;
			ret = PyUnicode_FromWideChar(outbuf, buflen);
			PyMem_Free(outbuf); PyMem_Free(fmt);
			return ret;
		}
		PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
		/* VisualStudio .NET 2005 does this properly */
		if (buflen == 0 && errno == EINVAL) {
			PyErr_SetString(PyExc_ValueError, "Invalid format string");
            goto end;
        }
#endif
    }
end:
    PyMem_Free(fmt); return NULL;
}
Example #18
0
File: type.c Project: zillow/ctds
static PyObject* translate_to_ucs2(PyObject* o)
{
    PyObject* translated = NULL;
    Py_ssize_t len;
    wchar_t* unicode;

    assert(PyUnicode_Check(o));
#if PY_MAJOR_VERSION < 3
    len = PyUnicode_GetSize(o);
    do
    {
        unicode = tds_mem_malloc((size_t)len * sizeof(wchar_t));
        if (!unicode)
        {
            PyErr_NoMemory();
            break;
        }
        if (-1 == PyUnicode_AsWideChar((PyUnicodeObject*)o, unicode, len))
        {
            break;
        }
    }
    while (0);
#else /* if PY_MAJOR_VERSION < 3 */
    unicode = PyUnicode_AsWideCharString(o, &len);
#endif /* else if PY_MAJOR_VERSION < 3 */

    if (!PyErr_Occurred())
    {
        Py_ssize_t ixsrc, ixdst = 0;
        for (ixsrc = 0; ixsrc < len; ++ixsrc, ++ixdst)
        {
#if defined(WCHAR_T_UCS4)
            if (0xFFFF < unicode[ixsrc])
#else /* if defined(WCHAR_T_UCS4) */
            if (Py_UNICODE_IS_SURROGATE(unicode[ixsrc]))
#endif /* else if defined(WCHAR_T_UCS4) */
            {
                static const char s_fmt[] =
                    "Unicode codepoint U+%08X is not representable in UCS-2; replaced with U+FFFD";
                char buffer[ARRAYSIZE(s_fmt) + 8 /* for codepoint chars */];
#if defined(WCHAR_T_UCS4)
                uint32_t codepoint = (uint32_t)unicode[ixsrc];
#else /* if defined(WCHAR_T_UCS4) */
                uint32_t codepoint;
                assert(((ixsrc + 1) < len) && Py_UNICODE_IS_SURROGATE(unicode[ixsrc + 1]));
                codepoint = Py_UNICODE_JOIN_SURROGATES(unicode[ixsrc], unicode[ixsrc + 1]);
                ++ixsrc;
#endif /* else if defined(WCHAR_T_UCS4) */
                (void)sprintf(buffer, s_fmt, codepoint);
                if (0 != PyErr_WarnEx(PyExc_UnicodeWarning, buffer, 1))
                {
                    break;
                }

                unicode[ixdst] = 0xFFFD; /* unicode replacement character */
            }
#if !defined(WCHAR_T_UCS4)
            else
            {
                unicode[ixdst] = unicode[ixsrc];
            }
#endif /* if !defined(WCHAR_T_UCS4) */
        }

        if (!PyErr_Occurred())
        {
            translated = PyUnicode_FromWideChar(unicode, ixdst);
        }
    }
#if PY_MAJOR_VERSION < 3
    tds_mem_free(unicode);
#else /* if PY_MAJOR_VERSION < 3 */
    PyMem_Free(unicode);
#endif /* else if PY_MAJOR_VERSION < 3 */

    return translated;
}