1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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"
9 #include "base/file_util.h"
10 #include "base/strings/stringprintf.h"
18 TempFile::TempFile() : file_(base::kInvalidPlatformFileValue
) {
21 TempFile::~TempFile() {
25 void TempFile::Close() {
27 base::ClosePlatformFile(file_
);
28 file_
= base::kInvalidPlatformFileValue
;
32 bool TempFile::Create() {
33 DCHECK(file_
== base::kInvalidPlatformFileValue
);
35 if (!file_util::CreateTemporaryFile(&path
))
39 base::PlatformFileError error_code
= base::PLATFORM_FILE_OK
;
40 int flags
= base::PLATFORM_FILE_OPEN_ALWAYS
| base::PLATFORM_FILE_READ
|
41 base::PLATFORM_FILE_WRITE
|
42 base::PLATFORM_FILE_DELETE_ON_CLOSE
|
43 base::PLATFORM_FILE_TEMPORARY
;
44 file_
= base::CreatePlatformFile(path
, flags
, &created
, &error_code
);
45 if (file_
== base::kInvalidPlatformFileValue
)
51 bool TempFile::valid() const {
52 return file_
!= base::kInvalidPlatformFileValue
;
55 base::PlatformFile
TempFile::handle() const {
59 bool TempFile::SetSize(size_t size
) {
60 return base::TruncatePlatformFile(file_
, size
);
65 FileMapping::FileMapping() : mapping_(NULL
), view_(NULL
) {
68 FileMapping::~FileMapping() {
72 bool FileMapping::InitializeView(size_t size
) {
73 DCHECK(view_
== NULL
);
74 DCHECK(mapping_
!= NULL
);
75 view_
= ::MapViewOfFile(mapping_
, FILE_MAP_WRITE
, 0, 0, size
);
83 bool FileMapping::Create(HANDLE file
, size_t size
) {
84 DCHECK(file
!= INVALID_HANDLE_VALUE
);
86 mapping_
= ::CreateFileMapping(file
, NULL
, PAGE_READWRITE
, 0, 0, NULL
);
90 return InitializeView(size
);
93 void FileMapping::Close() {
95 ::UnmapViewOfFile(view_
);
97 ::CloseHandle(mapping_
);
102 bool FileMapping::valid() const {
103 return view_
!= NULL
;
106 void* FileMapping::view() const {
112 TempMapping::TempMapping() {
115 TempMapping::~TempMapping() {
118 bool TempMapping::Initialize(size_t size
) {
119 // TODO(tommi): The assumption here is that the alignment of pointers (this)
120 // is as strict or stricter than the alignment of the element type. This is
121 // not always true, e.g. __m128 has 16-byte alignment.
122 size
+= sizeof(this);
123 if (!file_
.Create() ||
124 !file_
.SetSize(size
) ||
125 !mapping_
.Create(file_
.handle(), size
)) {
130 TempMapping
** write
= reinterpret_cast<TempMapping
**>(mapping_
.view());
136 void* TempMapping::memory() const {
137 uint8
* mem
= reinterpret_cast<uint8
*>(mapping_
.view());
138 // The 'this' pointer is written at the start of mapping_.view(), so
139 // go past it. (See Initialize()).
146 bool TempMapping::valid() const {
147 return mapping_
.valid();
151 TempMapping
* TempMapping::GetMappingFromPtr(void* mem
) {
152 TempMapping
* ret
= NULL
;
154 ret
= reinterpret_cast<TempMapping
**>(mem
)[-1];
160 } // namespace courgette