blob: b7d90795d3b4f82e880521fb08235d70bf7ce446 [file] [log] [blame]
bungeman@google.com6cab1a42013-05-29 13:43:31 +00001/*
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
bungeman@google.com11c9a552013-06-03 17:10:35 +000010#include "SkTemplates.h"
11
bungeman@google.com6cab1a42013-05-29 13:43:31 +000012#include <stdio.h>
13#include <sys/mman.h>
14#include <sys/stat.h>
15#include <sys/types.h>
16
17typedef struct {
18 dev_t dev;
19 ino_t ino;
20} SkFILEID;
21
22static bool sk_ino(SkFILE* a, SkFILEID* id) {
23 int fd = fileno((FILE*)a);
24 if (fd < 0) {
25 return 0;
26 }
27 struct stat status;
28 if (0 != fstat(fd, &status)) {
29 return 0;
30 }
31 id->dev = status.st_dev;
32 id->ino = status.st_ino;
33 return true;
34}
35
36bool sk_fidentical(SkFILE* a, SkFILE* b) {
37 SkFILEID aID, bID;
38 return sk_ino(a, &aID) && sk_ino(b, &bID)
39 && aID.ino == bID.ino
40 && aID.dev == bID.dev;
41}
42
43void sk_fmunmap(const void* addr, size_t length) {
44 munmap(const_cast<void*>(addr), length);
45}
46
bungeman@google.com11c9a552013-06-03 17:10:35 +000047void* sk_fdmmap(int fd, size_t* size) {
48 struct stat status;
49 if (0 != fstat(fd, &status)) {
bungeman@google.com6cab1a42013-05-29 13:43:31 +000050 return NULL;
51 }
bungeman@google.com11c9a552013-06-03 17:10:35 +000052 if (!S_ISREG(status.st_mode)) {
bungeman@google.com6cab1a42013-05-29 13:43:31 +000053 return NULL;
54 }
bungeman@google.com11c9a552013-06-03 17:10:35 +000055 if (!SkTFitsIn<size_t>(status.st_size)) {
56 return NULL;
57 }
58 size_t fileSize = static_cast<size_t>(status.st_size);
bungeman@google.com6cab1a42013-05-29 13:43:31 +000059
60 void* addr = mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
61 if (MAP_FAILED == addr) {
62 return NULL;
63 }
64
65 *size = fileSize;
66 return addr;
67}
bungeman@google.com11c9a552013-06-03 17:10:35 +000068
69int sk_fileno(SkFILE* f) {
70 return fileno((FILE*)f);
71}
72
73void* sk_fmmap(SkFILE* f, size_t* size) {
74 int fd = sk_fileno(f);
75 if (fd < 0) {
76 return NULL;
77 }
skia.committer@gmail.com11f2b442013-06-04 07:00:53 +000078
bungeman@google.com11c9a552013-06-03 17:10:35 +000079 return sk_fdmmap(fd, size);
80}