gfx/skia/trunk/src/ports/SkOSFile_posix.cpp
author George Wright <george@mozilla.com>
Mon, 28 Jul 2014 15:06:12 -0400
changeset 220765 883cd6be06d294600562435ebea87d2804bca957
parent 186600 3f5e3a855a3d1afe36142b581637498bb5aeba39
permissions -rw-r--r--
[PATCH 08/15] Bug 1017113 - Update Skia to 2014-07-28 r=upstream

/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkOSFile.h"

#include "SkTFitsIn.h"

#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

bool sk_exists(const char *path, SkFILE_Flags flags) {
    int mode = F_OK;
    if (flags & kRead_SkFILE_Flag) {
        mode |= R_OK;
    }
    if (flags & kWrite_SkFILE_Flag) {
        mode |= W_OK;
    }
    return (0 == access(path, mode));
}

typedef struct {
    dev_t dev;
    ino_t ino;
} SkFILEID;

static bool sk_ino(SkFILE* a, SkFILEID* id) {
    int fd = fileno((FILE*)a);
    if (fd < 0) {
        return 0;
    }
    struct stat status;
    if (0 != fstat(fd, &status)) {
        return 0;
    }
    id->dev = status.st_dev;
    id->ino = status.st_ino;
    return true;
}

bool sk_fidentical(SkFILE* a, SkFILE* b) {
    SkFILEID aID, bID;
    return sk_ino(a, &aID) && sk_ino(b, &bID)
           && aID.ino == bID.ino
           && aID.dev == bID.dev;
}

void sk_fmunmap(const void* addr, size_t length) {
    munmap(const_cast<void*>(addr), length);
}

void* sk_fdmmap(int fd, size_t* size) {
    struct stat status;
    if (0 != fstat(fd, &status)) {
        return NULL;
    }
    if (!S_ISREG(status.st_mode)) {
        return NULL;
    }
    if (!SkTFitsIn<size_t>(status.st_size)) {
        return NULL;
    }
    size_t fileSize = static_cast<size_t>(status.st_size);

    void* addr = mmap(NULL, fileSize, PROT_READ, MAP_PRIVATE, fd, 0);
    if (MAP_FAILED == addr) {
        return NULL;
    }

    *size = fileSize;
    return addr;
}

int sk_fileno(SkFILE* f) {
    return fileno((FILE*)f);
}

void* sk_fmmap(SkFILE* f, size_t* size) {
    int fd = sk_fileno(f);
    if (fd < 0) {
        return NULL;
    }

    return sk_fdmmap(fd, size);
}