2010-02-13 Jb Evain <jbevain@novell.com>
[mono-project.git] / mono / io-layer / posix.c
blob732529039ce58ab588e8d7d554e368074fdaf7f1
1 /*
2 * posix.c: Posix-specific support.
4 * Author:
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
8 * Copyright (c) 2002-2009 Novell, Inc.
9 */
11 #include <config.h>
12 #include <glib.h>
13 #include <fcntl.h>
14 #include <unistd.h>
15 #include <errno.h>
16 #include <string.h>
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 #include <stdio.h>
21 #include <mono/io-layer/wapi.h>
22 #include <mono/io-layer/wapi-private.h>
23 #include <mono/io-layer/handles-private.h>
24 #include <mono/io-layer/io-private.h>
26 static guint32
27 convert_from_flags(int flags)
29 guint32 fileaccess=0;
31 #ifndef O_ACCMODE
32 #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
33 #endif
35 if((flags & O_ACCMODE) == O_RDONLY) {
36 fileaccess=GENERIC_READ;
37 } else if ((flags & O_ACCMODE) == O_WRONLY) {
38 fileaccess=GENERIC_WRITE;
39 } else if ((flags & O_ACCMODE) == O_RDWR) {
40 fileaccess=GENERIC_READ|GENERIC_WRITE;
41 } else {
42 #ifdef DEBUG
43 g_message("%s: Can't figure out flags 0x%x", __func__, flags);
44 #endif
47 /* Maybe sort out create mode too */
49 return(fileaccess);
53 gpointer _wapi_stdhandle_create (int fd, const gchar *name)
55 struct _WapiHandle_file file_handle = {0};
56 gpointer handle;
57 int flags;
59 #ifdef DEBUG
60 g_message("%s: creating standard handle type %s, fd %d", __func__,
61 name, fd);
62 #endif
64 /* Check if fd is valid */
65 do {
66 flags=fcntl(fd, F_GETFL);
67 } while (flags == -1 && errno == EINTR);
69 if(flags==-1) {
70 /* Invalid fd. Not really much point checking for EBADF
71 * specifically
73 #ifdef DEBUG
74 g_message("%s: fcntl error on fd %d: %s", __func__, fd,
75 strerror(errno));
76 #endif
78 SetLastError (_wapi_get_win32_file_error (errno));
79 return(INVALID_HANDLE_VALUE);
82 file_handle.filename = g_strdup(name);
83 /* some default security attributes might be needed */
84 file_handle.security_attributes=0;
85 file_handle.fileaccess=convert_from_flags(flags);
87 /* Apparently input handles can't be written to. (I don't
88 * know if output or error handles can't be read from.)
90 if (fd == 0) {
91 file_handle.fileaccess &= ~GENERIC_WRITE;
94 file_handle.sharemode=0;
95 file_handle.attrs=0;
97 handle = _wapi_handle_new_fd (WAPI_HANDLE_CONSOLE, fd, &file_handle);
98 if (handle == _WAPI_HANDLE_INVALID) {
99 g_warning ("%s: error creating file handle", __func__);
100 SetLastError (ERROR_GEN_FAILURE);
101 return(INVALID_HANDLE_VALUE);
104 #ifdef DEBUG
105 g_message("%s: returning handle %p", __func__, handle);
106 #endif
108 return(handle);