1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <sys/stat.h>
6#include <sys/types.h>
7#include <unistd.h>
8#include <cstring>
9
10#include "base/logging.h"
11#include "native_client/src/trusted/service_runtime/include/sys/stat.h"
12#include "native_client/src/trusted/service_runtime/include/sys/time.h"
13
14namespace nacl {
15namespace nonsfi {
16
17void NaClAbiTimeSpecToTimeSpec(const struct nacl_abi_timespec& nacl_timespec,
18                               struct timespec* host_timespec) {
19  host_timespec->tv_sec = nacl_timespec.tv_sec;
20  host_timespec->tv_nsec = nacl_timespec.tv_nsec;
21}
22
23void TimeSpecToNaClAbiTimeSpec(const struct timespec& host_timespec,
24                               struct nacl_abi_timespec* nacl_timespec) {
25  nacl_timespec->tv_sec = host_timespec.tv_sec;
26  nacl_timespec->tv_nsec = host_timespec.tv_nsec;
27}
28
29void StatToNaClAbiStat(
30    const struct stat& host_stat, struct nacl_abi_stat* nacl_stat) {
31  // Some fields in host_stat, such as st_dev, group/other bits of mode and
32  // (a,m,c)timensec, are ignored to sync with the NaCl's original
33  // implementation. Please see also NaClAbiStatHostDescStatXlateCtor in
34  // native_client/src/trusted/desc/posix/nacl_desc.c.
35  std::memset(nacl_stat, 0, sizeof(*nacl_stat));
36  nacl_stat->nacl_abi_st_dev = 0;
37  nacl_stat->nacl_abi_st_ino = host_stat.st_ino;
38  nacl_abi_mode_t mode;
39  switch (host_stat.st_mode & S_IFMT) {
40    case S_IFREG:
41      mode = NACL_ABI_S_IFREG;
42      break;
43    case S_IFDIR:
44      mode = NACL_ABI_S_IFDIR;
45      break;
46    case S_IFCHR:
47      mode = NACL_ABI_S_IFCHR;
48      break;
49    default:
50      LOG(WARNING) << "Unusual NaCl descriptor type: "
51                   << (host_stat.st_mode & S_IFMT);
52      mode = NACL_ABI_S_UNSUP;
53  }
54  if (host_stat.st_mode & S_IRUSR)
55    mode |= NACL_ABI_S_IRUSR;
56  if (host_stat.st_mode & S_IWUSR)
57    mode |= NACL_ABI_S_IWUSR;
58  if (host_stat.st_mode & S_IXUSR)
59    mode |= NACL_ABI_S_IXUSR;
60  nacl_stat->nacl_abi_st_mode = mode;
61  nacl_stat->nacl_abi_st_nlink = host_stat.st_nlink;
62  nacl_stat->nacl_abi_st_uid = -1;  // Not root
63  nacl_stat->nacl_abi_st_gid = -1;  // Not wheel
64  nacl_stat->nacl_abi_st_rdev = 0;
65  nacl_stat->nacl_abi_st_size = host_stat.st_size;
66  nacl_stat->nacl_abi_st_blksize = 0;
67  nacl_stat->nacl_abi_st_blocks = 0;
68  nacl_stat->nacl_abi_st_atime = host_stat.st_atime;
69  nacl_stat->nacl_abi_st_mtime = host_stat.st_mtime;
70  nacl_stat->nacl_abi_st_ctime = host_stat.st_ctime;
71}
72
73}  // namespace nonsfi
74}  // namespace nacl
75