pypy /pypy/translator/cli/src/ll_os.cs

Language C# Lines 581
MD5 Hash 8cb7a7397e10700d190a997e3a6deddd Estimated Cost $12,282 (why?)
Repository https://bitbucket.org/dac_io/pypy View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using pypy.runtime;

namespace pypy.builtin
{
    interface IFile
    {
        FileStream GetStream();
        void Write(string buffer);
        string Read(int count);
    }

    // this class is used only for stdin/stdout/stderr
    class TextFile: IFile
    {
        private FileStream stream;
        private TextWriter writer;
        private TextReader reader;
        public TextFile(FileStream stream, TextReader reader, TextWriter writer)
        {
            this.stream = stream;
            this.writer = writer;
            this.reader = reader;
        }
        
        public FileStream GetStream()
        {
            return stream;
        }

        public void Write(string buffer)
        {
            if (writer == null)
                Helpers.raise_OSError(Errno.EBADF);
            writer.Write(buffer);
        }
        
        public string Read(int count)
        {
            if (reader == null)
                Helpers.raise_OSError(Errno.EBADF);
            char[] buf = new char[count];
            int n = reader.Read(buf, 0, count);
            return new string(buf, 0, n);
        }
    }

    abstract class AbstractFile: IFile
    {
        protected FileStream stream;

        protected abstract string _Read(int count);
        protected abstract void _Write(string buffer);

        public AbstractFile(FileStream stream)
        {
            this.stream = stream;
        }

        public FileStream GetStream()
        {
            return stream;
        }

        public void Write(string buffer)
        {
            if (!stream.CanWrite)
                Helpers.raise_OSError(Errno.EBADF);
            _Write(buffer);
        }

        public string Read(int count)
        {
            if (!stream.CanRead)
                Helpers.raise_OSError(Errno.EBADF);
            return _Read(count);
        }
    }

    class CRLFTextFile: AbstractFile
    {
        public CRLFTextFile(FileStream stream): base(stream)
        {
        }
        
        protected override void _Write(string buffer)
        {
            foreach(char ch in buffer) {
                if (ch == '\n')
                    stream.WriteByte((byte)'\r');
                stream.WriteByte((byte)ch);
            }
        }

        protected override string _Read(int count)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder(count);
            bool pending_CR = false;
            while (count-- > 0) {
                int ch = stream.ReadByte();
                if (ch == -1)
                    break;
                else if (ch == '\r')
                    pending_CR = true;
                else {
                    if (pending_CR && ch != '\n')
                        builder.Append('\r');
                    builder.Append((char)ch);
                    pending_CR = false;
                }
            }
            return builder.ToString();
        }
    }

    class BinaryFile: AbstractFile
    {
        public BinaryFile(FileStream stream): base(stream)
        {
        }
        
        protected override void _Write(string buffer)
        {
            foreach(char ch in buffer)
                stream.WriteByte((byte)ch);
        }

        protected override string _Read(int count)
        {
             byte[] rawbuf = new byte[count];
             int n = stream.Read(rawbuf, 0, count);
             char[] buf = new char[count];
             for(int i=0; i<count; i++)
                 buf[i] = (char)rawbuf[i];
             return new string(buf, 0, n);
        }
    }

    public class ll_os
    {
        private static Dictionary<int, IFile> FileDescriptors;
        private static int fdcount;
        private static Dictionary<int, string> ErrorMessages;
        
        // NB: these values are those used by Windows and they differs
        // from the Unix ones; the os module is patched with these
        // values before flowgraphing to make sure we get the very
        // same values on each platform we do the compilation.
        private const int O_RDONLY = 0x0000;
        private const int O_WRONLY = 0x0001;
        private const int O_RDWR   = 0x0002;
        private const int O_APPEND = 0x0008;
        private const int O_CREAT  = 0x0100;
        private const int O_TRUNC  = 0x0200;
        private const int O_TEXT   = 0x4000;
        private const int O_BINARY = 0x8000;

        private const int S_IFMT = 61440;
        private const int S_IFDIR = 16384;
        private const int S_IFREG = 32768;

        static ll_os()
        {
            ErrorMessages = new Dictionary<int, string>();
            FileDescriptors = new Dictionary<int, IFile>();
            // XXX: what about CRLF conversion for stdin, stdout and stderr?
            // It seems that Posix let you read from stdout and
            // stderr, so pass Console.In to them, too.
            FileDescriptors[0] = new TextFile(null, Console.In, null);
            FileDescriptors[1] = new TextFile(null, Console.In, Console.Out);
            FileDescriptors[2] = new TextFile(null, Console.In, Console.Error);
            fdcount = 2; // 0, 1 and 2 are already used by stdin, stdout and stderr
        }

        private static void raise_OSError(int errno, string msg)
        {
            ErrorMessages[errno] = msg;
            Helpers.raise_OSError(errno);
        }

        public static string ll_os_strerror(int errno)
        {
            try {
                string msg = ErrorMessages[errno];
                ErrorMessages.Remove(errno);
                return msg;
            }
            catch(KeyNotFoundException e) {
                return "error " + errno;
            }
        }

        public static string ll_os_getcwd()
        {
            return System.IO.Directory.GetCurrentDirectory();
        }

        private static IFile getfd(int fd)
        {
            IFile f = FileDescriptors[fd];
            if (f == null)
                raise_OSError(Errno.EBADF, string.Format("Invalid file descriptor: {0}", fd));

            return f;
        }

        private static FileAccess get_file_access(int flags)
        {
            if ((flags & O_RDWR) != 0) return FileAccess.ReadWrite;
            if ((flags & O_WRONLY) != 0) return FileAccess.Write;
            return FileAccess.Read;
        }

        private static FileMode get_file_mode(int flags) {
            if ((flags & O_APPEND) !=0 ) return FileMode.Append;
            if ((flags & O_TRUNC) !=0 ) return FileMode.Create;
            if ((flags & O_CREAT) !=0 ) return FileMode.OpenOrCreate;
            return FileMode.Open;
        }

        public static int ll_os_open(string name, int flags, int mode)
        {
            FileAccess f_access = get_file_access(flags);
            FileMode f_mode = get_file_mode(flags);
            FileStream stream;
            IFile f;

            try {
                stream = new FileStream(name, f_mode, f_access, FileShare.ReadWrite);
            }
            catch(UnauthorizedAccessException e) {
                raise_OSError(Errno.EACCES, e.Message);
                return -1;
            }
            catch(FileNotFoundException e) {
                raise_OSError(Errno.ENOENT, e.Message);
                return -1;
            }
            catch(IOException e) {
                raise_OSError(Errno.EIO, e.Message);
                return -1;
            }

            // - on Unix there is no difference between text and binary modes
            // - on Windows text mode means that we should convert '\n' from and to '\r\n'
            // - on Mac < OS9 text mode means that we should convert '\n' from and to '\r' -- XXX: TODO!
            if ((flags & O_BINARY) == 0 && System.Environment.NewLine == "\r\n")
                f = new CRLFTextFile(stream);
            else
                f = new BinaryFile(stream);

            fdcount++;
            FileDescriptors[fdcount] = f;
            return fdcount;
        }

        public static void ll_os_close(int fd)
        {
            FileStream stream = getfd(fd).GetStream();
            if (stream != null)  // stdin/stdout/stderr files don't have a stream
                stream.Close();
            FileDescriptors.Remove(fd);
        }

        public static int ll_os_write(int fd, string buffer)
        {
            getfd(fd).Write(buffer);
            return buffer.Length;
        }

        /*
        private static void PrintString(string source, string s)
        {
            Console.Error.WriteLine(source);
            Console.Error.WriteLine(s);
            Console.Error.WriteLine("Length: {0}", s.Length);
            for (int i=0; i<s.Length; i++)
                Console.Error.Write("{0} ", (int)s[i]);
            Console.Error.WriteLine();
            Console.Error.WriteLine();
        }
        */

        public static string ll_os_read(int fd, long count)
        {
            return ll_os_read(fd, (int)count);
        }

        public static string ll_os_read(int fd, int count)
        {
            return getfd(fd).Read(count);
        }

        public static Record_Stat_Result ll_os_stat(string path)
        {
            if (path == "")
                raise_OSError(Errno.ENOENT, "No such file or directory: ''");

            FileInfo f;
            try {
                f = new FileInfo(path);
            }
            catch(System.ArgumentException e) {
                raise_OSError(Errno.EINVAL, e.Message);
                return null;
            }
            catch(System.NotSupportedException e) {
                raise_OSError(Errno.EINVAL, e.Message);
                return null;
            }
            catch(System.IO.IOException e) {
                raise_OSError(Errno.EINVAL, e.Message);
                return null;
            }

            if (f.Exists) {
                Record_Stat_Result res = new Record_Stat_Result();
                TimeSpan t = File.GetLastWriteTime(path) - new DateTime(1970, 1, 1);
                res.item0 ^= S_IFREG;
                res.item6 = (int)f.Length;
                res.item8 = (int)t.TotalSeconds;
                return res;
            }

            DirectoryInfo d = new DirectoryInfo(path);
            if (d.Exists) {
                Record_Stat_Result res = new Record_Stat_Result();
                res.item0 ^= S_IFDIR;
                return res;
            }
            // path is not a file nor a dir, raise OSError
            raise_OSError(Errno.ENOENT, string.Format("No such file or directory: '{0}'", path));
            return null; // never reached
        }

        public static Record_Stat_Result ll_os_fstat(int fd)
        {
            FileStream stream = getfd(fd).GetStream();
            return ll_os_stat(stream.Name);    // TODO: approximate only
        }

        public static Record_Stat_Result ll_os_lstat(string path)
        {
            return ll_os_stat(path);    // TODO
        }

        public static void ll_os_unlink(string path)
        {
            File.Delete(path);
        }

        public static void ll_os_putenv(string key, string value)
        {
            Environment.SetEnvironmentVariable(key, value);
        }

        public static string ll_os_getenv(string key)
        {
            return Environment.GetEnvironmentVariable(key);
        }

        public static void ll_os_unsetenv(string s)
        {
            Environment.SetEnvironmentVariable(s, null);
        }

        public static pypy.runtime.List<Record_String_String> ll_os_envitems()
        {
            pypy.runtime.List<Record_String_String> env = new pypy.runtime.List<Record_String_String>();
            foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
                {
                    Record_String_String var = new Record_String_String();
                    var.item0 = (string)entry.Key;
                    var.item1 = (string)entry.Value;
                    env.Add(var);
                }
            return env;
        }

        public static pypy.runtime.List<string> ll_os_envkeys()
        {
            pypy.runtime.List<string> keys = new pypy.runtime.List<string>();
            foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
                keys.Add((string)entry.Key);
            return keys;
        }
     
        public static long ll_os_lseek(int fd, long offset, int whence)
        {
            SeekOrigin origin = SeekOrigin.Begin;
            switch(whence)
                {
                case 0:
                    origin = SeekOrigin.Begin;
                    break;
                case 1:
                    origin = SeekOrigin.Current;
                    break;
                case 2:
                    origin = SeekOrigin.End;
                    break;
                }
            FileStream stream = getfd(fd).GetStream();
            return stream.Seek(offset, origin);
        }

        public static void ll_os__exit(int x)
        {
            Console.Error.WriteLine("WARNING: ll_os__exit has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static void ll_os_chdir(string s)
        {
            Console.Error.WriteLine("WARNING: ll_os_chdir has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static void ll_os_chmod(string s, int x)
        {
            Console.Error.WriteLine("WARNING: ll_os_chmod has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static int ll_os_dup(int x)
        {
            Console.Error.WriteLine("WARNING: ll_os_dup has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return -1;
        }

        public static void ll_os_dup2(int x, int y)
        {
            Console.Error.WriteLine("WARNING: ll_os_dup2 has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static int ll_os_fork()
        {
            Console.Error.WriteLine("WARNING: ll_os_fork has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return -1;
        }

        public static void ll_os_ftruncate(int x, int y)
        {
            Console.Error.WriteLine("WARNING: ll_os_ftruncate has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static int ll_os_getpid()
        {
            Console.Error.WriteLine("WARNING: ll_os_getpid has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return -1;
        }

        public static bool ll_os_isatty(int x)
        {
            // XXX: this is not the right behaviour, but it's needed
            // to have the interactive interpreter working
            if (x == 0 || x == 1 || x == 2)
                return true;
            else
                return false;
        }

        public static void ll_os_link(string s1, string s2)
        {
            Console.Error.WriteLine("WARNING: ll_os_link has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static void ll_os_mkdir(string s, int x)
        {
            Console.Error.WriteLine("WARNING: ll_os_mkdir has been called, but it's only a stub");
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static pypy.runtime.List<string> ll_os_listdir(string path)
        {
            if (path == "")
                Helpers.raise_OSError(Errno.ENOENT);

            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists)
                Helpers.raise_OSError(Errno.ENOENT);

            pypy.runtime.List<string> names = new pypy.runtime.List<string>();
            foreach(DirectoryInfo d in dir.GetDirectories())
                names.Add(d.Name);
            foreach(FileInfo f in dir.GetFiles())
                names.Add(f.Name);

            return names;
        }

        /* XXX old interface, will be removed at some point */
        public static object ll_os_opendir(string path)
        {
            if (path == "")
                Helpers.raise_OSError(Errno.ENOENT);

            DirectoryInfo dir = new DirectoryInfo(path);
            if (!dir.Exists)
                Helpers.raise_OSError(Errno.ENOENT);

            System.Collections.Generic.List<string> names = new System.Collections.Generic.List<string>();
            foreach(DirectoryInfo d in dir.GetDirectories())
                names.Add(d.Name);
            foreach(FileInfo f in dir.GetFiles())
                names.Add(f.Name);

            return names.GetEnumerator();
        }

        /* XXX old interface, will be removed at some point */
        public static string ll_os_readdir(object obj)
        {
            IEnumerator<string> names = (IEnumerator<string>)obj;
            if (names.MoveNext())
                return names.Current;
            else
                return null;
        }

        /* XXX old interface, will be removed at some point */
        public static void ll_os_closedir(object obj)
        {
        }

        public static string posix__getfullpathname(string path)
        {
            return System.IO.Path.GetFullPath(path);
        }

        public static Record_Signed_Signed ll_os_pipe()
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return null;
        }

        public static string ll_os_readlink(string s)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return null;
        }

        public static void ll_os_rename(string s1, string s2)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static void ll_os_rmdir(string s)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static void ll_os_symlink(string s1, string s2)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
        }

        public static int ll_os_system(string s)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return -1;
        }

        public static Record_Signed_Signed ll_os_waitpid(int x, int y)
        {
            Helpers.raise_OSError(Errno.EPERM); // this is only a stub
            return null;
        }
    }
}
Back to Top