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
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
13 #include "mozilla/Assertions.h"
14 #include "mozilla/Sprintf.h"
16 #include "BaseProfiler.h"
17 #include "PlatformMacros.h"
18 #include "AutoObjectMapper.h"
20 // A helper function for creating failure error messages in
21 // AutoObjectMapper*::Map.
22 static void failedToMessage(void (*aLog
)(const char*), const char* aHowFailed
,
23 std::string aFileName
) {
25 SprintfLiteral(buf
, "AutoObjectMapper::Map: Failed to %s \'%s\'", aHowFailed
,
27 buf
[sizeof(buf
) - 1] = 0;
31 AutoObjectMapperPOSIX::AutoObjectMapperPOSIX(void (*aLog
)(const char*))
32 : mImage(nullptr), mSize(0), mLog(aLog
), mIsMapped(false) {}
34 AutoObjectMapperPOSIX::~AutoObjectMapperPOSIX() {
36 // There's nothing to do.
38 MOZ_ASSERT(mSize
== 0);
41 MOZ_ASSERT(mSize
> 0);
42 // The following assertion doesn't necessarily have to be true,
43 // but we assume (reasonably enough) that no mmap facility would
44 // be crazy enough to map anything at page zero.
46 munmap(mImage
, mSize
);
49 bool AutoObjectMapperPOSIX::Map(/*OUT*/ void** start
, /*OUT*/ size_t* length
,
50 std::string fileName
) {
51 MOZ_ASSERT(!mIsMapped
);
53 int fd
= open(fileName
.c_str(), O_RDONLY
);
55 failedToMessage(mLog
, "open", fileName
);
60 int err
= fstat(fd
, &st
);
61 size_t sz
= (err
== 0) ? st
.st_size
: 0;
62 if (err
!= 0 || sz
== 0) {
63 failedToMessage(mLog
, "fstat", fileName
);
68 void* image
= mmap(nullptr, sz
, PROT_READ
, MAP_SHARED
, fd
, 0);
69 if (image
== MAP_FAILED
) {
70 failedToMessage(mLog
, "mmap", fileName
);
77 mImage
= *start
= image
;