8756 lines · 218.4 KB · C
RawDownload
#endif #if defined(PYOS_OS2)/********************************************************************** *         Helper Function to Trim and Format OS/2 Messages **********************************************************************/    static voidos2_formatmsg(char *msgbuf, int msglen, char *reason){    msgbuf[msglen] = '\0'; /* OS/2 Doesn't Guarantee a Terminator */     if (strlen(msgbuf) > 0) { /* If Non-Empty Msg, Trim CRLF */        char *lastc = &msgbuf[ strlen(msgbuf)-1 ];         while (lastc > msgbuf && isspace(Py_CHARMASK(*lastc)))            *lastc-- = '\0'; /* Trim Trailing Whitespace (CRLF) */    }     /* Add Optional Reason Text */    if (reason) {        strcat(msgbuf, " : ");        strcat(msgbuf, reason);    }} /********************************************************************** *             Decode an OS/2 Operating System Error Code * * A convenience function to lookup an OS/2 error code and return a * text message we can use to raise a Python exception. * * Notes: *   The messages for errors returned from the OS/2 kernel reside in *   the file OSO001.MSG in the \OS2 directory hierarchy. * **********************************************************************/    static char *os2_strerror(char *msgbuf, int msgbuflen, int errorcode, char *reason){    APIRET rc;    ULONG  msglen;     /* Retrieve Kernel-Related Error Message from OSO001.MSG File */    Py_BEGIN_ALLOW_THREADS    rc = DosGetMessage(NULL, 0, msgbuf, msgbuflen,                       errorcode, "oso001.msg", &msglen);    Py_END_ALLOW_THREADS     if (rc == NO_ERROR)        os2_formatmsg(msgbuf, msglen, reason);    else        PyOS_snprintf(msgbuf, msgbuflen,        	      "unknown OS error #%d", errorcode);     return msgbuf;} /* Set an OS/2-specific error and return NULL.  OS/2 kernel   errors are not in a global variable e.g. 'errno' nor are   they congruent with posix error numbers. */ static PyObject * os2_error(int code){    char text[1024];    PyObject *v;     os2_strerror(text, sizeof(text), code, "");     v = Py_BuildValue("(is)", code, text);    if (v != NULL) {        PyErr_SetObject(PyExc_OSError, v);        Py_DECREF(v);    }    return NULL; /* Signal to Python that an Exception is Pending */} #endif /* OS2 */ /* POSIX generic methods */ static PyObject *posix_fildes(PyObject *fdobj, int (*func)(int)){	int fd;	int res;	fd = PyObject_AsFileDescriptor(fdobj);	if (fd < 0)		return NULL;	Py_BEGIN_ALLOW_THREADS	res = (*func)(fd);	Py_END_ALLOW_THREADS	if (res < 0)		return posix_error();	Py_INCREF(Py_None);	return Py_None;} #ifdef Py_WIN_WIDE_FILENAMESstatic intunicode_file_names(void){	static int canusewide = -1;	if (canusewide == -1) {		/* As per doc for ::GetVersion(), this is the correct test for		   the Windows NT family. */		canusewide = (GetVersion() < 0x80000000) ? 1 : 0;	}	return canusewide;}#endif static PyObject *posix_1str(PyObject *args, char *format, int (*func)(const char*)){	char *path1 = NULL;	int res;	if (!PyArg_ParseTuple(args, format,	                      Py_FileSystemDefaultEncoding, &path1))		return NULL;	Py_BEGIN_ALLOW_THREADS	res = (*func)(path1);	Py_END_ALLOW_THREADS	if (res < 0)		return posix_error_with_allocated_filename(path1);	PyMem_Free(path1);	Py_INCREF(Py_None);	return Py_None;} static PyObject *posix_2str(PyObject *args,	   char *format,	   int (*func)(const char *, const char *)){	char *path1 = NULL, *path2 = NULL;	int res;	if (!PyArg_ParseTuple(args, format,	                      Py_FileSystemDefaultEncoding, &path1,	                      Py_FileSystemDefaultEncoding, &path2))		return NULL;	Py_BEGIN_ALLOW_THREADS	res = (*func)(path1, path2);	Py_END_ALLOW_THREADS	PyMem_Free(path1);	PyMem_Free(path2);	if (res != 0)		/* XXX how to report both path1 and path2??? */		return posix_error();	Py_INCREF(Py_None);	return Py_None;} #ifdef Py_WIN_WIDE_FILENAMESstatic PyObject*win32_1str(PyObject* args, char* func, 	   char* format, BOOL (__stdcall *funcA)(LPCSTR), 	   char* wformat, BOOL (__stdcall *funcW)(LPWSTR)){	PyObject *uni;	char *ansi;	BOOL result;	if (unicode_file_names()) {		if (!PyArg_ParseTuple(args, wformat, &uni))			PyErr_Clear();		else {			Py_BEGIN_ALLOW_THREADS			result = funcW(PyUnicode_AsUnicode(uni));			Py_END_ALLOW_THREADS			if (!result)				return win32_error_unicode(func, PyUnicode_AsUnicode(uni));			Py_INCREF(Py_None);			return Py_None;		}	}	if (!PyArg_ParseTuple(args, format, &ansi))		return NULL;	Py_BEGIN_ALLOW_THREADS	result = funcA(ansi);	Py_END_ALLOW_THREADS	if (!result)		return win32_error(func, ansi);	Py_INCREF(Py_None);	return Py_None; } /* This is a reimplementation of the C library's chdir function,   but one that produces Win32 errors instead of DOS error codes.   chdir is essentially a wrapper around SetCurrentDirectory; however,   it also needs to set "magic" environment variables indicating   the per-drive current directory, which are of the form =<drive>: */BOOL __stdcallwin32_chdir(LPCSTR path){	char new_path[MAX_PATH+1];	int result;	char env[4] = "=x:"; 	if(!SetCurrentDirectoryA(path))		return FALSE;	result = GetCurrentDirectoryA(MAX_PATH+1, new_path);	if (!result)		return FALSE;	/* In the ANSI API, there should not be any paths longer	   than MAX_PATH. */	assert(result <= MAX_PATH+1);	if (strncmp(new_path, "\\\\", 2) == 0 ||	    strncmp(new_path, "//", 2) == 0)	    /* UNC path, nothing to do. */	    return TRUE;	env[1] = new_path[0];	return SetEnvironmentVariableA(env, new_path);} /* The Unicode version differs from the ANSI version   since the current directory might exceed MAX_PATH characters */BOOL __stdcallwin32_wchdir(LPCWSTR path){	wchar_t _new_path[MAX_PATH+1], *new_path = _new_path;	int result;	wchar_t env[4] = L"=x:"; 	if(!SetCurrentDirectoryW(path))		return FALSE;	result = GetCurrentDirectoryW(MAX_PATH+1, new_path);	if (!result)		return FALSE;	if (result > MAX_PATH+1) {		new_path = malloc(result);		if (!new_path) {			SetLastError(ERROR_OUTOFMEMORY);			return FALSE;		}	}	if (wcsncmp(new_path, L"\\\\", 2) == 0 ||	    wcsncmp(new_path, L"//", 2) == 0)	    /* UNC path, nothing to do. */	    return TRUE;	env[1] = new_path[0];	result = SetEnvironmentVariableW(env, new_path);	if (new_path != _new_path)		free(new_path);	return result;}#endif #ifdef MS_WINDOWS/* The CRT of Windows has a number of flaws wrt. its stat() implementation:   - time stamps are restricted to second resolution   - file modification times suffer from forth-and-back conversions between     UTC and local time   Therefore, we implement our own stat, based on the Win32 API directly.*/#define HAVE_STAT_NSEC 1  struct win32_stat{    int st_dev;    __int64 st_ino;    unsigned short st_mode;    int st_nlink;    int st_uid;    int st_gid;    int st_rdev;    __int64 st_size;    int st_atime;    int st_atime_nsec;    int st_mtime;    int st_mtime_nsec;    int st_ctime;    int st_ctime_nsec;}; static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */ static voidFILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out){	/* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */	/* Cannot simply cast and dereference in_ptr, 	   since it might not be aligned properly */	__int64 in;	memcpy(&in, in_ptr, sizeof(in));	*nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */	/* XXX Win32 supports time stamps past 2038; we currently don't */	*time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);} static voidtime_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr){	/* XXX endianness */	__int64 out;	out = time_in + secs_between_epochs;	out = out * 10000000 + nsec_in / 100;	memcpy(out_ptr, &out, sizeof(out));} /* Below, we *know* that ugo+r is 0444 */#if _S_IREAD != 0400#error Unsupported C library#endifstatic intattributes_to_mode(DWORD attr){	int m = 0;	if (attr & FILE_ATTRIBUTE_DIRECTORY)		m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */	else		m |= _S_IFREG;	if (attr & FILE_ATTRIBUTE_READONLY)		m |= 0444;	else		m |= 0666;	return m;} static intattribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result){	memset(result, 0, sizeof(*result));	result->st_mode = attributes_to_mode(info->dwFileAttributes);	result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;	FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);	FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);	FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec); 	return 0;} /* Emulate GetFileAttributesEx[AW] on Windows 95 */static int checked = 0;static BOOL (CALLBACK *gfaxa)(LPCSTR, GET_FILEEX_INFO_LEVELS, LPVOID);static BOOL (CALLBACK *gfaxw)(LPCWSTR, GET_FILEEX_INFO_LEVELS, LPVOID);static voidcheck_gfax(){	HINSTANCE hKernel32;	if (checked)	    return;	checked = 1;	hKernel32 = GetModuleHandle("KERNEL32");	*(FARPROC*)&gfaxa = GetProcAddress(hKernel32, "GetFileAttributesExA");	*(FARPROC*)&gfaxw = GetProcAddress(hKernel32, "GetFileAttributesExW");} static BOOLattributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad){	HANDLE hFindFile;	WIN32_FIND_DATAA FileData;	hFindFile = FindFirstFileA(pszFile, &FileData);	if (hFindFile == INVALID_HANDLE_VALUE)		return FALSE;	FindClose(hFindFile);	pfad->dwFileAttributes = FileData.dwFileAttributes;	pfad->ftCreationTime   = FileData.ftCreationTime;	pfad->ftLastAccessTime = FileData.ftLastAccessTime;	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;	pfad->nFileSizeLow     = FileData.nFileSizeLow;	return TRUE;} static BOOLattributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad){	HANDLE hFindFile;	WIN32_FIND_DATAW FileData;	hFindFile = FindFirstFileW(pszFile, &FileData);	if (hFindFile == INVALID_HANDLE_VALUE)		return FALSE;	FindClose(hFindFile);	pfad->dwFileAttributes = FileData.dwFileAttributes;	pfad->ftCreationTime   = FileData.ftCreationTime;	pfad->ftLastAccessTime = FileData.ftLastAccessTime;	pfad->ftLastWriteTime  = FileData.ftLastWriteTime;	pfad->nFileSizeHigh    = FileData.nFileSizeHigh;	pfad->nFileSizeLow     = FileData.nFileSizeLow;	return TRUE;} static BOOL WINAPIPy_GetFileAttributesExA(LPCSTR pszFile, 		       GET_FILEEX_INFO_LEVELS level,                       LPVOID pv){	BOOL result;	LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;	/* First try to use the system's implementation, if that is	   available and either succeeds to gives an error other than	   that it isn't implemented. */	check_gfax();	if (gfaxa) {		result = gfaxa(pszFile, level, pv);		if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)			return result;	}	/* It's either not present, or not implemented.	   Emulate using FindFirstFile. */	if (level != GetFileExInfoStandard) {		SetLastError(ERROR_INVALID_PARAMETER);		return FALSE;	}	/* Use GetFileAttributes to validate that the file name	   does not contain wildcards (which FindFirstFile would	   accept). */	if (GetFileAttributesA(pszFile) == 0xFFFFFFFF)		return FALSE;	return attributes_from_dir(pszFile, pfad);} static BOOL WINAPIPy_GetFileAttributesExW(LPCWSTR pszFile, 		       GET_FILEEX_INFO_LEVELS level,                       LPVOID pv){	BOOL result;	LPWIN32_FILE_ATTRIBUTE_DATA pfad = pv;	/* First try to use the system's implementation, if that is	   available and either succeeds to gives an error other than	   that it isn't implemented. */	check_gfax();	if (gfaxa) {		result = gfaxw(pszFile, level, pv);		if (result || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)			return result;	}	/* It's either not present, or not implemented.	   Emulate using FindFirstFile. */	if (level != GetFileExInfoStandard) {		SetLastError(ERROR_INVALID_PARAMETER);		return FALSE;	}	/* Use GetFileAttributes to validate that the file name	   does not contain wildcards (which FindFirstFile would	   accept). */	if (GetFileAttributesW(pszFile) == 0xFFFFFFFF)		return FALSE;	return attributes_from_dir_w(pszFile, pfad);} static int win32_stat(const char* path, struct win32_stat *result){	WIN32_FILE_ATTRIBUTE_DATA info;	int code;	char *dot;	/* XXX not supported on Win95 and NT 3.x */	if (!Py_GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {		if (GetLastError() != ERROR_SHARING_VIOLATION) {			/* Protocol violation: we explicitly clear errno, instead of			   setting it to a POSIX error. Callers should use GetLastError. */			errno = 0;			return -1;		} else {			/* Could not get attributes on open file. Fall back to			   reading the directory. */			if (!attributes_from_dir(path, &info)) {				/* Very strange. This should not fail now */				errno = 0;				return -1;			}		}	}	code = attribute_data_to_stat(&info, result);	if (code != 0)		return code;	/* Set S_IFEXEC if it is an .exe, .bat, ... */	dot = strrchr(path, '.');	if (dot) {		if (stricmp(dot, ".bat") == 0 ||		stricmp(dot, ".cmd") == 0 ||		stricmp(dot, ".exe") == 0 ||		stricmp(dot, ".com") == 0)		result->st_mode |= 0111;	}	return code;} static int win32_wstat(const wchar_t* path, struct win32_stat *result){	int code;	const wchar_t *dot;	WIN32_FILE_ATTRIBUTE_DATA info;	/* XXX not supported on Win95 and NT 3.x */	if (!Py_GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {		if (GetLastError() != ERROR_SHARING_VIOLATION) {			/* Protocol violation: we explicitly clear errno, instead of			   setting it to a POSIX error. Callers should use GetLastError. */			errno = 0;			return -1;		} else {			/* Could not get attributes on open file. Fall back to			   reading the directory. */			if (!attributes_from_dir_w(path, &info)) {				/* Very strange. This should not fail now */				errno = 0;				return -1;

Lines 501–1000 of 8756. Previous lines

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t