• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 The Android Open Source Project
2 //
3 // This software is licensed under the terms of the GNU General Public
4 // License version 2, as published by the Free Software Foundation, and
5 // may be copied, distributed, and modified under those terms.
6 //
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 // GNU General Public License for more details.
11 #include <io.h>
12 #include <share.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <windows.h>
17 
pread(int fd,void * buf,size_t count,off_t offset)18 ssize_t pread(int fd, void* buf, size_t count, off_t offset) {
19     if (fd < 0) {
20         errno = EINVAL;
21         return -1;
22     }
23     auto handle = (HANDLE)_get_osfhandle(fd);
24     if (handle == INVALID_HANDLE_VALUE) {
25         errno = EBADF;
26         return -1;
27     }
28 
29     DWORD cRead;
30     OVERLAPPED overlapped = {.OffsetHigh = (DWORD)((offset & 0xFFFFFFFF00000000LL) >> 32),
31                              .Offset = (DWORD)(offset & 0xFFFFFFFFLL)};
32     bool rd = ReadFile(handle, buf, count, &cRead, &overlapped);
33     if (!rd) {
34         auto err = GetLastError();
35         switch (err) {
36             case ERROR_IO_PENDING:
37                 errno = EAGAIN;
38                 break;
39             case ERROR_HANDLE_EOF:
40                 cRead = 0;
41                 errno = 0;
42                 return 0;
43             default:
44                 // Oh oh
45                 errno = EINVAL;
46         }
47         return -1;
48     }
49 
50     return cRead;
51 }