Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 : /* vim: set ts=8 sts=4 et sw=4 tw=99: */
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
5 : * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 :
7 : #include "AutoMemMap.h"
8 : #include "ScriptPreloader-inl.h"
9 :
10 : #include "mozilla/Unused.h"
11 : #include "nsIFile.h"
12 :
13 : #include <private/pprio.h>
14 :
15 : namespace mozilla {
16 : namespace loader {
17 :
18 : using namespace mozilla::ipc;
19 :
20 202 : AutoMemMap::~AutoMemMap()
21 : {
22 101 : if (fileMap) {
23 101 : if (addr) {
24 101 : Unused << NS_WARN_IF(PR_MemUnmap(addr, size()) != PR_SUCCESS);
25 101 : addr = nullptr;
26 : }
27 :
28 101 : Unused << NS_WARN_IF(PR_CloseFileMap(fileMap) != PR_SUCCESS);
29 101 : fileMap = nullptr;
30 : }
31 101 : }
32 :
33 : FileDescriptor
34 2 : AutoMemMap::cloneFileDescriptor()
35 : {
36 2 : if (fd.get()) {
37 2 : auto handle = FileDescriptor::PlatformHandleType(PR_FileDesc2NativeHandle(fd.get()));
38 2 : return FileDescriptor(handle);
39 : }
40 0 : return FileDescriptor();
41 : }
42 :
43 : Result<Ok, nsresult>
44 103 : AutoMemMap::init(nsIFile* file, int flags, int mode, PRFileMapProtect prot)
45 : {
46 103 : MOZ_ASSERT(!fd);
47 :
48 103 : NS_TRY(file->OpenNSPRFileDesc(flags, mode, &fd.rwget()));
49 :
50 103 : return initInternal(prot);
51 : }
52 :
53 : Result<Ok, nsresult>
54 2 : AutoMemMap::init(const FileDescriptor& file)
55 : {
56 2 : MOZ_ASSERT(!fd);
57 2 : if (!file.IsValid()) {
58 0 : return Err(NS_ERROR_INVALID_ARG);
59 : }
60 :
61 4 : auto handle = file.ClonePlatformHandle();
62 :
63 2 : fd = PR_ImportFile(PROsfd(handle.get()));
64 2 : if (!fd) {
65 0 : return Err(NS_ERROR_FAILURE);
66 : }
67 2 : Unused << handle.release();
68 :
69 2 : return initInternal();
70 : }
71 :
72 : Result<Ok, nsresult>
73 105 : AutoMemMap::initInternal(PRFileMapProtect prot)
74 : {
75 105 : MOZ_ASSERT(!fileMap);
76 105 : MOZ_ASSERT(!addr);
77 :
78 : PRFileInfo64 fileInfo;
79 105 : NS_TRY(PR_GetOpenFileInfo64(fd.get(), &fileInfo));
80 :
81 105 : if (fileInfo.size > UINT32_MAX)
82 0 : return Err(NS_ERROR_INVALID_ARG);
83 :
84 105 : fileMap = PR_CreateFileMap(fd, 0, prot);
85 105 : if (!fileMap)
86 0 : return Err(NS_ERROR_FAILURE);
87 :
88 105 : size_ = fileInfo.size;
89 105 : addr = PR_MemMap(fileMap, 0, size_);
90 105 : if (!addr)
91 0 : return Err(NS_ERROR_FAILURE);
92 :
93 105 : return Ok();
94 : }
95 :
96 : } // namespace loader
97 : } // namespace mozilla
|