Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Modules/timemodule.c

    r2 r391  
    4747static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
    4848{
    49         SetEvent(hInterruptEvent);
    50         /* allow other default handlers to be called.
    51            Default Python handler will setup the
    52            KeyboardInterrupt exception.
    53         */
    54         return FALSE;
     49    SetEvent(hInterruptEvent);
     50    /* allow other default handlers to be called.
     51       Default Python handler will setup the
     52       KeyboardInterrupt exception.
     53    */
     54    return FALSE;
    5555}
    5656static long main_thread;
     
    9797
    9898/* For Y2K check */
    99 static PyObject *moddict;
     99static PyObject *moddict = NULL;
    100100
    101101/* Exposed in timefuncs.h. */
     
    103103_PyTime_DoubleToTimet(double x)
    104104{
    105         time_t result;
    106         double diff;
    107 
    108         result = (time_t)x;
    109         /* How much info did we lose?  time_t may be an integral or
    110         * floating type, and we don't know which.  If it's integral,
    111         * we don't know whether C truncates, rounds, returns the floor,
    112         * etc.  If we lost a second or more, the C rounding is
    113         * unreasonable, or the input just doesn't fit in a time_t;
    114         * call it an error regardless.  Note that the original cast to
    115         * time_t can cause a C error too, but nothing we can do to
    116         * worm around that.
    117         */
    118         diff = x - (double)result;
    119         if (diff <= -1.0 || diff >= 1.0) {
    120                 PyErr_SetString(PyExc_ValueError,
    121                                 "timestamp out of range for platform time_t");
    122                 result = (time_t)-1;
    123         }
    124         return result;
     105    time_t result;
     106    double diff;
     107
     108    result = (time_t)x;
     109    /* How much info did we lose?  time_t may be an integral or
     110    * floating type, and we don't know which.  If it's integral,
     111    * we don't know whether C truncates, rounds, returns the floor,
     112    * etc.  If we lost a second or more, the C rounding is
     113    * unreasonable, or the input just doesn't fit in a time_t;
     114    * call it an error regardless.  Note that the original cast to
     115    * time_t can cause a C error too, but nothing we can do to
     116    * worm around that.
     117    */
     118    diff = x - (double)result;
     119    if (diff <= -1.0 || diff >= 1.0) {
     120        PyErr_SetString(PyExc_ValueError,
     121                        "timestamp out of range for platform time_t");
     122        result = (time_t)-1;
     123    }
     124    return result;
    125125}
    126126
     
    128128time_time(PyObject *self, PyObject *unused)
    129129{
    130         double secs;
    131         secs = floattime();
    132         if (secs == 0.0) {
    133                 PyErr_SetFromErrno(PyExc_IOError);
    134                 return NULL;
    135         }
    136         return PyFloat_FromDouble(secs);
     130    double secs;
     131    secs = floattime();
     132    if (secs == 0.0) {
     133        PyErr_SetFromErrno(PyExc_IOError);
     134        return NULL;
     135    }
     136    return PyFloat_FromDouble(secs);
    137137}
    138138
     
    156156time_clock(PyObject *self, PyObject *unused)
    157157{
    158         return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
     158    return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
    159159}
    160160#endif /* HAVE_CLOCK */
     
    165165time_clock(PyObject *self, PyObject *unused)
    166166{
    167         static LARGE_INTEGER ctrStart;
    168         static double divisor = 0.0;
    169         LARGE_INTEGER now;
    170         double diff;
    171 
    172         if (divisor == 0.0) {
    173                 LARGE_INTEGER freq;
    174                 QueryPerformanceCounter(&ctrStart);
    175                 if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
    176                         /* Unlikely to happen - this works on all intel
    177                            machines at least!  Revert to clock() */
    178                         return PyFloat_FromDouble(((double)clock()) /
    179                                                   CLOCKS_PER_SEC);
    180                 }
    181                 divisor = (double)freq.QuadPart;
    182         }
    183         QueryPerformanceCounter(&now);
    184         diff = (double)(now.QuadPart - ctrStart.QuadPart);
    185         return PyFloat_FromDouble(diff / divisor);
     167    static LARGE_INTEGER ctrStart;
     168    static double divisor = 0.0;
     169    LARGE_INTEGER now;
     170    double diff;
     171
     172    if (divisor == 0.0) {
     173        LARGE_INTEGER freq;
     174        QueryPerformanceCounter(&ctrStart);
     175        if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
     176            /* Unlikely to happen - this works on all intel
     177               machines at least!  Revert to clock() */
     178            return PyFloat_FromDouble(((double)clock()) /
     179                                      CLOCKS_PER_SEC);
     180        }
     181        divisor = (double)freq.QuadPart;
     182    }
     183    QueryPerformanceCounter(&now);
     184    diff = (double)(now.QuadPart - ctrStart.QuadPart);
     185    return PyFloat_FromDouble(diff / divisor);
    186186}
    187187
     
    201201time_sleep(PyObject *self, PyObject *args)
    202202{
    203         double secs;
    204         if (!PyArg_ParseTuple(args, "d:sleep", &secs))
    205                 return NULL;
    206         if (floatsleep(secs) != 0)
    207                 return NULL;
    208         Py_INCREF(Py_None);
    209         return Py_None;
     203    double secs;
     204    if (!PyArg_ParseTuple(args, "d:sleep", &secs))
     205        return NULL;
     206    if (floatsleep(secs) != 0)
     207        return NULL;
     208    Py_INCREF(Py_None);
     209    return Py_None;
    210210}
    211211
     
    217217
    218218static PyStructSequence_Field struct_time_type_fields[] = {
    219         {"tm_year", NULL},
    220         {"tm_mon", NULL},
    221         {"tm_mday", NULL},
    222         {"tm_hour", NULL},
    223         {"tm_min", NULL},
    224         {"tm_sec", NULL},
    225         {"tm_wday", NULL},
    226         {"tm_yday", NULL},
    227         {"tm_isdst", NULL},
    228         {0}
     219    {"tm_year", "year, for example, 1993"},
     220    {"tm_mon", "month of year, range [1, 12]"},
     221    {"tm_mday", "day of month, range [1, 31]"},
     222    {"tm_hour", "hours, range [0, 23]"},
     223    {"tm_min", "minutes, range [0, 59]"},
     224    {"tm_sec", "seconds, range [0, 61])"},
     225    {"tm_wday", "day of week, range [0, 6], Monday is 0"},
     226    {"tm_yday", "day of year, range [1, 366]"},
     227    {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
     228    {0}
    229229};
    230230
    231231static PyStructSequence_Desc struct_time_type_desc = {
    232         "time.struct_time",
    233         NULL,
    234         struct_time_type_fields,
    235         9,
     232    "time.struct_time",
     233    "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
     234    " accepted by asctime(), mktime() and strftime().  May be considered as a\n"
     235    " sequence of 9 integers.\n\n"
     236    " Note that several fields' values are not the same as those defined by\n"
     237    " the C language standard for struct tm.  For example, the value of the\n"
     238    " field tm_year is the actual year, not year - 1900.  See individual\n"
     239    " fields' descriptions for details.",
     240    struct_time_type_fields,
     241    9,
    236242};
    237243
     
    242248tmtotuple(struct tm *p)
    243249{
    244         PyObject *v = PyStructSequence_New(&StructTimeType);
    245         if (v == NULL)
    246                 return NULL;
     250    PyObject *v = PyStructSequence_New(&StructTimeType);
     251    if (v == NULL)
     252        return NULL;
    247253
    248254#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
    249255
    250         SET(0, p->tm_year + 1900);
    251         SET(1, p->tm_mon + 1);     /* Want January == 1 */
    252         SET(2, p->tm_mday);
    253         SET(3, p->tm_hour);
    254         SET(4, p->tm_min);
    255         SET(5, p->tm_sec);
    256         SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
    257         SET(7, p->tm_yday + 1);    /* Want January, 1 == 1 */
    258         SET(8, p->tm_isdst);
     256    SET(0, p->tm_year + 1900);
     257    SET(1, p->tm_mon + 1);         /* Want January == 1 */
     258    SET(2, p->tm_mday);
     259    SET(3, p->tm_hour);
     260    SET(4, p->tm_min);
     261    SET(5, p->tm_sec);
     262    SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
     263    SET(7, p->tm_yday + 1);        /* Want January, 1 == 1 */
     264    SET(8, p->tm_isdst);
    259265#undef SET
    260         if (PyErr_Occurred()) {
    261                 Py_XDECREF(v);
    262                 return NULL;
    263         }
    264 
    265         return v;
     266    if (PyErr_Occurred()) {
     267        Py_XDECREF(v);
     268        return NULL;
     269    }
     270
     271    return v;
    266272}
    267273
     
    269275time_convert(double when, struct tm * (*function)(const time_t *))
    270276{
    271         struct tm *p;
    272         time_t whent = _PyTime_DoubleToTimet(when);
    273 
    274         if (whent == (time_t)-1 && PyErr_Occurred())
    275                 return NULL;
    276         errno = 0;
    277         p = function(&whent);
    278         if (p == NULL) {
     277    struct tm *p;
     278    time_t whent = _PyTime_DoubleToTimet(when);
     279
     280    if (whent == (time_t)-1 && PyErr_Occurred())
     281        return NULL;
     282    errno = 0;
     283    p = function(&whent);
     284    if (p == NULL) {
    279285#ifdef EINVAL
    280                 if (errno == 0)
    281                         errno = EINVAL;
    282 #endif
    283                 return PyErr_SetFromErrno(PyExc_ValueError);
    284         }
    285         return tmtotuple(p);
     286        if (errno == 0)
     287            errno = EINVAL;
     288#endif
     289        return PyErr_SetFromErrno(PyExc_ValueError);
     290    }
     291    return tmtotuple(p);
    286292}
    287293
     
    293299parse_time_double_args(PyObject *args, char *format, double *pwhen)
    294300{
    295         PyObject *ot = NULL;
    296 
    297         if (!PyArg_ParseTuple(args, format, &ot))
    298                 return 0;
    299         if (ot == NULL || ot == Py_None)
    300                 *pwhen = floattime();
    301         else {
    302                 double when = PyFloat_AsDouble(ot);
    303                 if (PyErr_Occurred())
    304                         return 0;
    305                 *pwhen = when;
    306         }
    307         return 1;
     301    PyObject *ot = NULL;
     302
     303    if (!PyArg_ParseTuple(args, format, &ot))
     304        return 0;
     305    if (ot == NULL || ot == Py_None)
     306        *pwhen = floattime();
     307    else {
     308        double when = PyFloat_AsDouble(ot);
     309        if (PyErr_Occurred())
     310            return 0;
     311        *pwhen = when;
     312    }
     313    return 1;
    308314}
    309315
     
    311317time_gmtime(PyObject *self, PyObject *args)
    312318{
    313         double when;
    314         if (!parse_time_double_args(args, "|O:gmtime", &when))
    315                 return NULL;
    316         return time_convert(when, gmtime);
     319    double when;
     320    if (!parse_time_double_args(args, "|O:gmtime", &when))
     321        return NULL;
     322    return time_convert(when, gmtime);
    317323}
    318324
     
    327333time_localtime(PyObject *self, PyObject *args)
    328334{
    329         double when;
    330         if (!parse_time_double_args(args, "|O:localtime", &when))
    331                 return NULL;
    332         return time_convert(when, localtime);
     335    double when;
     336    if (!parse_time_double_args(args, "|O:localtime", &when))
     337        return NULL;
     338    return time_convert(when, localtime);
    333339}
    334340
    335341PyDoc_STRVAR(localtime_doc,
    336342"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
    337                           tm_sec,tm_wday,tm_yday,tm_isdst)\n\
     343                          tm_sec,tm_wday,tm_yday,tm_isdst)\n\
    338344\n\
    339345Convert seconds since the Epoch to a time tuple expressing local time.\n\
     
    343349gettmarg(PyObject *args, struct tm *p)
    344350{
    345         int y;
    346         memset((void *) p, '\0', sizeof(struct tm));
    347 
    348         if (!PyArg_Parse(args, "(iiiiiiiii)",
    349                         &y,
    350                         &p->tm_mon,
    351                         &p->tm_mday,
    352                         &p->tm_hour,
    353                         &p->tm_min,
    354                         &p->tm_sec,
    355                         &p->tm_wday,
    356                         &p->tm_yday,
    357                         &p->tm_isdst))
    358                 return 0;
    359         if (y < 1900) {
    360                 PyObject *accept = PyDict_GetItemString(moddict,
    361                                                         "accept2dyear");
    362                 if (accept == NULL || !PyInt_Check(accept) ||
    363                     PyInt_AsLong(accept) == 0) {
    364                         PyErr_SetString(PyExc_ValueError,
    365                                         "year >= 1900 required");
    366                         return 0;
    367                 }
    368                 if (69 <= y && y <= 99)
    369                         y += 1900;
    370                 else if (0 <= y && y <= 68)
    371                         y += 2000;
    372                 else {
    373                         PyErr_SetString(PyExc_ValueError,
    374                                         "year out of range");
    375                         return 0;
    376                 }
    377         }
    378         p->tm_year = y - 1900;
    379         p->tm_mon--;
    380         p->tm_wday = (p->tm_wday + 1) % 7;
    381         p->tm_yday--;
    382         return 1;
     351    int y;
     352    memset((void *) p, '\0', sizeof(struct tm));
     353
     354    if (!PyArg_Parse(args, "(iiiiiiiii)",
     355                    &y,
     356                    &p->tm_mon,
     357                    &p->tm_mday,
     358                    &p->tm_hour,
     359                    &p->tm_min,
     360                    &p->tm_sec,
     361                    &p->tm_wday,
     362                    &p->tm_yday,
     363                    &p->tm_isdst))
     364        return 0;
     365    if (y < 1900) {
     366        PyObject *accept = PyDict_GetItemString(moddict,
     367                                                "accept2dyear");
     368        if (accept == NULL || !PyInt_Check(accept) ||
     369            PyInt_AsLong(accept) == 0) {
     370            PyErr_SetString(PyExc_ValueError,
     371                            "year >= 1900 required");
     372            return 0;
     373        }
     374        if (69 <= y && y <= 99)
     375            y += 1900;
     376        else if (0 <= y && y <= 68)
     377            y += 2000;
     378        else {
     379            PyErr_SetString(PyExc_ValueError,
     380                            "year out of range");
     381            return 0;
     382        }
     383    }
     384    p->tm_year = y - 1900;
     385    p->tm_mon--;
     386    p->tm_wday = (p->tm_wday + 1) % 7;
     387    p->tm_yday--;
     388    return 1;
    383389}
    384390
     
    387393time_strftime(PyObject *self, PyObject *args)
    388394{
    389         PyObject *tup = NULL;
    390         struct tm buf;
    391         const char *fmt;
    392         size_t fmtlen, buflen;
    393         char *outbuf = 0;
    394         size_t i;
    395 
    396         memset((void *) &buf, '\0', sizeof(buf));
    397 
    398         if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
    399                 return NULL;
    400 
    401         if (tup == NULL) {
    402                 time_t tt = time(NULL);
    403                 buf = *localtime(&tt);
    404         } else if (!gettmarg(tup, &buf))
    405                 return NULL;
    406 
    407         /* Checks added to make sure strftime() does not crash Python by
    408             indexing blindly into some array for a textual representation
    409             by some bad index (fixes bug #897625).
    410 
    411             Also support values of zero from Python code for arguments in which
    412             that is out of range by forcing that value to the lowest value that
    413             is valid (fixed bug #1520914).
    414 
    415             Valid ranges based on what is allowed in struct tm:
    416 
    417             - tm_year: [0, max(int)] (1)
    418             - tm_mon: [0, 11] (2)
    419             - tm_mday: [1, 31]
    420             - tm_hour: [0, 23]
    421             - tm_min: [0, 59]
    422             - tm_sec: [0, 60]
    423             - tm_wday: [0, 6] (1)
    424             - tm_yday: [0, 365] (2)
    425             - tm_isdst: [-max(int), max(int)]
    426 
    427             (1) gettmarg() handles bounds-checking.
    428             (2) Python's acceptable range is one greater than the range in C,
    429                 thus need to check against automatic decrement by gettmarg().
    430         */
    431         if (buf.tm_mon == -1)
    432             buf.tm_mon = 0;
    433         else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
    434             PyErr_SetString(PyExc_ValueError, "month out of range");
    435                         return NULL;
    436         }
    437         if (buf.tm_mday == 0)
    438             buf.tm_mday = 1;
    439         else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
    440             PyErr_SetString(PyExc_ValueError, "day of month out of range");
    441                         return NULL;
    442         }
    443         if (buf.tm_hour < 0 || buf.tm_hour > 23) {
    444             PyErr_SetString(PyExc_ValueError, "hour out of range");
     395    PyObject *tup = NULL;
     396    struct tm buf;
     397    const char *fmt;
     398    size_t fmtlen, buflen;
     399    char *outbuf = 0;
     400    size_t i;
     401
     402    memset((void *) &buf, '\0', sizeof(buf));
     403
     404    if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
     405        return NULL;
     406
     407    if (tup == NULL) {
     408        time_t tt = time(NULL);
     409        buf = *localtime(&tt);
     410    } else if (!gettmarg(tup, &buf))
     411        return NULL;
     412
     413    /* Checks added to make sure strftime() does not crash Python by
     414       indexing blindly into some array for a textual representation
     415       by some bad index (fixes bug #897625).
     416
     417        Also support values of zero from Python code for arguments in which
     418        that is out of range by forcing that value to the lowest value that
     419        is valid (fixed bug #1520914).
     420
     421        Valid ranges based on what is allowed in struct tm:
     422
     423        - tm_year: [0, max(int)] (1)
     424        - tm_mon: [0, 11] (2)
     425        - tm_mday: [1, 31]
     426        - tm_hour: [0, 23]
     427        - tm_min: [0, 59]
     428        - tm_sec: [0, 60]
     429        - tm_wday: [0, 6] (1)
     430        - tm_yday: [0, 365] (2)
     431        - tm_isdst: [-max(int), max(int)]
     432
     433        (1) gettmarg() handles bounds-checking.
     434        (2) Python's acceptable range is one greater than the range in C,
     435        thus need to check against automatic decrement by gettmarg().
     436    */
     437    if (buf.tm_mon == -1)
     438        buf.tm_mon = 0;
     439    else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
     440        PyErr_SetString(PyExc_ValueError, "month out of range");
    445441            return NULL;
    446         }
    447         if (buf.tm_min < 0 || buf.tm_min > 59) {
    448             PyErr_SetString(PyExc_ValueError, "minute out of range");
     442    }
     443    if (buf.tm_mday == 0)
     444        buf.tm_mday = 1;
     445    else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
     446        PyErr_SetString(PyExc_ValueError, "day of month out of range");
    449447            return NULL;
    450         }
    451         if (buf.tm_sec < 0 || buf.tm_sec > 61) {
    452             PyErr_SetString(PyExc_ValueError, "seconds out of range");
    453             return NULL;
    454         }
    455         /* tm_wday does not need checking of its upper-bound since taking
    456         ``% 7`` in gettmarg() automatically restricts the range. */
    457         if (buf.tm_wday < 0) {
    458             PyErr_SetString(PyExc_ValueError, "day of week out of range");
    459             return NULL;
    460         }
    461         if (buf.tm_yday == -1)
    462             buf.tm_yday = 0;
    463         else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
    464             PyErr_SetString(PyExc_ValueError, "day of year out of range");
    465             return NULL;
    466         }
    467         if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
    468             PyErr_SetString(PyExc_ValueError,
    469                             "daylight savings flag out of range");
    470             return NULL;
    471         }
    472 
    473         fmtlen = strlen(fmt);
    474 
    475         /* I hate these functions that presume you know how big the output
    476          * will be ahead of time...
    477          */
    478         for (i = 1024; ; i += i) {
    479                 outbuf = (char *)malloc(i);
    480                 if (outbuf == NULL) {
    481                         return PyErr_NoMemory();
    482                 }
    483                 buflen = strftime(outbuf, i, fmt, &buf);
    484                 if (buflen > 0 || i >= 256 * fmtlen) {
    485                         /* If the buffer is 256 times as long as the format,
    486                            it's probably not failing for lack of room!
    487                            More likely, the format yields an empty result,
    488                            e.g. an empty format, or %Z when the timezone
    489                            is unknown. */
    490                         PyObject *ret;
    491                         ret = PyString_FromStringAndSize(outbuf, buflen);
    492                         free(outbuf);
    493                         return ret;
    494                 }
    495                 free(outbuf);
     448    }
     449    if (buf.tm_hour < 0 || buf.tm_hour > 23) {
     450        PyErr_SetString(PyExc_ValueError, "hour out of range");
     451        return NULL;
     452    }
     453    if (buf.tm_min < 0 || buf.tm_min > 59) {
     454        PyErr_SetString(PyExc_ValueError, "minute out of range");
     455        return NULL;
     456    }
     457    if (buf.tm_sec < 0 || buf.tm_sec > 61) {
     458        PyErr_SetString(PyExc_ValueError, "seconds out of range");
     459        return NULL;
     460    }
     461    /* tm_wday does not need checking of its upper-bound since taking
     462    ``% 7`` in gettmarg() automatically restricts the range. */
     463    if (buf.tm_wday < 0) {
     464        PyErr_SetString(PyExc_ValueError, "day of week out of range");
     465        return NULL;
     466    }
     467    if (buf.tm_yday == -1)
     468        buf.tm_yday = 0;
     469    else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
     470        PyErr_SetString(PyExc_ValueError, "day of year out of range");
     471        return NULL;
     472    }
     473    /* Normalize tm_isdst just in case someone foolishly implements %Z
     474       based on the assumption that tm_isdst falls within the range of
     475       [-1, 1] */
     476    if (buf.tm_isdst < -1)
     477        buf.tm_isdst = -1;
     478    else if (buf.tm_isdst > 1)
     479        buf.tm_isdst = 1;
     480
     481#ifdef MS_WINDOWS
     482    /* check that the format string contains only valid directives */
     483    for(outbuf = strchr(fmt, '%');
     484        outbuf != NULL;
     485        outbuf = strchr(outbuf+2, '%'))
     486    {
     487        if (outbuf[1]=='#')
     488            ++outbuf; /* not documented by python, */
     489        if (outbuf[1]=='\0' ||
     490            !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
     491        {
     492            PyErr_SetString(PyExc_ValueError, "Invalid format string");
     493            return 0;
     494        }
     495    }
     496#endif
     497
     498    fmtlen = strlen(fmt);
     499
     500    /* I hate these functions that presume you know how big the output
     501     * will be ahead of time...
     502     */
     503    for (i = 1024; ; i += i) {
     504        outbuf = (char *)malloc(i);
     505        if (outbuf == NULL) {
     506            return PyErr_NoMemory();
     507        }
     508        buflen = strftime(outbuf, i, fmt, &buf);
     509        if (buflen > 0 || i >= 256 * fmtlen) {
     510            /* If the buffer is 256 times as long as the format,
     511               it's probably not failing for lack of room!
     512               More likely, the format yields an empty result,
     513               e.g. an empty format, or %Z when the timezone
     514               is unknown. */
     515            PyObject *ret;
     516            ret = PyString_FromStringAndSize(outbuf, buflen);
     517            free(outbuf);
     518            return ret;
     519        }
     520        free(outbuf);
    496521#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
    497                 /* VisualStudio .NET 2005 does this properly */
    498                 if (buflen == 0 && errno == EINVAL) {
    499                         PyErr_SetString(PyExc_ValueError, "Invalid format string");
    500                         return 0;
    501                 }
    502 #endif
    503                
    504         }
     522        /* VisualStudio .NET 2005 does this properly */
     523        if (buflen == 0 && errno == EINVAL) {
     524            PyErr_SetString(PyExc_ValueError, "Invalid format string");
     525            return 0;
     526        }
     527#endif
     528
     529    }
    505530}
    506531
     
    521546    if (!strptime_module)
    522547        return NULL;
    523     strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
     548    strptime_result = PyObject_CallMethod(strptime_module,
     549                                            "_strptime_time", "O", args);
    524550    Py_DECREF(strptime_module);
    525551    return strptime_result;
     
    536562time_asctime(PyObject *self, PyObject *args)
    537563{
    538         PyObject *tup = NULL;
    539         struct tm buf;
    540         char *p;
    541         if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
    542                 return NULL;
    543         if (tup == NULL) {
    544                 time_t tt = time(NULL);
    545                 buf = *localtime(&tt);
    546         } else if (!gettmarg(tup, &buf))
    547                 return NULL;
    548         p = asctime(&buf);
    549         if (p[24] == '\n')
    550                 p[24] = '\0';
    551         return PyString_FromString(p);
     564    PyObject *tup = NULL;
     565    struct tm buf;
     566    char *p;
     567    if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
     568        return NULL;
     569    if (tup == NULL) {
     570        time_t tt = time(NULL);
     571        buf = *localtime(&tt);
     572    } else if (!gettmarg(tup, &buf))
     573        return NULL;
     574    p = asctime(&buf);
     575    if (p == NULL) {
     576        PyErr_SetString(PyExc_ValueError, "invalid time");
     577        return NULL;
     578    }
     579    if (p[24] == '\n')
     580        p[24] = '\0';
     581    return PyString_FromString(p);
    552582}
    553583
     
    562592time_ctime(PyObject *self, PyObject *args)
    563593{
    564         PyObject *ot = NULL;
    565         time_t tt;
    566         char *p;
    567 
    568         if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
    569                 return NULL;
    570         if (ot == NULL || ot == Py_None)
    571                 tt = time(NULL);
    572         else {
    573                 double dt = PyFloat_AsDouble(ot);
    574                 if (PyErr_Occurred())
    575                         return NULL;
    576                 tt = _PyTime_DoubleToTimet(dt);
    577                 if (tt == (time_t)-1 && PyErr_Occurred())
    578                         return NULL;
    579         }
    580         p = ctime(&tt);
    581         if (p == NULL) {
    582                 PyErr_SetString(PyExc_ValueError, "unconvertible time");
    583                 return NULL;
    584         }
    585         if (p[24] == '\n')
    586                 p[24] = '\0';
    587         return PyString_FromString(p);
     594    PyObject *ot = NULL;
     595    time_t tt;
     596    char *p;
     597
     598    if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
     599        return NULL;
     600    if (ot == NULL || ot == Py_None)
     601        tt = time(NULL);
     602    else {
     603        double dt = PyFloat_AsDouble(ot);
     604        if (PyErr_Occurred())
     605            return NULL;
     606        tt = _PyTime_DoubleToTimet(dt);
     607        if (tt == (time_t)-1 && PyErr_Occurred())
     608            return NULL;
     609    }
     610    p = ctime(&tt);
     611    if (p == NULL) {
     612        PyErr_SetString(PyExc_ValueError, "unconvertible time");
     613        return NULL;
     614    }
     615    if (p[24] == '\n')
     616        p[24] = '\0';
     617    return PyString_FromString(p);
    588618}
    589619
     
    599629time_mktime(PyObject *self, PyObject *tup)
    600630{
    601         struct tm buf;
    602         time_t tt;
    603         if (!gettmarg(tup, &buf))
    604                 return NULL;
    605         tt = mktime(&buf);
    606         if (tt == (time_t)(-1)) {
    607                 PyErr_SetString(PyExc_OverflowError,
    608                                 "mktime argument out of range");
    609                 return NULL;
    610         }
    611         return PyFloat_FromDouble((double)tt);
     631    struct tm buf;
     632    time_t tt;
     633    if (!gettmarg(tup, &buf))
     634        return NULL;
     635    buf.tm_wday = -1;  /* sentinel; original value ignored */
     636    tt = mktime(&buf);
     637    /* Return value of -1 does not necessarily mean an error, but tm_wday
     638     * cannot remain set to -1 if mktime succeeded. */
     639    if (tt == (time_t)(-1) && buf.tm_wday == -1) {
     640        PyErr_SetString(PyExc_OverflowError,
     641                        "mktime argument out of range");
     642        return NULL;
     643    }
     644    return PyFloat_FromDouble((double)tt);
    612645}
    613646
     
    624657time_tzset(PyObject *self, PyObject *unused)
    625658{
    626         PyObject* m;
    627 
    628         m = PyImport_ImportModuleNoBlock("time");
    629         if (m == NULL) {
    630             return NULL;
    631         }
    632 
    633         tzset();
    634 
    635         /* Reset timezone, altzone, daylight and tzname */
    636         inittimezone(m);
    637         Py_DECREF(m);
    638 
    639         Py_INCREF(Py_None);
    640         return Py_None;
     659    PyObject* m;
     660
     661    m = PyImport_ImportModuleNoBlock("time");
     662    if (m == NULL) {
     663        return NULL;
     664    }
     665
     666    tzset();
     667
     668    /* Reset timezone, altzone, daylight and tzname */
     669    inittimezone(m);
     670    Py_DECREF(m);
     671
     672    Py_INCREF(Py_None);
     673    return Py_None;
    641674}
    642675
    643676PyDoc_STRVAR(tzset_doc,
    644 "tzset(zone)\n\
     677"tzset()\n\
    645678\n\
    646679Initialize, or reinitialize, the local timezone to the value stored in\n\
     
    658691inittimezone(PyObject *m) {
    659692    /* This code moved from inittime wholesale to allow calling it from
    660         time_tzset. In the future, some parts of it can be moved back
    661         (for platforms that don't HAVE_WORKING_TZSET, when we know what they
    662         are), and the extraneous calls to tzset(3) should be removed.
    663         I haven't done this yet, as I don't want to change this code as
    664         little as possible when introducing the time.tzset and time.tzsetwall
    665         methods. This should simply be a method of doing the following once,
    666         at the top of this function and removing the call to tzset() from
    667         time_tzset():
    668 
    669             #ifdef HAVE_TZSET
    670             tzset()
    671             #endif
    672 
    673         And I'm lazy and hate C so nyer.
     693    time_tzset. In the future, some parts of it can be moved back
     694    (for platforms that don't HAVE_WORKING_TZSET, when we know what they
     695    are), and the extraneous calls to tzset(3) should be removed.
     696    I haven't done this yet, as I don't want to change this code as
     697    little as possible when introducing the time.tzset and time.tzsetwall
     698    methods. This should simply be a method of doing the following once,
     699    at the top of this function and removing the call to tzset() from
     700    time_tzset():
     701
     702        #ifdef HAVE_TZSET
     703        tzset()
     704        #endif
     705
     706    And I'm lazy and hate C so nyer.
    674707     */
    675708#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
    676         tzset();
     709    tzset();
    677710#ifdef PYOS_OS2
    678         PyModule_AddIntConstant(m, "timezone", _timezone);
     711    PyModule_AddIntConstant(m, "timezone", _timezone);
    679712#else /* !PYOS_OS2 */
    680         PyModule_AddIntConstant(m, "timezone", timezone);
     713    PyModule_AddIntConstant(m, "timezone", timezone);
    681714#endif /* PYOS_OS2 */
    682715#ifdef HAVE_ALTZONE
    683         PyModule_AddIntConstant(m, "altzone", altzone);
     716    PyModule_AddIntConstant(m, "altzone", altzone);
    684717#else
    685718#ifdef PYOS_OS2
    686         PyModule_AddIntConstant(m, "altzone", _timezone-3600);
     719    PyModule_AddIntConstant(m, "altzone", _timezone-3600);
    687720#else /* !PYOS_OS2 */
    688         PyModule_AddIntConstant(m, "altzone", timezone-3600);
     721    PyModule_AddIntConstant(m, "altzone", timezone-3600);
    689722#endif /* PYOS_OS2 */
    690723#endif
    691         PyModule_AddIntConstant(m, "daylight", daylight);
    692         PyModule_AddObject(m, "tzname",
    693                            Py_BuildValue("(zz)", tzname[0], tzname[1]));
     724    PyModule_AddIntConstant(m, "daylight", daylight);
     725    PyModule_AddObject(m, "tzname",
     726                       Py_BuildValue("(zz)", tzname[0], tzname[1]));
    694727#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
    695728#ifdef HAVE_STRUCT_TM_TM_ZONE
    696         {
     729    {
    697730#define YEAR ((time_t)((365 * 24 + 6) * 3600))
    698                 time_t t;
    699                 struct tm *p;
    700                 long janzone, julyzone;
    701                 char janname[10], julyname[10];
    702                 t = (time((time_t *)0) / YEAR) * YEAR;
    703                 p = localtime(&t);
    704                 janzone = -p->tm_gmtoff;
    705                 strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
    706                 janname[9] = '\0';
    707                 t += YEAR/2;
    708                 p = localtime(&t);
    709                 julyzone = -p->tm_gmtoff;
    710                 strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
    711                 julyname[9] = '\0';
    712 
    713                 if( janzone < julyzone ) {
    714                         /* DST is reversed in the southern hemisphere */
    715                         PyModule_AddIntConstant(m, "timezone", julyzone);
    716                         PyModule_AddIntConstant(m, "altzone", janzone);
    717                         PyModule_AddIntConstant(m, "daylight",
    718                                                 janzone != julyzone);
    719                         PyModule_AddObject(m, "tzname",
    720                                            Py_BuildValue("(zz)",
    721                                                         julyname, janname));
    722                 } else {
    723                         PyModule_AddIntConstant(m, "timezone", janzone);
    724                         PyModule_AddIntConstant(m, "altzone", julyzone);
    725                         PyModule_AddIntConstant(m, "daylight",
    726                                                 janzone != julyzone);
    727                         PyModule_AddObject(m, "tzname",
    728                                            Py_BuildValue("(zz)",
    729                                                         janname, julyname));
    730                 }
    731         }
     731        time_t t;
     732        struct tm *p;
     733        long janzone, julyzone;
     734        char janname[10], julyname[10];
     735        t = (time((time_t *)0) / YEAR) * YEAR;
     736        p = localtime(&t);
     737        janzone = -p->tm_gmtoff;
     738        strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
     739        janname[9] = '\0';
     740        t += YEAR/2;
     741        p = localtime(&t);
     742        julyzone = -p->tm_gmtoff;
     743        strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
     744        julyname[9] = '\0';
     745
     746        if( janzone < julyzone ) {
     747            /* DST is reversed in the southern hemisphere */
     748            PyModule_AddIntConstant(m, "timezone", julyzone);
     749            PyModule_AddIntConstant(m, "altzone", janzone);
     750            PyModule_AddIntConstant(m, "daylight",
     751                                    janzone != julyzone);
     752            PyModule_AddObject(m, "tzname",
     753                               Py_BuildValue("(zz)",
     754                                            julyname, janname));
     755        } else {
     756            PyModule_AddIntConstant(m, "timezone", janzone);
     757            PyModule_AddIntConstant(m, "altzone", julyzone);
     758            PyModule_AddIntConstant(m, "daylight",
     759                                    janzone != julyzone);
     760            PyModule_AddObject(m, "tzname",
     761                               Py_BuildValue("(zz)",
     762                                            janname, julyname));
     763        }
     764    }
    732765#else
    733766#endif /* HAVE_STRUCT_TM_TM_ZONE */
    734767#ifdef __CYGWIN__
    735         tzset();
    736         PyModule_AddIntConstant(m, "timezone", _timezone);
    737         PyModule_AddIntConstant(m, "altzone", _timezone-3600);
    738         PyModule_AddIntConstant(m, "daylight", _daylight);
    739         PyModule_AddObject(m, "tzname",
    740                            Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
     768    tzset();
     769    PyModule_AddIntConstant(m, "timezone", _timezone);
     770    PyModule_AddIntConstant(m, "altzone", _timezone-3600);
     771    PyModule_AddIntConstant(m, "daylight", _daylight);
     772    PyModule_AddObject(m, "tzname",
     773                       Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
    741774#endif /* __CYGWIN__ */
    742775#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
     
    745778
    746779static PyMethodDef time_methods[] = {
    747         {"time",        time_time, METH_NOARGS, time_doc},
     780    {"time",            time_time, METH_NOARGS, time_doc},
    748781#ifdef HAVE_CLOCK
    749         {"clock",       time_clock, METH_NOARGS, clock_doc},
    750 #endif
    751         {"sleep",       time_sleep, METH_VARARGS, sleep_doc},
    752         {"gmtime",      time_gmtime, METH_VARARGS, gmtime_doc},
    753         {"localtime",   time_localtime, METH_VARARGS, localtime_doc},
    754         {"asctime",     time_asctime, METH_VARARGS, asctime_doc},
    755         {"ctime",       time_ctime, METH_VARARGS, ctime_doc},
     782    {"clock",           time_clock, METH_NOARGS, clock_doc},
     783#endif
     784    {"sleep",           time_sleep, METH_VARARGS, sleep_doc},
     785    {"gmtime",          time_gmtime, METH_VARARGS, gmtime_doc},
     786    {"localtime",       time_localtime, METH_VARARGS, localtime_doc},
     787    {"asctime",         time_asctime, METH_VARARGS, asctime_doc},
     788    {"ctime",           time_ctime, METH_VARARGS, ctime_doc},
    756789#ifdef HAVE_MKTIME
    757         {"mktime",      time_mktime, METH_O, mktime_doc},
     790    {"mktime",          time_mktime, METH_O, mktime_doc},
    758791#endif
    759792#ifdef HAVE_STRFTIME
    760         {"strftime",    time_strftime, METH_VARARGS, strftime_doc},
    761 #endif
    762         {"strptime",    time_strptime, METH_VARARGS, strptime_doc},
     793    {"strftime",        time_strftime, METH_VARARGS, strftime_doc},
     794#endif
     795    {"strptime",        time_strptime, METH_VARARGS, strptime_doc},
    763796#ifdef HAVE_WORKING_TZSET
    764         {"tzset",       time_tzset, METH_NOARGS, tzset_doc},
    765 #endif
    766         {NULL,          NULL}           /* sentinel */
     797    {"tzset",           time_tzset, METH_NOARGS, tzset_doc},
     798#endif
     799    {NULL,              NULL}           /* sentinel */
    767800};
    768801
     
    817850inittime(void)
    818851{
    819         PyObject *m;
    820         char *p;
    821         m = Py_InitModule3("time", time_methods, module_doc);
    822         if (m == NULL)
    823                 return;
    824 
    825         /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
    826         p = Py_GETENV("PYTHONY2K");
    827         PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
    828         /* Squirrel away the module's dictionary for the y2k check */
    829         moddict = PyModule_GetDict(m);
    830         Py_INCREF(moddict);
    831 
    832         /* Set, or reset, module variables like time.timezone */
    833         inittimezone(m);
     852    PyObject *m;
     853    char *p;
     854    m = Py_InitModule3("time", time_methods, module_doc);
     855    if (m == NULL)
     856        return;
     857
     858    /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
     859    p = Py_GETENV("PYTHONY2K");
     860    PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
     861    /* If an embedded interpreter is shutdown and reinitialized the old
     862       moddict was not decrefed on shutdown and the next import of this
     863       module leads to a leak.  Conditionally decref here to prevent that.
     864    */
     865    Py_XDECREF(moddict);
     866    /* Squirrel away the module's dictionary for the y2k check */
     867    moddict = PyModule_GetDict(m);
     868    Py_INCREF(moddict);
     869
     870    /* Set, or reset, module variables like time.timezone */
     871    inittimezone(m);
    834872
    835873#ifdef MS_WINDOWS
    836         /* Helper to allow interrupts for Windows.
    837            If Ctrl+C event delivered while not sleeping
    838            it will be ignored.
    839         */
    840         main_thread = PyThread_get_thread_ident();
    841         hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    842         SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
     874    /* Helper to allow interrupts for Windows.
     875       If Ctrl+C event delivered while not sleeping
     876       it will be ignored.
     877    */
     878    main_thread = PyThread_get_thread_ident();
     879    hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
     880    SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
    843881#endif /* MS_WINDOWS */
    844         if (!initialized) {
    845                 PyStructSequence_InitType(&StructTimeType,
    846                                           &struct_time_type_desc);
    847         }
    848         Py_INCREF(&StructTimeType);
    849         PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
    850         initialized = 1;
     882    if (!initialized) {
     883        PyStructSequence_InitType(&StructTimeType,
     884                                  &struct_time_type_desc);
     885    }
     886    Py_INCREF(&StructTimeType);
     887    PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
     888    initialized = 1;
    851889}
    852890
     
    857895floattime(void)
    858896{
    859         /* There are three ways to get the time:
    860           (1) gettimeofday() -- resolution in microseconds
    861           (2) ftime() -- resolution in milliseconds
    862           (3) time() -- resolution in seconds
    863           In all cases the return value is a float in seconds.
    864           Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
    865           fail, so we fall back on ftime() or time().
    866           Note: clock resolution does not imply clock accuracy! */
     897    /* There are three ways to get the time:
     898      (1) gettimeofday() -- resolution in microseconds
     899      (2) ftime() -- resolution in milliseconds
     900      (3) time() -- resolution in seconds
     901      In all cases the return value is a float in seconds.
     902      Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
     903      fail, so we fall back on ftime() or time().
     904      Note: clock resolution does not imply clock accuracy! */
    867905#ifdef HAVE_GETTIMEOFDAY
    868         {
    869                 struct timeval t;
     906    {
     907        struct timeval t;
    870908#ifdef GETTIMEOFDAY_NO_TZ
    871                 if (gettimeofday(&t) == 0)
    872                         return (double)t.tv_sec + t.tv_usec*0.000001;
     909        if (gettimeofday(&t) == 0)
     910            return (double)t.tv_sec + t.tv_usec*0.000001;
    873911#else /* !GETTIMEOFDAY_NO_TZ */
    874                 if (gettimeofday(&t, (struct timezone *)NULL) == 0)
    875                         return (double)t.tv_sec + t.tv_usec*0.000001;
     912        if (gettimeofday(&t, (struct timezone *)NULL) == 0)
     913            return (double)t.tv_sec + t.tv_usec*0.000001;
    876914#endif /* !GETTIMEOFDAY_NO_TZ */
    877         }
     915    }
    878916
    879917#endif /* !HAVE_GETTIMEOFDAY */
    880         {
     918    {
    881919#if defined(HAVE_FTIME)
    882                 struct timeb t;
    883                 ftime(&t);
    884                 return (double)t.time + (double)t.millitm * (double)0.001;
     920        struct timeb t;
     921        ftime(&t);
     922        return (double)t.time + (double)t.millitm * (double)0.001;
    885923#else /* !HAVE_FTIME */
    886                 time_t secs;
    887                 time(&secs);
    888                 return (double)secs;
     924        time_t secs;
     925        time(&secs);
     926        return (double)secs;
    889927#endif /* !HAVE_FTIME */
    890         }
     928    }
    891929}
    892930
     
    901939/* XXX Should test for MS_WINDOWS first! */
    902940#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
    903         struct timeval t;
    904         double frac;
    905         frac = fmod(secs, 1.0);
    906         secs = floor(secs);
    907         t.tv_sec = (long)secs;
    908         t.tv_usec = (long)(frac*1000000.0);
    909         Py_BEGIN_ALLOW_THREADS
    910         if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
     941    struct timeval t;
     942    double frac;
     943    frac = fmod(secs, 1.0);
     944    secs = floor(secs);
     945    t.tv_sec = (long)secs;
     946    t.tv_usec = (long)(frac*1000000.0);
     947    Py_BEGIN_ALLOW_THREADS
     948    if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
    911949#ifdef EINTR
    912                 if (errno != EINTR) {
     950        if (errno != EINTR) {
    913951#else
    914                 if (1) {
    915 #endif
    916                         Py_BLOCK_THREADS
    917                         PyErr_SetFromErrno(PyExc_IOError);
    918                         return -1;
    919                 }
    920         }
    921         Py_END_ALLOW_THREADS
     952        if (1) {
     953#endif
     954            Py_BLOCK_THREADS
     955            PyErr_SetFromErrno(PyExc_IOError);
     956            return -1;
     957        }
     958    }
     959    Py_END_ALLOW_THREADS
    922960#elif defined(__WATCOMC__) && !defined(__QNX__)
    923         /* XXX Can't interrupt this sleep */
    924         Py_BEGIN_ALLOW_THREADS
    925         delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
    926         Py_END_ALLOW_THREADS
     961    /* XXX Can't interrupt this sleep */
     962    Py_BEGIN_ALLOW_THREADS
     963    delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
     964    Py_END_ALLOW_THREADS
    927965#elif defined(MS_WINDOWS)
    928         {
    929                 double millisecs = secs * 1000.0;
    930                 unsigned long ul_millis;
    931 
    932                 if (millisecs > (double)ULONG_MAX) {
    933                         PyErr_SetString(PyExc_OverflowError,
    934                                         "sleep length is too large");
    935                         return -1;
    936                 }
    937                 Py_BEGIN_ALLOW_THREADS
    938                 /* Allow sleep(0) to maintain win32 semantics, and as decreed
    939                 * by Guido, only the main thread can be interrupted.
    940                 */
    941                 ul_millis = (unsigned long)millisecs;
    942                 if (ul_millis == 0 ||
    943                     main_thread != PyThread_get_thread_ident())
    944                         Sleep(ul_millis);
    945                 else {
    946                         DWORD rc;
    947                         ResetEvent(hInterruptEvent);
    948                         rc = WaitForSingleObject(hInterruptEvent, ul_millis);
    949                         if (rc == WAIT_OBJECT_0) {
    950                                 /* Yield to make sure real Python signal
    951                                 * handler called.
    952                                 */
    953                                 Sleep(1);
    954                                 Py_BLOCK_THREADS
    955                                 errno = EINTR;
    956                                 PyErr_SetFromErrno(PyExc_IOError);
    957                                 return -1;
    958                         }
    959                 }
    960                 Py_END_ALLOW_THREADS
    961         }
     966    {
     967        double millisecs = secs * 1000.0;
     968        unsigned long ul_millis;
     969
     970        if (millisecs > (double)ULONG_MAX) {
     971            PyErr_SetString(PyExc_OverflowError,
     972                            "sleep length is too large");
     973            return -1;
     974        }
     975        Py_BEGIN_ALLOW_THREADS
     976        /* Allow sleep(0) to maintain win32 semantics, and as decreed
     977        * by Guido, only the main thread can be interrupted.
     978        */
     979        ul_millis = (unsigned long)millisecs;
     980        if (ul_millis == 0 ||
     981            main_thread != PyThread_get_thread_ident())
     982            Sleep(ul_millis);
     983        else {
     984            DWORD rc;
     985            ResetEvent(hInterruptEvent);
     986            rc = WaitForSingleObject(hInterruptEvent, ul_millis);
     987            if (rc == WAIT_OBJECT_0) {
     988                /* Yield to make sure real Python signal
     989                * handler called.
     990                */
     991                Sleep(1);
     992                Py_BLOCK_THREADS
     993                errno = EINTR;
     994                PyErr_SetFromErrno(PyExc_IOError);
     995                return -1;
     996            }
     997        }
     998        Py_END_ALLOW_THREADS
     999    }
    9621000#elif defined(PYOS_OS2)
    963         /* This Sleep *IS* Interruptable by Exceptions */
    964         Py_BEGIN_ALLOW_THREADS
    965         if (DosSleep(secs * 1000) != NO_ERROR) {
    966                 Py_BLOCK_THREADS
    967                 PyErr_SetFromErrno(PyExc_IOError);
    968                 return -1;
    969         }
    970         Py_END_ALLOW_THREADS
     1001    /* This Sleep *IS* Interruptable by Exceptions */
     1002    Py_BEGIN_ALLOW_THREADS
     1003    if (DosSleep(secs * 1000) != NO_ERROR) {
     1004        Py_BLOCK_THREADS
     1005        PyErr_SetFromErrno(PyExc_IOError);
     1006        return -1;
     1007    }
     1008    Py_END_ALLOW_THREADS
    9711009#elif defined(__BEOS__)
    972         /* This sleep *CAN BE* interrupted. */
    973         {
    974                 if( secs <= 0.0 ) {
    975                         return;
    976                 }
    977 
    978                 Py_BEGIN_ALLOW_THREADS
    979                 /* BeOS snooze() is in microseconds... */
    980                 if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
    981                         Py_BLOCK_THREADS
    982                         PyErr_SetFromErrno( PyExc_IOError );
    983                         return -1;
    984                 }
    985                 Py_END_ALLOW_THREADS
    986         }
     1010    /* This sleep *CAN BE* interrupted. */
     1011    {
     1012        if( secs <= 0.0 ) {
     1013            return;
     1014        }
     1015
     1016        Py_BEGIN_ALLOW_THREADS
     1017        /* BeOS snooze() is in microseconds... */
     1018        if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
     1019            Py_BLOCK_THREADS
     1020            PyErr_SetFromErrno( PyExc_IOError );
     1021            return -1;
     1022        }
     1023        Py_END_ALLOW_THREADS
     1024    }
    9871025#elif defined(RISCOS)
    988         if (secs <= 0.0)
    989                 return 0;
    990         Py_BEGIN_ALLOW_THREADS
    991         /* This sleep *CAN BE* interrupted. */
    992         if ( riscos_sleep(secs) )
    993                 return -1;
    994         Py_END_ALLOW_THREADS
     1026    if (secs <= 0.0)
     1027        return 0;
     1028    Py_BEGIN_ALLOW_THREADS
     1029    /* This sleep *CAN BE* interrupted. */
     1030    if ( riscos_sleep(secs) )
     1031        return -1;
     1032    Py_END_ALLOW_THREADS
    9951033#elif defined(PLAN9)
    996         {
    997                 double millisecs = secs * 1000.0;
    998                 if (millisecs > (double)LONG_MAX) {
    999                         PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
    1000                         return -1;
    1001                 }
    1002                 /* This sleep *CAN BE* interrupted. */
    1003                 Py_BEGIN_ALLOW_THREADS
    1004                 if(sleep((long)millisecs) < 0){
    1005                         Py_BLOCK_THREADS
    1006                         PyErr_SetFromErrno(PyExc_IOError);
    1007                         return -1;
    1008                 }
    1009                 Py_END_ALLOW_THREADS
    1010         }
     1034    {
     1035        double millisecs = secs * 1000.0;
     1036        if (millisecs > (double)LONG_MAX) {
     1037            PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
     1038            return -1;
     1039        }
     1040        /* This sleep *CAN BE* interrupted. */
     1041        Py_BEGIN_ALLOW_THREADS
     1042        if(sleep((long)millisecs) < 0){
     1043            Py_BLOCK_THREADS
     1044            PyErr_SetFromErrno(PyExc_IOError);
     1045            return -1;
     1046        }
     1047        Py_END_ALLOW_THREADS
     1048    }
    10111049#else
    1012         /* XXX Can't interrupt this sleep */
    1013         Py_BEGIN_ALLOW_THREADS
    1014         sleep((int)secs);
    1015         Py_END_ALLOW_THREADS
    1016 #endif
    1017 
    1018         return 0;
    1019 }
    1020 
    1021 
     1050    /* XXX Can't interrupt this sleep */
     1051    Py_BEGIN_ALLOW_THREADS
     1052    sleep((int)secs);
     1053    Py_END_ALLOW_THREADS
     1054#endif
     1055
     1056    return 0;
     1057}
     1058
     1059/* export floattime to socketmodule.c */
     1060PyAPI_FUNC(double)
     1061_PyTime_FloatTime(void)
     1062{
     1063    return floattime();
     1064}
Note: See TracChangeset for help on using the changeset viewer.