Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/security/sandbox/linux/SandboxOpenedFiles.cpp
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
3
/* This Source Code Form is subject to the terms of the Mozilla Public
4
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7
#include "SandboxOpenedFiles.h"
8
9
#include "mozilla/Move.h"
10
#include "SandboxLogging.h"
11
12
#include <errno.h>
13
#include <fcntl.h>
14
#include <unistd.h>
15
16
namespace mozilla {
17
18
// The default move constructor almost works, but Atomic isn't
19
// move-constructable and the fd needs some special handling.
20
SandboxOpenedFile::SandboxOpenedFile(SandboxOpenedFile&& aMoved)
21
: mPath(std::move(aMoved.mPath))
22
, mMaybeFd(aMoved.TakeDesc())
23
, mDup(aMoved.mDup)
24
, mExpectError(aMoved.mExpectError)
25
0
{ }
26
27
SandboxOpenedFile::SandboxOpenedFile(const char* aPath, bool aDup)
28
  : mPath(aPath), mDup(aDup), mExpectError(false)
29
0
{
30
0
  MOZ_ASSERT(aPath[0] == '/', "path should be absolute");
31
0
32
0
  int fd = open(aPath, O_RDONLY | O_CLOEXEC);
33
0
  if (fd < 0) {
34
0
    mExpectError = true;
35
0
  }
36
0
  mMaybeFd = fd;
37
0
}
38
39
int
40
SandboxOpenedFile::GetDesc() const
41
0
{
42
0
  int fd;
43
0
  if (mDup) {
44
0
    fd = mMaybeFd;
45
0
    if (fd >= 0) {
46
0
      fd = dup(fd);
47
0
      if (fd < 0) {
48
0
        SANDBOX_LOG_ERROR("dup: %s", strerror(errno));
49
0
      }
50
0
    }
51
0
  } else {
52
0
    fd = TakeDesc();
53
0
  }
54
0
  if (fd < 0 && !mExpectError) {
55
0
    SANDBOX_LOG_ERROR("unexpected multiple open of file %s", Path());
56
0
  }
57
0
  return fd;
58
0
}
59
60
SandboxOpenedFile::~SandboxOpenedFile()
61
0
{
62
0
  int fd = TakeDesc();
63
0
  if (fd >= 0) {
64
0
    close(fd);
65
0
  }
66
0
}
67
68
int
69
SandboxOpenedFiles::GetDesc(const char* aPath) const
70
0
{
71
0
  for (const auto& file : mFiles) {
72
0
    if (strcmp(file.Path(), aPath) == 0) {
73
0
      return file.GetDesc();
74
0
    }
75
0
  }
76
0
  SANDBOX_LOG_ERROR("attempt to open unexpected file %s", aPath);
77
0
  return -1;
78
0
}
79
80
} // namespace mozilla