diff -r c3cd486cb6b9 Modules/posixmodule.c --- a/Modules/posixmodule.c Mon Apr 20 09:29:57 2015 -0700 +++ b/Modules/posixmodule.c Mon Apr 20 19:33:18 2015 -0700 @@ -3267,12 +3267,15 @@ static PyObject * posix_getcwd(int use_bytes) { - char buf[1026]; - char *res; + char *buf, *tmpbuf; + char *cwd; + const size_t chunk = 1024; + size_t buflen = 0; + PyObject *obj; #ifdef MS_WINDOWS if (!use_bytes) { - wchar_t wbuf[1026]; + wchar_t wbuf[MAXPATHLEN]; wchar_t *wbuf2 = wbuf; PyObject *resobj; DWORD len; @@ -3306,14 +3309,36 @@ return NULL; #endif + buf = cwd = NULL; Py_BEGIN_ALLOW_THREADS - res = getcwd(buf, sizeof buf); + do { + buflen += chunk; + tmpbuf = PyMem_RawRealloc(buf, buflen); + if (tmpbuf == NULL) { + cwd = NULL; + break; + } + + buf = tmpbuf; + cwd = getcwd(buf, buflen); + } while (cwd == NULL && errno == ERANGE); Py_END_ALLOW_THREADS - if (res == NULL) + + if (cwd == NULL) { + PyMem_RawFree(buf); + buf = NULL; return posix_error(); - if (use_bytes) - return PyBytes_FromStringAndSize(buf, strlen(buf)); - return PyUnicode_DecodeFSDefault(buf); + } + + if (cwd && use_bytes) { + obj = PyBytes_FromStringAndSize(buf, strlen(buf)); + } else { + obj = PyUnicode_DecodeFSDefault(buf); + } + + PyMem_RawFree(buf); + buf = NULL; + return obj; }