• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Flutter 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 "runtime/dart/utils/vmo.h"
6 
7 #include <fcntl.h>
8 #include <sys/stat.h>
9 
10 #include <fuchsia/mem/cpp/fidl.h>
11 #include <lib/fdio/io.h>
12 #include <lib/syslog/global.h>
13 
14 #include "runtime/dart/utils/logging.h"
15 
16 namespace {
17 
VmoFromFd(int fd,fuchsia::mem::Buffer * buffer)18 bool VmoFromFd(int fd, fuchsia::mem::Buffer* buffer) {
19   if (!buffer) {
20     FX_LOG(FATAL, LOG_TAG, "Invalid buffer pointer");
21   }
22 
23   struct stat stat_struct;
24   if (fstat(fd, &stat_struct) == -1) {
25     FX_LOGF(ERROR, LOG_TAG, "fstat failed: %s", strerror(errno));
26     return false;
27   }
28 
29   zx_handle_t result = ZX_HANDLE_INVALID;
30   if (fdio_get_vmo_copy(fd, &result) != ZX_OK) {
31     return false;
32   }
33 
34   buffer->vmo = zx::vmo(result);
35   buffer->size = stat_struct.st_size;
36 
37   return true;
38 }
39 
40 }  // namespace
41 
42 namespace dart_utils {
43 
VmoFromFilename(const std::string & filename,fuchsia::mem::Buffer * buffer)44 bool VmoFromFilename(const std::string& filename,
45                      fuchsia::mem::Buffer* buffer) {
46   return VmoFromFilenameAt(AT_FDCWD, filename, buffer);
47 }
48 
VmoFromFilenameAt(int dirfd,const std::string & filename,fuchsia::mem::Buffer * buffer)49 bool VmoFromFilenameAt(int dirfd,
50                        const std::string& filename,
51                        fuchsia::mem::Buffer* buffer) {
52   int fd = openat(dirfd, filename.c_str(), O_RDONLY);
53   if (fd == -1) {
54     FX_LOGF(ERROR, LOG_TAG, "openat(\"%s\") failed: %s", filename.c_str(),
55             strerror(errno));
56     return false;
57   }
58   bool result = VmoFromFd(fd, buffer);
59   close(fd);
60   return result;
61 }
62 
IsSizeValid(const fuchsia::mem::Buffer & buffer,bool * is_valid)63 zx_status_t IsSizeValid(const fuchsia::mem::Buffer& buffer, bool* is_valid) {
64   size_t vmo_size;
65   zx_status_t status = buffer.vmo.get_size(&vmo_size);
66   if (status == ZX_OK) {
67     *is_valid = vmo_size >= buffer.size;
68   } else {
69     *is_valid = false;
70   }
71   return status;
72 }
73 
74 }  // namespace dart_utils
75