Backed out changeset b71c8c052463 (bug 1943846) for causing mass failures. CLOSED...
[gecko.git] / mozglue / baseprofiler / lul / AutoObjectMapper.cpp
blob0037c943aa7a54161e0a8e0acb24dbc548856d33
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/. */
7 #include <sys/mman.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
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) {
24 char buf[300];
25 SprintfLiteral(buf, "AutoObjectMapper::Map: Failed to %s \'%s\'", aHowFailed,
26 aFileName.c_str());
27 buf[sizeof(buf) - 1] = 0;
28 aLog(buf);
31 AutoObjectMapperPOSIX::AutoObjectMapperPOSIX(void (*aLog)(const char*))
32 : mImage(nullptr), mSize(0), mLog(aLog), mIsMapped(false) {}
34 AutoObjectMapperPOSIX::~AutoObjectMapperPOSIX() {
35 if (!mIsMapped) {
36 // There's nothing to do.
37 MOZ_ASSERT(!mImage);
38 MOZ_ASSERT(mSize == 0);
39 return;
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.
45 MOZ_ASSERT(mImage);
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);
54 if (fd == -1) {
55 failedToMessage(mLog, "open", fileName);
56 return false;
59 struct stat st;
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);
64 close(fd);
65 return false;
68 void* image = mmap(nullptr, sz, PROT_READ, MAP_SHARED, fd, 0);
69 if (image == MAP_FAILED) {
70 failedToMessage(mLog, "mmap", fileName);
71 close(fd);
72 return false;
75 close(fd);
76 mIsMapped = true;
77 mImage = *start = image;
78 mSize = *length = sz;
79 return true;