1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "courgette/memory_allocator.h"
12 #include "base/files/file_util.h"
13 #include "build/build_config.h"
21 // The file is created in the %TEMP% folder.
22 // NOTE: Since the file will be used as backing for a memory allocation,
23 // it will never be so big that size_t cannot represent its size.
24 base::File CreateTempFile() {
26 if (!base::CreateTemporaryFile(&path))
29 int flags = base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ |
30 base::File::FLAG_WRITE | base::File::FLAG_DELETE_ON_CLOSE |
31 base::File::FLAG_WIN_TEMPORARY;
32 return base::File(path, flags);
41 FileMapping::FileMapping() : mapping_(nullptr), view_(nullptr) {}
43 FileMapping::~FileMapping() {
47 bool FileMapping::InitializeView(size_t size) {
48 DCHECK(view_ == nullptr);
49 DCHECK(mapping_ != nullptr);
50 view_ = ::MapViewOfFile(mapping_, FILE_MAP_WRITE, 0, 0, size);
58 bool FileMapping::Create(HANDLE file, size_t size) {
59 DCHECK(file != INVALID_HANDLE_VALUE);
61 mapping_ = ::CreateFileMapping(file, nullptr, PAGE_READWRITE, 0, 0, nullptr);
65 return InitializeView(size);
68 void FileMapping::Close() {
70 ::UnmapViewOfFile(view_);
72 ::CloseHandle(mapping_);
77 bool FileMapping::valid() const {
78 return view_ != nullptr;
81 void* FileMapping::view() const {
87 TempMapping::TempMapping() {
90 TempMapping::~TempMapping() {
93 bool TempMapping::Initialize(size_t size) {
94 file_ = CreateTempFile();
98 // TODO(tommi): The assumption here is that the alignment of pointers (this)
99 // is as strict or stricter than the alignment of the element type. This is
100 // not always true, e.g. __m128 has 16-byte alignment.
101 size += sizeof(this);
102 if (!file_.SetLength(size) ||
103 !mapping_.Create(file_.GetPlatformFile(), size)) {
108 TempMapping** write = reinterpret_cast<TempMapping**>(mapping_.view());
114 void* TempMapping::memory() const {
115 uint8_t* mem = reinterpret_cast<uint8_t*>(mapping_.view());
116 // The 'this' pointer is written at the start of mapping_.view(), so
117 // go past it. (See Initialize()).
124 bool TempMapping::valid() const {
125 return mapping_.valid();
129 TempMapping* TempMapping::GetMappingFromPtr(void* mem) {
130 TempMapping* ret = nullptr;
132 ret = reinterpret_cast<TempMapping**>(mem)[-1];
138 } // namespace courgette
140 #endif // BUILDFLAG(IS_WIN)