Home | History | Annotate | Download | only in ports
      1 /*
      2  * Copyright 2013 Google Inc.
      3  *
      4  * Use of this source code is governed by a BSD-style license that can be
      5  * found in the LICENSE file.
      6  */
      7 
      8 #include "SkOSFile.h"
      9 
     10 #include "SkTFitsIn.h"
     11 
     12 #include <stdio.h>
     13 #include <sys/mman.h>
     14 #include <sys/stat.h>
     15 #include <sys/types.h>
     16 #include <unistd.h>
     17 
     18 bool sk_exists(const char *path, SkFILE_Flags flags) {
     19     int mode = F_OK;
     20     if (flags & kRead_SkFILE_Flag) {
     21         mode |= R_OK;
     22     }
     23     if (flags & kWrite_SkFILE_Flag) {
     24         mode |= W_OK;
     25     }
     26     return (0 == access(path, mode));
     27 }
     28 
     29 typedef struct {
     30     dev_t dev;
     31     ino_t ino;
     32 } SkFILEID;
     33 
     34 static bool sk_ino(SkFILE* a, SkFILEID* id) {
     35     int fd = fileno((FILE*)a);
     36     if (fd < 0) {
     37         return 0;
     38     }
     39     struct stat status;
     40     if (0 != fstat(fd, &status)) {
     41         return 0;
     42     }
     43     id->dev = status.st_dev;
     44     id->ino = status.st_ino;
     45     return true;
     46 }
     47 
     48 bool sk_fidentical(SkFILE* a, SkFILE* b) {
     49     SkFILEID aID, bID;
     50     return sk_ino(a, &aID) && sk_ino(b, &bID)
     51            && aID.ino == bID.ino
     52            && aID.dev == bID.dev;
     53 }
     54 
     55 void sk_fmunmap(const void* addr, size_t length) {
     56     munmap(const_cast<void*>(addr), length);
     57 }
     58 
     59 void* sk_fdmmap(int fd, size_t* size) {
     60     struct stat status;
     61     if (0 != fstat(fd, &status)) {
     62         return NULL;
     63     }
     64     if (!S_ISREG(status.st_mode)) {
     65         return NULL;
     66     }
     67     if (!SkTFitsIn<size_t>(status.st_size)) {
     68         return NULL;
     69     }
     70     size_t fileSize = static_cast<size_t>(status.st_size);
     71 
     72     void* addr = mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
     73     if (MAP_FAILED == addr) {
     74         return NULL;
     75     }
     76 
     77     *size = fileSize;
     78     return addr;
     79 }
     80 
     81 int sk_fileno(SkFILE* f) {
     82     return fileno((FILE*)f);
     83 }
     84 
     85 void* sk_fmmap(SkFILE* f, size_t* size) {
     86     int fd = sk_fileno(f);
     87     if (fd < 0) {
     88         return NULL;
     89     }
     90 
     91     return sk_fdmmap(fd, size);
     92 }
     93