blob: 4786fb4dd9d799219f32b6ea8effa0a90a8a2ffe [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_SPACES_H_
29#define V8_SPACES_H_
30
31#include "list-inl.h"
32#include "log.h"
33
34namespace v8 {
35namespace internal {
36
37// -----------------------------------------------------------------------------
38// Heap structures:
39//
40// A JS heap consists of a young generation, an old generation, and a large
41// object space. The young generation is divided into two semispaces. A
42// scavenger implements Cheney's copying algorithm. The old generation is
43// separated into a map space and an old object space. The map space contains
44// all (and only) map objects, the rest of old objects go into the old space.
45// The old generation is collected by a mark-sweep-compact collector.
46//
47// The semispaces of the young generation are contiguous. The old and map
48// spaces consists of a list of pages. A page has a page header, a remembered
49// set area, and an object area. A page size is deliberately chosen as 8K
50// bytes. The first word of a page is an opaque page header that has the
51// address of the next page and its ownership information. The second word may
52// have the allocation top address of this page. The next 248 bytes are
53// remembered sets. Heap objects are aligned to the pointer size (4 bytes). A
54// remembered set bit corresponds to a pointer in the object area.
55//
56// There is a separate large object space for objects larger than
57// Page::kMaxHeapObjectSize, so that they do not have to move during
58// collection. The large object space is paged and uses the same remembered
59// set implementation. Pages in large object space may be larger than 8K.
60//
61// NOTE: The mark-compact collector rebuilds the remembered set after a
62// collection. It reuses first a few words of the remembered set for
63// bookkeeping relocation information.
64
65
66// Some assertion macros used in the debugging mode.
67
Leon Clarkee46be812010-01-19 14:06:41 +000068#define ASSERT_PAGE_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000069 ASSERT((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
70
Leon Clarkee46be812010-01-19 14:06:41 +000071#define ASSERT_OBJECT_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000072 ASSERT((OffsetFrom(address) & kObjectAlignmentMask) == 0)
73
Leon Clarkee46be812010-01-19 14:06:41 +000074#define ASSERT_MAP_ALIGNED(address) \
75 ASSERT((OffsetFrom(address) & kMapAlignmentMask) == 0)
76
77#define ASSERT_OBJECT_SIZE(size) \
Steve Blocka7e24c12009-10-30 11:49:00 +000078 ASSERT((0 < size) && (size <= Page::kMaxHeapObjectSize))
79
Leon Clarkee46be812010-01-19 14:06:41 +000080#define ASSERT_PAGE_OFFSET(offset) \
81 ASSERT((Page::kObjectStartOffset <= offset) \
Steve Blocka7e24c12009-10-30 11:49:00 +000082 && (offset <= Page::kPageSize))
83
Leon Clarkee46be812010-01-19 14:06:41 +000084#define ASSERT_MAP_PAGE_INDEX(index) \
Steve Blocka7e24c12009-10-30 11:49:00 +000085 ASSERT((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
86
87
88class PagedSpace;
89class MemoryAllocator;
90class AllocationInfo;
91
92// -----------------------------------------------------------------------------
93// A page normally has 8K bytes. Large object pages may be larger. A page
94// address is always aligned to the 8K page size. A page is divided into
95// three areas: the first two words are used for bookkeeping, the next 248
96// bytes are used as remembered set, and the rest of the page is the object
97// area.
98//
99// Pointers are aligned to the pointer size (4), only 1 bit is needed
100// for a pointer in the remembered set. Given an address, its remembered set
101// bit position (offset from the start of the page) is calculated by dividing
102// its page offset by 32. Therefore, the object area in a page starts at the
103// 256th byte (8K/32). Bytes 0 to 255 do not need the remembered set, so that
104// the first two words (64 bits) in a page can be used for other purposes.
105//
106// On the 64-bit platform, we add an offset to the start of the remembered set,
107// and pointers are aligned to 8-byte pointer size. This means that we need
108// only 128 bytes for the RSet, and only get two bytes free in the RSet's RSet.
109// For this reason we add an offset to get room for the Page data at the start.
110//
111// The mark-compact collector transforms a map pointer into a page index and a
Leon Clarkee46be812010-01-19 14:06:41 +0000112// page offset. The excact encoding is described in the comments for
113// class MapWord in objects.h.
Steve Blocka7e24c12009-10-30 11:49:00 +0000114//
115// The only way to get a page pointer is by calling factory methods:
116// Page* p = Page::FromAddress(addr); or
117// Page* p = Page::FromAllocationTop(top);
118class Page {
119 public:
120 // Returns the page containing a given address. The address ranges
121 // from [page_addr .. page_addr + kPageSize[
122 //
123 // Note that this function only works for addresses in normal paged
124 // spaces and addresses in the first 8K of large object pages (i.e.,
125 // the start of large objects but not necessarily derived pointers
126 // within them).
127 INLINE(static Page* FromAddress(Address a)) {
128 return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
129 }
130
131 // Returns the page containing an allocation top. Because an allocation
132 // top address can be the upper bound of the page, we need to subtract
133 // it with kPointerSize first. The address ranges from
134 // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
135 INLINE(static Page* FromAllocationTop(Address top)) {
136 Page* p = FromAddress(top - kPointerSize);
137 ASSERT_PAGE_OFFSET(p->Offset(top));
138 return p;
139 }
140
141 // Returns the start address of this page.
142 Address address() { return reinterpret_cast<Address>(this); }
143
144 // Checks whether this is a valid page address.
145 bool is_valid() { return address() != NULL; }
146
147 // Returns the next page of this page.
148 inline Page* next_page();
149
150 // Return the end of allocation in this page. Undefined for unused pages.
151 inline Address AllocationTop();
152
153 // Returns the start address of the object area in this page.
154 Address ObjectAreaStart() { return address() + kObjectStartOffset; }
155
156 // Returns the end address (exclusive) of the object area in this page.
157 Address ObjectAreaEnd() { return address() + Page::kPageSize; }
158
159 // Returns the start address of the remembered set area.
160 Address RSetStart() { return address() + kRSetStartOffset; }
161
162 // Returns the end address of the remembered set area (exclusive).
163 Address RSetEnd() { return address() + kRSetEndOffset; }
164
165 // Checks whether an address is page aligned.
166 static bool IsAlignedToPageSize(Address a) {
167 return 0 == (OffsetFrom(a) & kPageAlignmentMask);
168 }
169
170 // True if this page is a large object page.
171 bool IsLargeObjectPage() { return (is_normal_page & 0x1) == 0; }
172
173 // Returns the offset of a given address to this page.
174 INLINE(int Offset(Address a)) {
Steve Blockd0582a62009-12-15 09:54:21 +0000175 int offset = static_cast<int>(a - address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000176 ASSERT_PAGE_OFFSET(offset);
177 return offset;
178 }
179
180 // Returns the address for a given offset to the this page.
181 Address OffsetToAddress(int offset) {
182 ASSERT_PAGE_OFFSET(offset);
183 return address() + offset;
184 }
185
186 // ---------------------------------------------------------------------
187 // Remembered set support
188
189 // Clears remembered set in this page.
190 inline void ClearRSet();
191
192 // Return the address of the remembered set word corresponding to an
193 // object address/offset pair, and the bit encoded as a single-bit
194 // mask in the output parameter 'bitmask'.
195 INLINE(static Address ComputeRSetBitPosition(Address address, int offset,
196 uint32_t* bitmask));
197
198 // Sets the corresponding remembered set bit for a given address.
199 INLINE(static void SetRSet(Address address, int offset));
200
201 // Clears the corresponding remembered set bit for a given address.
202 static inline void UnsetRSet(Address address, int offset);
203
204 // Checks whether the remembered set bit for a given address is set.
205 static inline bool IsRSetSet(Address address, int offset);
206
207#ifdef DEBUG
208 // Use a state to mark whether remembered set space can be used for other
209 // purposes.
210 enum RSetState { IN_USE, NOT_IN_USE };
211 static bool is_rset_in_use() { return rset_state_ == IN_USE; }
212 static void set_rset_state(RSetState state) { rset_state_ = state; }
213#endif
214
Steve Blocka7e24c12009-10-30 11:49:00 +0000215 // Page size in bytes. This must be a multiple of the OS page size.
216 static const int kPageSize = 1 << kPageSizeBits;
217
218 // Page size mask.
219 static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
220
221 // The offset of the remembered set in a page, in addition to the empty bytes
222 // formed as the remembered bits of the remembered set itself.
223#ifdef V8_TARGET_ARCH_X64
224 static const int kRSetOffset = 4 * kPointerSize; // Room for four pointers.
225#else
226 static const int kRSetOffset = 0;
227#endif
228 // The end offset of the remembered set in a page
229 // (heaps are aligned to pointer size).
230 static const int kRSetEndOffset = kRSetOffset + kPageSize / kBitsPerPointer;
231
232 // The start offset of the object area in a page.
233 // This needs to be at least (bits per uint32_t) * kBitsPerPointer,
234 // to align start of rset to a uint32_t address.
235 static const int kObjectStartOffset = 256;
236
237 // The start offset of the used part of the remembered set in a page.
238 static const int kRSetStartOffset = kRSetOffset +
239 kObjectStartOffset / kBitsPerPointer;
240
241 // Object area size in bytes.
242 static const int kObjectAreaSize = kPageSize - kObjectStartOffset;
243
244 // Maximum object size that fits in a page.
245 static const int kMaxHeapObjectSize = kObjectAreaSize;
246
247 //---------------------------------------------------------------------------
248 // Page header description.
249 //
250 // If a page is not in the large object space, the first word,
251 // opaque_header, encodes the next page address (aligned to kPageSize 8K)
252 // and the chunk number (0 ~ 8K-1). Only MemoryAllocator should use
253 // opaque_header. The value range of the opaque_header is [0..kPageSize[,
254 // or [next_page_start, next_page_end[. It cannot point to a valid address
255 // in the current page. If a page is in the large object space, the first
256 // word *may* (if the page start and large object chunk start are the
257 // same) contain the address of the next large object chunk.
258 intptr_t opaque_header;
259
260 // If the page is not in the large object space, the low-order bit of the
261 // second word is set. If the page is in the large object space, the
262 // second word *may* (if the page start and large object chunk start are
263 // the same) contain the large object chunk size. In either case, the
264 // low-order bit for large object pages will be cleared.
265 int is_normal_page;
266
267 // The following fields may overlap with remembered set, they can only
268 // be used in the mark-compact collector when remembered set is not
269 // used.
270
271 // The index of the page in its owner space.
272 int mc_page_index;
273
274 // The allocation pointer after relocating objects to this page.
275 Address mc_relocation_top;
276
277 // The forwarding address of the first live object in this page.
278 Address mc_first_forwarded;
279
280#ifdef DEBUG
281 private:
282 static RSetState rset_state_; // state of the remembered set
283#endif
284};
285
286
287// ----------------------------------------------------------------------------
288// Space is the abstract superclass for all allocation spaces.
289class Space : public Malloced {
290 public:
291 Space(AllocationSpace id, Executability executable)
292 : id_(id), executable_(executable) {}
293
294 virtual ~Space() {}
295
296 // Does the space need executable memory?
297 Executability executable() { return executable_; }
298
299 // Identity used in error reporting.
300 AllocationSpace identity() { return id_; }
301
302 virtual int Size() = 0;
303
304#ifdef DEBUG
305 virtual void Print() = 0;
306#endif
307
Leon Clarkee46be812010-01-19 14:06:41 +0000308 // After calling this we can allocate a certain number of bytes using only
309 // linear allocation (with a LinearAllocationScope and an AlwaysAllocateScope)
310 // without using freelists or causing a GC. This is used by partial
311 // snapshots. It returns true of space was reserved or false if a GC is
312 // needed. For paged spaces the space requested must include the space wasted
313 // at the end of each when allocating linearly.
314 virtual bool ReserveSpace(int bytes) = 0;
315
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 private:
317 AllocationSpace id_;
318 Executability executable_;
319};
320
321
322// ----------------------------------------------------------------------------
323// All heap objects containing executable code (code objects) must be allocated
324// from a 2 GB range of memory, so that they can call each other using 32-bit
325// displacements. This happens automatically on 32-bit platforms, where 32-bit
326// displacements cover the entire 4GB virtual address space. On 64-bit
327// platforms, we support this using the CodeRange object, which reserves and
328// manages a range of virtual memory.
329class CodeRange : public AllStatic {
330 public:
331 // Reserves a range of virtual memory, but does not commit any of it.
332 // Can only be called once, at heap initialization time.
333 // Returns false on failure.
334 static bool Setup(const size_t requested_size);
335
336 // Frees the range of virtual memory, and frees the data structures used to
337 // manage it.
338 static void TearDown();
339
340 static bool exists() { return code_range_ != NULL; }
341 static bool contains(Address address) {
342 if (code_range_ == NULL) return false;
343 Address start = static_cast<Address>(code_range_->address());
344 return start <= address && address < start + code_range_->size();
345 }
346
347 // Allocates a chunk of memory from the large-object portion of
348 // the code range. On platforms with no separate code range, should
349 // not be called.
350 static void* AllocateRawMemory(const size_t requested, size_t* allocated);
351 static void FreeRawMemory(void* buf, size_t length);
352
353 private:
354 // The reserved range of virtual memory that all code objects are put in.
355 static VirtualMemory* code_range_;
356 // Plain old data class, just a struct plus a constructor.
357 class FreeBlock {
358 public:
359 FreeBlock(Address start_arg, size_t size_arg)
360 : start(start_arg), size(size_arg) {}
361 FreeBlock(void* start_arg, size_t size_arg)
362 : start(static_cast<Address>(start_arg)), size(size_arg) {}
363
364 Address start;
365 size_t size;
366 };
367
368 // Freed blocks of memory are added to the free list. When the allocation
369 // list is exhausted, the free list is sorted and merged to make the new
370 // allocation list.
371 static List<FreeBlock> free_list_;
372 // Memory is allocated from the free blocks on the allocation list.
373 // The block at current_allocation_block_index_ is the current block.
374 static List<FreeBlock> allocation_list_;
375 static int current_allocation_block_index_;
376
377 // Finds a block on the allocation list that contains at least the
378 // requested amount of memory. If none is found, sorts and merges
379 // the existing free memory blocks, and searches again.
380 // If none can be found, terminates V8 with FatalProcessOutOfMemory.
381 static void GetNextAllocationBlock(size_t requested);
382 // Compares the start addresses of two free blocks.
383 static int CompareFreeBlockAddress(const FreeBlock* left,
384 const FreeBlock* right);
385};
386
387
388// ----------------------------------------------------------------------------
389// A space acquires chunks of memory from the operating system. The memory
390// allocator manages chunks for the paged heap spaces (old space and map
391// space). A paged chunk consists of pages. Pages in a chunk have contiguous
392// addresses and are linked as a list.
393//
394// The allocator keeps an initial chunk which is used for the new space. The
395// leftover regions of the initial chunk are used for the initial chunks of
396// old space and map space if they are big enough to hold at least one page.
397// The allocator assumes that there is one old space and one map space, each
398// expands the space by allocating kPagesPerChunk pages except the last
399// expansion (before running out of space). The first chunk may contain fewer
400// than kPagesPerChunk pages as well.
401//
402// The memory allocator also allocates chunks for the large object space, but
403// they are managed by the space itself. The new space does not expand.
404
405class MemoryAllocator : public AllStatic {
406 public:
407 // Initializes its internal bookkeeping structures.
408 // Max capacity of the total space.
409 static bool Setup(int max_capacity);
410
411 // Deletes valid chunks.
412 static void TearDown();
413
414 // Reserves an initial address range of virtual memory to be split between
415 // the two new space semispaces, the old space, and the map space. The
416 // memory is not yet committed or assigned to spaces and split into pages.
417 // The initial chunk is unmapped when the memory allocator is torn down.
418 // This function should only be called when there is not already a reserved
419 // initial chunk (initial_chunk_ should be NULL). It returns the start
420 // address of the initial chunk if successful, with the side effect of
421 // setting the initial chunk, or else NULL if unsuccessful and leaves the
422 // initial chunk NULL.
423 static void* ReserveInitialChunk(const size_t requested);
424
425 // Commits pages from an as-yet-unmanaged block of virtual memory into a
426 // paged space. The block should be part of the initial chunk reserved via
427 // a call to ReserveInitialChunk. The number of pages is always returned in
428 // the output parameter num_pages. This function assumes that the start
429 // address is non-null and that it is big enough to hold at least one
430 // page-aligned page. The call always succeeds, and num_pages is always
431 // greater than zero.
432 static Page* CommitPages(Address start, size_t size, PagedSpace* owner,
433 int* num_pages);
434
435 // Commit a contiguous block of memory from the initial chunk. Assumes that
436 // the address is not NULL, the size is greater than zero, and that the
437 // block is contained in the initial chunk. Returns true if it succeeded
438 // and false otherwise.
439 static bool CommitBlock(Address start, size_t size, Executability executable);
440
441
442 // Uncommit a contiguous block of memory [start..(start+size)[.
443 // start is not NULL, the size is greater than zero, and the
444 // block is contained in the initial chunk. Returns true if it succeeded
445 // and false otherwise.
446 static bool UncommitBlock(Address start, size_t size);
447
448 // Attempts to allocate the requested (non-zero) number of pages from the
449 // OS. Fewer pages might be allocated than requested. If it fails to
450 // allocate memory for the OS or cannot allocate a single page, this
451 // function returns an invalid page pointer (NULL). The caller must check
452 // whether the returned page is valid (by calling Page::is_valid()). It is
453 // guaranteed that allocated pages have contiguous addresses. The actual
454 // number of allocated pages is returned in the output parameter
455 // allocated_pages. If the PagedSpace owner is executable and there is
456 // a code range, the pages are allocated from the code range.
457 static Page* AllocatePages(int requested_pages, int* allocated_pages,
458 PagedSpace* owner);
459
460 // Frees pages from a given page and after. If 'p' is the first page
461 // of a chunk, pages from 'p' are freed and this function returns an
462 // invalid page pointer. Otherwise, the function searches a page
463 // after 'p' that is the first page of a chunk. Pages after the
464 // found page are freed and the function returns 'p'.
465 static Page* FreePages(Page* p);
466
467 // Allocates and frees raw memory of certain size.
468 // These are just thin wrappers around OS::Allocate and OS::Free,
469 // but keep track of allocated bytes as part of heap.
470 // If the flag is EXECUTABLE and a code range exists, the requested
471 // memory is allocated from the code range. If a code range exists
472 // and the freed memory is in it, the code range manages the freed memory.
473 static void* AllocateRawMemory(const size_t requested,
474 size_t* allocated,
475 Executability executable);
476 static void FreeRawMemory(void* buf, size_t length);
477
478 // Returns the maximum available bytes of heaps.
479 static int Available() { return capacity_ < size_ ? 0 : capacity_ - size_; }
480
481 // Returns allocated spaces in bytes.
482 static int Size() { return size_; }
483
484 // Returns maximum available bytes that the old space can have.
485 static int MaxAvailable() {
486 return (Available() / Page::kPageSize) * Page::kObjectAreaSize;
487 }
488
489 // Links two pages.
490 static inline void SetNextPage(Page* prev, Page* next);
491
492 // Returns the next page of a given page.
493 static inline Page* GetNextPage(Page* p);
494
495 // Checks whether a page belongs to a space.
496 static inline bool IsPageInSpace(Page* p, PagedSpace* space);
497
498 // Returns the space that owns the given page.
499 static inline PagedSpace* PageOwner(Page* page);
500
501 // Finds the first/last page in the same chunk as a given page.
502 static Page* FindFirstPageInSameChunk(Page* p);
503 static Page* FindLastPageInSameChunk(Page* p);
504
505#ifdef ENABLE_HEAP_PROTECTION
506 // Protect/unprotect a block of memory by marking it read-only/writable.
507 static inline void Protect(Address start, size_t size);
508 static inline void Unprotect(Address start, size_t size,
509 Executability executable);
510
511 // Protect/unprotect a chunk given a page in the chunk.
512 static inline void ProtectChunkFromPage(Page* page);
513 static inline void UnprotectChunkFromPage(Page* page);
514#endif
515
516#ifdef DEBUG
517 // Reports statistic info of the space.
518 static void ReportStatistics();
519#endif
520
521 // Due to encoding limitation, we can only have 8K chunks.
Leon Clarkee46be812010-01-19 14:06:41 +0000522 static const int kMaxNofChunks = 1 << kPageSizeBits;
Steve Blocka7e24c12009-10-30 11:49:00 +0000523 // If a chunk has at least 16 pages, the maximum heap size is about
524 // 8K * 8K * 16 = 1G bytes.
525#ifdef V8_TARGET_ARCH_X64
526 static const int kPagesPerChunk = 32;
527#else
528 static const int kPagesPerChunk = 16;
529#endif
530 static const int kChunkSize = kPagesPerChunk * Page::kPageSize;
531
532 private:
533 // Maximum space size in bytes.
534 static int capacity_;
535
536 // Allocated space size in bytes.
537 static int size_;
538
539 // The initial chunk of virtual memory.
540 static VirtualMemory* initial_chunk_;
541
542 // Allocated chunk info: chunk start address, chunk size, and owning space.
543 class ChunkInfo BASE_EMBEDDED {
544 public:
545 ChunkInfo() : address_(NULL), size_(0), owner_(NULL) {}
546 void init(Address a, size_t s, PagedSpace* o) {
547 address_ = a;
548 size_ = s;
549 owner_ = o;
550 }
551 Address address() { return address_; }
552 size_t size() { return size_; }
553 PagedSpace* owner() { return owner_; }
554
555 private:
556 Address address_;
557 size_t size_;
558 PagedSpace* owner_;
559 };
560
561 // Chunks_, free_chunk_ids_ and top_ act as a stack of free chunk ids.
562 static List<ChunkInfo> chunks_;
563 static List<int> free_chunk_ids_;
564 static int max_nof_chunks_;
565 static int top_;
566
567 // Push/pop a free chunk id onto/from the stack.
568 static void Push(int free_chunk_id);
569 static int Pop();
570 static bool OutOfChunkIds() { return top_ == 0; }
571
572 // Frees a chunk.
573 static void DeleteChunk(int chunk_id);
574
575 // Basic check whether a chunk id is in the valid range.
576 static inline bool IsValidChunkId(int chunk_id);
577
578 // Checks whether a chunk id identifies an allocated chunk.
579 static inline bool IsValidChunk(int chunk_id);
580
581 // Returns the chunk id that a page belongs to.
582 static inline int GetChunkId(Page* p);
583
584 // True if the address lies in the initial chunk.
585 static inline bool InInitialChunk(Address address);
586
587 // Initializes pages in a chunk. Returns the first page address.
588 // This function and GetChunkId() are provided for the mark-compact
589 // collector to rebuild page headers in the from space, which is
590 // used as a marking stack and its page headers are destroyed.
591 static Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
592 PagedSpace* owner);
593};
594
595
596// -----------------------------------------------------------------------------
597// Interface for heap object iterator to be implemented by all object space
598// object iterators.
599//
600// NOTE: The space specific object iterators also implements the own has_next()
601// and next() methods which are used to avoid using virtual functions
602// iterating a specific space.
603
604class ObjectIterator : public Malloced {
605 public:
606 virtual ~ObjectIterator() { }
607
608 virtual bool has_next_object() = 0;
609 virtual HeapObject* next_object() = 0;
610};
611
612
613// -----------------------------------------------------------------------------
614// Heap object iterator in new/old/map spaces.
615//
616// A HeapObjectIterator iterates objects from a given address to the
617// top of a space. The given address must be below the current
618// allocation pointer (space top). There are some caveats.
619//
620// (1) If the space top changes upward during iteration (because of
621// allocating new objects), the iterator does not iterate objects
622// above the original space top. The caller must create a new
623// iterator starting from the old top in order to visit these new
624// objects.
625//
626// (2) If new objects are allocated below the original allocation top
627// (e.g., free-list allocation in paged spaces), the new objects
628// may or may not be iterated depending on their position with
629// respect to the current point of iteration.
630//
631// (3) The space top should not change downward during iteration,
632// otherwise the iterator will return not-necessarily-valid
633// objects.
634
635class HeapObjectIterator: public ObjectIterator {
636 public:
637 // Creates a new object iterator in a given space. If a start
638 // address is not given, the iterator starts from the space bottom.
639 // If the size function is not given, the iterator calls the default
640 // Object::Size().
641 explicit HeapObjectIterator(PagedSpace* space);
642 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
643 HeapObjectIterator(PagedSpace* space, Address start);
644 HeapObjectIterator(PagedSpace* space,
645 Address start,
646 HeapObjectCallback size_func);
647
648 inline bool has_next();
649 inline HeapObject* next();
650
651 // implementation of ObjectIterator.
652 virtual bool has_next_object() { return has_next(); }
653 virtual HeapObject* next_object() { return next(); }
654
655 private:
656 Address cur_addr_; // current iteration point
657 Address end_addr_; // end iteration point
658 Address cur_limit_; // current page limit
659 HeapObjectCallback size_func_; // size function
660 Page* end_page_; // caches the page of the end address
661
662 // Slow path of has_next, checks whether there are more objects in
663 // the next page.
664 bool HasNextInNextPage();
665
666 // Initializes fields.
667 void Initialize(Address start, Address end, HeapObjectCallback size_func);
668
669#ifdef DEBUG
670 // Verifies whether fields have valid values.
671 void Verify();
672#endif
673};
674
675
676// -----------------------------------------------------------------------------
677// A PageIterator iterates the pages in a paged space.
678//
679// The PageIterator class provides three modes for iterating pages in a space:
680// PAGES_IN_USE iterates pages containing allocated objects.
681// PAGES_USED_BY_MC iterates pages that hold relocated objects during a
682// mark-compact collection.
683// ALL_PAGES iterates all pages in the space.
684//
685// There are some caveats.
686//
687// (1) If the space expands during iteration, new pages will not be
688// returned by the iterator in any mode.
689//
690// (2) If new objects are allocated during iteration, they will appear
691// in pages returned by the iterator. Allocation may cause the
692// allocation pointer or MC allocation pointer in the last page to
693// change between constructing the iterator and iterating the last
694// page.
695//
696// (3) The space should not shrink during iteration, otherwise the
697// iterator will return deallocated pages.
698
699class PageIterator BASE_EMBEDDED {
700 public:
701 enum Mode {
702 PAGES_IN_USE,
703 PAGES_USED_BY_MC,
704 ALL_PAGES
705 };
706
707 PageIterator(PagedSpace* space, Mode mode);
708
709 inline bool has_next();
710 inline Page* next();
711
712 private:
713 PagedSpace* space_;
714 Page* prev_page_; // Previous page returned.
715 Page* stop_page_; // Page to stop at (last page returned by the iterator).
716};
717
718
719// -----------------------------------------------------------------------------
720// A space has a list of pages. The next page can be accessed via
721// Page::next_page() call. The next page of the last page is an
722// invalid page pointer. A space can expand and shrink dynamically.
723
724// An abstraction of allocation and relocation pointers in a page-structured
725// space.
726class AllocationInfo {
727 public:
728 Address top; // current allocation top
729 Address limit; // current allocation limit
730
731#ifdef DEBUG
732 bool VerifyPagedAllocation() {
733 return (Page::FromAllocationTop(top) == Page::FromAllocationTop(limit))
734 && (top <= limit);
735 }
736#endif
737};
738
739
740// An abstraction of the accounting statistics of a page-structured space.
741// The 'capacity' of a space is the number of object-area bytes (ie, not
742// including page bookkeeping structures) currently in the space. The 'size'
743// of a space is the number of allocated bytes, the 'waste' in the space is
744// the number of bytes that are not allocated and not available to
745// allocation without reorganizing the space via a GC (eg, small blocks due
746// to internal fragmentation, top of page areas in map space), and the bytes
747// 'available' is the number of unallocated bytes that are not waste. The
748// capacity is the sum of size, waste, and available.
749//
750// The stats are only set by functions that ensure they stay balanced. These
751// functions increase or decrease one of the non-capacity stats in
752// conjunction with capacity, or else they always balance increases and
753// decreases to the non-capacity stats.
754class AllocationStats BASE_EMBEDDED {
755 public:
756 AllocationStats() { Clear(); }
757
758 // Zero out all the allocation statistics (ie, no capacity).
759 void Clear() {
760 capacity_ = 0;
761 available_ = 0;
762 size_ = 0;
763 waste_ = 0;
764 }
765
766 // Reset the allocation statistics (ie, available = capacity with no
767 // wasted or allocated bytes).
768 void Reset() {
769 available_ = capacity_;
770 size_ = 0;
771 waste_ = 0;
772 }
773
774 // Accessors for the allocation statistics.
775 int Capacity() { return capacity_; }
776 int Available() { return available_; }
777 int Size() { return size_; }
778 int Waste() { return waste_; }
779
780 // Grow the space by adding available bytes.
781 void ExpandSpace(int size_in_bytes) {
782 capacity_ += size_in_bytes;
783 available_ += size_in_bytes;
784 }
785
786 // Shrink the space by removing available bytes.
787 void ShrinkSpace(int size_in_bytes) {
788 capacity_ -= size_in_bytes;
789 available_ -= size_in_bytes;
790 }
791
792 // Allocate from available bytes (available -> size).
793 void AllocateBytes(int size_in_bytes) {
794 available_ -= size_in_bytes;
795 size_ += size_in_bytes;
796 }
797
798 // Free allocated bytes, making them available (size -> available).
799 void DeallocateBytes(int size_in_bytes) {
800 size_ -= size_in_bytes;
801 available_ += size_in_bytes;
802 }
803
804 // Waste free bytes (available -> waste).
805 void WasteBytes(int size_in_bytes) {
806 available_ -= size_in_bytes;
807 waste_ += size_in_bytes;
808 }
809
810 // Consider the wasted bytes to be allocated, as they contain filler
811 // objects (waste -> size).
812 void FillWastedBytes(int size_in_bytes) {
813 waste_ -= size_in_bytes;
814 size_ += size_in_bytes;
815 }
816
817 private:
818 int capacity_;
819 int available_;
820 int size_;
821 int waste_;
822};
823
824
825class PagedSpace : public Space {
826 public:
827 // Creates a space with a maximum capacity, and an id.
828 PagedSpace(int max_capacity, AllocationSpace id, Executability executable);
829
830 virtual ~PagedSpace() {}
831
832 // Set up the space using the given address range of virtual memory (from
833 // the memory allocator's initial chunk) if possible. If the block of
834 // addresses is not big enough to contain a single page-aligned page, a
835 // fresh chunk will be allocated.
836 bool Setup(Address start, size_t size);
837
838 // Returns true if the space has been successfully set up and not
839 // subsequently torn down.
840 bool HasBeenSetup();
841
842 // Cleans up the space, frees all pages in this space except those belonging
843 // to the initial chunk, uncommits addresses in the initial chunk.
844 void TearDown();
845
846 // Checks whether an object/address is in this space.
847 inline bool Contains(Address a);
848 bool Contains(HeapObject* o) { return Contains(o->address()); }
849
850 // Given an address occupied by a live object, return that object if it is
851 // in this space, or Failure::Exception() if it is not. The implementation
852 // iterates over objects in the page containing the address, the cost is
853 // linear in the number of objects in the page. It may be slow.
854 Object* FindObject(Address addr);
855
856 // Checks whether page is currently in use by this space.
857 bool IsUsed(Page* page);
858
859 // Clears remembered sets of pages in this space.
860 void ClearRSet();
861
862 // Prepares for a mark-compact GC.
863 virtual void PrepareForMarkCompact(bool will_compact) = 0;
864
865 virtual Address PageAllocationTop(Page* page) = 0;
866
867 // Current capacity without growing (Size() + Available() + Waste()).
868 int Capacity() { return accounting_stats_.Capacity(); }
869
Steve Block3ce2e202009-11-05 08:53:23 +0000870 // Total amount of memory committed for this space. For paged
871 // spaces this equals the capacity.
872 int CommittedMemory() { return Capacity(); }
873
Steve Blocka7e24c12009-10-30 11:49:00 +0000874 // Available bytes without growing.
875 int Available() { return accounting_stats_.Available(); }
876
877 // Allocated bytes in this space.
878 virtual int Size() { return accounting_stats_.Size(); }
879
880 // Wasted bytes due to fragmentation and not recoverable until the
881 // next GC of this space.
882 int Waste() { return accounting_stats_.Waste(); }
883
884 // Returns the address of the first object in this space.
885 Address bottom() { return first_page_->ObjectAreaStart(); }
886
887 // Returns the allocation pointer in this space.
888 Address top() { return allocation_info_.top; }
889
890 // Allocate the requested number of bytes in the space if possible, return a
891 // failure object if not.
892 inline Object* AllocateRaw(int size_in_bytes);
893
894 // Allocate the requested number of bytes for relocation during mark-compact
895 // collection.
896 inline Object* MCAllocateRaw(int size_in_bytes);
897
Leon Clarkee46be812010-01-19 14:06:41 +0000898 virtual bool ReserveSpace(int bytes);
899
900 // Used by ReserveSpace.
901 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page) = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000902
903 // ---------------------------------------------------------------------------
904 // Mark-compact collection support functions
905
906 // Set the relocation point to the beginning of the space.
907 void MCResetRelocationInfo();
908
909 // Writes relocation info to the top page.
910 void MCWriteRelocationInfoToPage() {
911 TopPageOf(mc_forwarding_info_)->mc_relocation_top = mc_forwarding_info_.top;
912 }
913
914 // Computes the offset of a given address in this space to the beginning
915 // of the space.
916 int MCSpaceOffsetForAddress(Address addr);
917
918 // Updates the allocation pointer to the relocation top after a mark-compact
919 // collection.
920 virtual void MCCommitRelocationInfo() = 0;
921
922 // Releases half of unused pages.
923 void Shrink();
924
925 // Ensures that the capacity is at least 'capacity'. Returns false on failure.
926 bool EnsureCapacity(int capacity);
927
928#ifdef ENABLE_HEAP_PROTECTION
929 // Protect/unprotect the space by marking it read-only/writable.
930 void Protect();
931 void Unprotect();
932#endif
933
934#ifdef DEBUG
935 // Print meta info and objects in this space.
936 virtual void Print();
937
938 // Verify integrity of this space.
939 virtual void Verify(ObjectVisitor* visitor);
940
941 // Overridden by subclasses to verify space-specific object
942 // properties (e.g., only maps or free-list nodes are in map space).
943 virtual void VerifyObject(HeapObject* obj) {}
944
945 // Report code object related statistics
946 void CollectCodeStatistics();
947 static void ReportCodeStatistics();
948 static void ResetCodeStatistics();
949#endif
950
951 protected:
952 // Maximum capacity of this space.
953 int max_capacity_;
954
955 // Accounting information for this space.
956 AllocationStats accounting_stats_;
957
958 // The first page in this space.
959 Page* first_page_;
960
961 // The last page in this space. Initially set in Setup, updated in
962 // Expand and Shrink.
963 Page* last_page_;
964
965 // Normal allocation information.
966 AllocationInfo allocation_info_;
967
968 // Relocation information during mark-compact collections.
969 AllocationInfo mc_forwarding_info_;
970
971 // Bytes of each page that cannot be allocated. Possibly non-zero
972 // for pages in spaces with only fixed-size objects. Always zero
973 // for pages in spaces with variable sized objects (those pages are
974 // padded with free-list nodes).
975 int page_extra_;
976
977 // Sets allocation pointer to a page bottom.
978 static void SetAllocationInfo(AllocationInfo* alloc_info, Page* p);
979
980 // Returns the top page specified by an allocation info structure.
981 static Page* TopPageOf(AllocationInfo alloc_info) {
982 return Page::FromAllocationTop(alloc_info.limit);
983 }
984
985 // Expands the space by allocating a fixed number of pages. Returns false if
986 // it cannot allocate requested number of pages from OS. Newly allocated
987 // pages are append to the last_page;
988 bool Expand(Page* last_page);
989
990 // Generic fast case allocation function that tries linear allocation in
991 // the top page of 'alloc_info'. Returns NULL on failure.
992 inline HeapObject* AllocateLinearly(AllocationInfo* alloc_info,
993 int size_in_bytes);
994
995 // During normal allocation or deserialization, roll to the next page in
996 // the space (there is assumed to be one) and allocate there. This
997 // function is space-dependent.
998 virtual HeapObject* AllocateInNextPage(Page* current_page,
999 int size_in_bytes) = 0;
1000
1001 // Slow path of AllocateRaw. This function is space-dependent.
1002 virtual HeapObject* SlowAllocateRaw(int size_in_bytes) = 0;
1003
1004 // Slow path of MCAllocateRaw.
1005 HeapObject* SlowMCAllocateRaw(int size_in_bytes);
1006
1007#ifdef DEBUG
Leon Clarkee46be812010-01-19 14:06:41 +00001008 // Returns the number of total pages in this space.
1009 int CountTotalPages();
1010
Steve Blocka7e24c12009-10-30 11:49:00 +00001011 void DoPrintRSet(const char* space_name);
1012#endif
1013 private:
1014 // Returns the page of the allocation pointer.
1015 Page* AllocationTopPage() { return TopPageOf(allocation_info_); }
1016
1017 // Returns a pointer to the page of the relocation pointer.
1018 Page* MCRelocationTopPage() { return TopPageOf(mc_forwarding_info_); }
1019
Steve Blocka7e24c12009-10-30 11:49:00 +00001020 friend class PageIterator;
1021};
1022
1023
1024#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1025class NumberAndSizeInfo BASE_EMBEDDED {
1026 public:
1027 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1028
1029 int number() const { return number_; }
1030 void increment_number(int num) { number_ += num; }
1031
1032 int bytes() const { return bytes_; }
1033 void increment_bytes(int size) { bytes_ += size; }
1034
1035 void clear() {
1036 number_ = 0;
1037 bytes_ = 0;
1038 }
1039
1040 private:
1041 int number_;
1042 int bytes_;
1043};
1044
1045
1046// HistogramInfo class for recording a single "bar" of a histogram. This
1047// class is used for collecting statistics to print to stdout (when compiled
1048// with DEBUG) or to the log file (when compiled with
1049// ENABLE_LOGGING_AND_PROFILING).
1050class HistogramInfo: public NumberAndSizeInfo {
1051 public:
1052 HistogramInfo() : NumberAndSizeInfo() {}
1053
1054 const char* name() { return name_; }
1055 void set_name(const char* name) { name_ = name; }
1056
1057 private:
1058 const char* name_;
1059};
1060#endif
1061
1062
1063// -----------------------------------------------------------------------------
1064// SemiSpace in young generation
1065//
1066// A semispace is a contiguous chunk of memory. The mark-compact collector
1067// uses the memory in the from space as a marking stack when tracing live
1068// objects.
1069
1070class SemiSpace : public Space {
1071 public:
1072 // Constructor.
1073 SemiSpace() :Space(NEW_SPACE, NOT_EXECUTABLE) {
1074 start_ = NULL;
1075 age_mark_ = NULL;
1076 }
1077
1078 // Sets up the semispace using the given chunk.
1079 bool Setup(Address start, int initial_capacity, int maximum_capacity);
1080
1081 // Tear down the space. Heap memory was not allocated by the space, so it
1082 // is not deallocated here.
1083 void TearDown();
1084
1085 // True if the space has been set up but not torn down.
1086 bool HasBeenSetup() { return start_ != NULL; }
1087
1088 // Grow the size of the semispace by committing extra virtual memory.
1089 // Assumes that the caller has checked that the semispace has not reached
1090 // its maximum capacity (and thus there is space available in the reserved
1091 // address range to grow).
1092 bool Grow();
1093
1094 // Grow the semispace to the new capacity. The new capacity
1095 // requested must be larger than the current capacity.
1096 bool GrowTo(int new_capacity);
1097
1098 // Shrinks the semispace to the new capacity. The new capacity
1099 // requested must be more than the amount of used memory in the
1100 // semispace and less than the current capacity.
1101 bool ShrinkTo(int new_capacity);
1102
1103 // Returns the start address of the space.
1104 Address low() { return start_; }
1105 // Returns one past the end address of the space.
1106 Address high() { return low() + capacity_; }
1107
1108 // Age mark accessors.
1109 Address age_mark() { return age_mark_; }
1110 void set_age_mark(Address mark) { age_mark_ = mark; }
1111
1112 // True if the address is in the address range of this semispace (not
1113 // necessarily below the allocation pointer).
1114 bool Contains(Address a) {
1115 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1116 == reinterpret_cast<uintptr_t>(start_);
1117 }
1118
1119 // True if the object is a heap object in the address range of this
1120 // semispace (not necessarily below the allocation pointer).
1121 bool Contains(Object* o) {
1122 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1123 }
1124
1125 // The offset of an address from the beginning of the space.
Steve Blockd0582a62009-12-15 09:54:21 +00001126 int SpaceOffsetForAddress(Address addr) {
1127 return static_cast<int>(addr - low());
1128 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001129
Leon Clarkee46be812010-01-19 14:06:41 +00001130 // If we don't have these here then SemiSpace will be abstract. However
1131 // they should never be called.
Steve Blocka7e24c12009-10-30 11:49:00 +00001132 virtual int Size() {
1133 UNREACHABLE();
1134 return 0;
1135 }
1136
Leon Clarkee46be812010-01-19 14:06:41 +00001137 virtual bool ReserveSpace(int bytes) {
1138 UNREACHABLE();
1139 return false;
1140 }
1141
Steve Blocka7e24c12009-10-30 11:49:00 +00001142 bool is_committed() { return committed_; }
1143 bool Commit();
1144 bool Uncommit();
1145
1146#ifdef DEBUG
1147 virtual void Print();
1148 virtual void Verify();
1149#endif
1150
1151 // Returns the current capacity of the semi space.
1152 int Capacity() { return capacity_; }
1153
1154 // Returns the maximum capacity of the semi space.
1155 int MaximumCapacity() { return maximum_capacity_; }
1156
1157 // Returns the initial capacity of the semi space.
1158 int InitialCapacity() { return initial_capacity_; }
1159
1160 private:
1161 // The current and maximum capacity of the space.
1162 int capacity_;
1163 int maximum_capacity_;
1164 int initial_capacity_;
1165
1166 // The start address of the space.
1167 Address start_;
1168 // Used to govern object promotion during mark-compact collection.
1169 Address age_mark_;
1170
1171 // Masks and comparison values to test for containment in this semispace.
1172 uintptr_t address_mask_;
1173 uintptr_t object_mask_;
1174 uintptr_t object_expected_;
1175
1176 bool committed_;
1177
1178 public:
1179 TRACK_MEMORY("SemiSpace")
1180};
1181
1182
1183// A SemiSpaceIterator is an ObjectIterator that iterates over the active
1184// semispace of the heap's new space. It iterates over the objects in the
1185// semispace from a given start address (defaulting to the bottom of the
1186// semispace) to the top of the semispace. New objects allocated after the
1187// iterator is created are not iterated.
1188class SemiSpaceIterator : public ObjectIterator {
1189 public:
1190 // Create an iterator over the objects in the given space. If no start
1191 // address is given, the iterator starts from the bottom of the space. If
1192 // no size function is given, the iterator calls Object::Size().
1193 explicit SemiSpaceIterator(NewSpace* space);
1194 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
1195 SemiSpaceIterator(NewSpace* space, Address start);
1196
1197 bool has_next() {return current_ < limit_; }
1198
1199 HeapObject* next() {
1200 ASSERT(has_next());
1201
1202 HeapObject* object = HeapObject::FromAddress(current_);
1203 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
1204
1205 current_ += size;
1206 return object;
1207 }
1208
1209 // Implementation of the ObjectIterator functions.
1210 virtual bool has_next_object() { return has_next(); }
1211 virtual HeapObject* next_object() { return next(); }
1212
1213 private:
1214 void Initialize(NewSpace* space, Address start, Address end,
1215 HeapObjectCallback size_func);
1216
1217 // The semispace.
1218 SemiSpace* space_;
1219 // The current iteration point.
1220 Address current_;
1221 // The end of iteration.
1222 Address limit_;
1223 // The callback function.
1224 HeapObjectCallback size_func_;
1225};
1226
1227
1228// -----------------------------------------------------------------------------
1229// The young generation space.
1230//
1231// The new space consists of a contiguous pair of semispaces. It simply
1232// forwards most functions to the appropriate semispace.
1233
1234class NewSpace : public Space {
1235 public:
1236 // Constructor.
1237 NewSpace() : Space(NEW_SPACE, NOT_EXECUTABLE) {}
1238
1239 // Sets up the new space using the given chunk.
1240 bool Setup(Address start, int size);
1241
1242 // Tears down the space. Heap memory was not allocated by the space, so it
1243 // is not deallocated here.
1244 void TearDown();
1245
1246 // True if the space has been set up but not torn down.
1247 bool HasBeenSetup() {
1248 return to_space_.HasBeenSetup() && from_space_.HasBeenSetup();
1249 }
1250
1251 // Flip the pair of spaces.
1252 void Flip();
1253
1254 // Grow the capacity of the semispaces. Assumes that they are not at
1255 // their maximum capacity.
1256 void Grow();
1257
1258 // Shrink the capacity of the semispaces.
1259 void Shrink();
1260
1261 // True if the address or object lies in the address range of either
1262 // semispace (not necessarily below the allocation pointer).
1263 bool Contains(Address a) {
1264 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1265 == reinterpret_cast<uintptr_t>(start_);
1266 }
1267 bool Contains(Object* o) {
1268 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1269 }
1270
1271 // Return the allocated bytes in the active semispace.
Steve Blockd0582a62009-12-15 09:54:21 +00001272 virtual int Size() { return static_cast<int>(top() - bottom()); }
Steve Block3ce2e202009-11-05 08:53:23 +00001273
Steve Blocka7e24c12009-10-30 11:49:00 +00001274 // Return the current capacity of a semispace.
1275 int Capacity() {
1276 ASSERT(to_space_.Capacity() == from_space_.Capacity());
1277 return to_space_.Capacity();
1278 }
Steve Block3ce2e202009-11-05 08:53:23 +00001279
1280 // Return the total amount of memory committed for new space.
1281 int CommittedMemory() {
1282 if (from_space_.is_committed()) return 2 * Capacity();
1283 return Capacity();
1284 }
1285
Steve Blocka7e24c12009-10-30 11:49:00 +00001286 // Return the available bytes without growing in the active semispace.
1287 int Available() { return Capacity() - Size(); }
1288
1289 // Return the maximum capacity of a semispace.
1290 int MaximumCapacity() {
1291 ASSERT(to_space_.MaximumCapacity() == from_space_.MaximumCapacity());
1292 return to_space_.MaximumCapacity();
1293 }
1294
1295 // Returns the initial capacity of a semispace.
1296 int InitialCapacity() {
1297 ASSERT(to_space_.InitialCapacity() == from_space_.InitialCapacity());
1298 return to_space_.InitialCapacity();
1299 }
1300
1301 // Return the address of the allocation pointer in the active semispace.
1302 Address top() { return allocation_info_.top; }
1303 // Return the address of the first object in the active semispace.
1304 Address bottom() { return to_space_.low(); }
1305
1306 // Get the age mark of the inactive semispace.
1307 Address age_mark() { return from_space_.age_mark(); }
1308 // Set the age mark in the active semispace.
1309 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
1310
1311 // The start address of the space and a bit mask. Anding an address in the
1312 // new space with the mask will result in the start address.
1313 Address start() { return start_; }
1314 uintptr_t mask() { return address_mask_; }
1315
1316 // The allocation top and limit addresses.
1317 Address* allocation_top_address() { return &allocation_info_.top; }
1318 Address* allocation_limit_address() { return &allocation_info_.limit; }
1319
1320 Object* AllocateRaw(int size_in_bytes) {
1321 return AllocateRawInternal(size_in_bytes, &allocation_info_);
1322 }
1323
1324 // Allocate the requested number of bytes for relocation during mark-compact
1325 // collection.
1326 Object* MCAllocateRaw(int size_in_bytes) {
1327 return AllocateRawInternal(size_in_bytes, &mc_forwarding_info_);
1328 }
1329
1330 // Reset the allocation pointer to the beginning of the active semispace.
1331 void ResetAllocationInfo();
1332 // Reset the reloction pointer to the bottom of the inactive semispace in
1333 // preparation for mark-compact collection.
1334 void MCResetRelocationInfo();
1335 // Update the allocation pointer in the active semispace after a
1336 // mark-compact collection.
1337 void MCCommitRelocationInfo();
1338
1339 // Get the extent of the inactive semispace (for use as a marking stack).
1340 Address FromSpaceLow() { return from_space_.low(); }
1341 Address FromSpaceHigh() { return from_space_.high(); }
1342
1343 // Get the extent of the active semispace (to sweep newly copied objects
1344 // during a scavenge collection).
1345 Address ToSpaceLow() { return to_space_.low(); }
1346 Address ToSpaceHigh() { return to_space_.high(); }
1347
1348 // Offsets from the beginning of the semispaces.
1349 int ToSpaceOffsetForAddress(Address a) {
1350 return to_space_.SpaceOffsetForAddress(a);
1351 }
1352 int FromSpaceOffsetForAddress(Address a) {
1353 return from_space_.SpaceOffsetForAddress(a);
1354 }
1355
1356 // True if the object is a heap object in the address range of the
1357 // respective semispace (not necessarily below the allocation pointer of the
1358 // semispace).
1359 bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
1360 bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
1361
1362 bool ToSpaceContains(Address a) { return to_space_.Contains(a); }
1363 bool FromSpaceContains(Address a) { return from_space_.Contains(a); }
1364
Leon Clarkee46be812010-01-19 14:06:41 +00001365 virtual bool ReserveSpace(int bytes);
1366
Steve Blocka7e24c12009-10-30 11:49:00 +00001367#ifdef ENABLE_HEAP_PROTECTION
1368 // Protect/unprotect the space by marking it read-only/writable.
1369 virtual void Protect();
1370 virtual void Unprotect();
1371#endif
1372
1373#ifdef DEBUG
1374 // Verify the active semispace.
1375 virtual void Verify();
1376 // Print the active semispace.
1377 virtual void Print() { to_space_.Print(); }
1378#endif
1379
1380#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1381 // Iterates the active semispace to collect statistics.
1382 void CollectStatistics();
1383 // Reports previously collected statistics of the active semispace.
1384 void ReportStatistics();
1385 // Clears previously collected statistics.
1386 void ClearHistograms();
1387
1388 // Record the allocation or promotion of a heap object. Note that we don't
1389 // record every single allocation, but only those that happen in the
1390 // to space during a scavenge GC.
1391 void RecordAllocation(HeapObject* obj);
1392 void RecordPromotion(HeapObject* obj);
1393#endif
1394
1395 // Return whether the operation succeded.
1396 bool CommitFromSpaceIfNeeded() {
1397 if (from_space_.is_committed()) return true;
1398 return from_space_.Commit();
1399 }
1400
1401 bool UncommitFromSpace() {
1402 if (!from_space_.is_committed()) return true;
1403 return from_space_.Uncommit();
1404 }
1405
1406 private:
1407 // The semispaces.
1408 SemiSpace to_space_;
1409 SemiSpace from_space_;
1410
1411 // Start address and bit mask for containment testing.
1412 Address start_;
1413 uintptr_t address_mask_;
1414 uintptr_t object_mask_;
1415 uintptr_t object_expected_;
1416
1417 // Allocation pointer and limit for normal allocation and allocation during
1418 // mark-compact collection.
1419 AllocationInfo allocation_info_;
1420 AllocationInfo mc_forwarding_info_;
1421
1422#if defined(DEBUG) || defined(ENABLE_LOGGING_AND_PROFILING)
1423 HistogramInfo* allocated_histogram_;
1424 HistogramInfo* promoted_histogram_;
1425#endif
1426
1427 // Implementation of AllocateRaw and MCAllocateRaw.
1428 inline Object* AllocateRawInternal(int size_in_bytes,
1429 AllocationInfo* alloc_info);
1430
1431 friend class SemiSpaceIterator;
1432
1433 public:
1434 TRACK_MEMORY("NewSpace")
1435};
1436
1437
1438// -----------------------------------------------------------------------------
1439// Free lists for old object spaces
1440//
1441// Free-list nodes are free blocks in the heap. They look like heap objects
1442// (free-list node pointers have the heap object tag, and they have a map like
1443// a heap object). They have a size and a next pointer. The next pointer is
1444// the raw address of the next free list node (or NULL).
1445class FreeListNode: public HeapObject {
1446 public:
1447 // Obtain a free-list node from a raw address. This is not a cast because
1448 // it does not check nor require that the first word at the address is a map
1449 // pointer.
1450 static FreeListNode* FromAddress(Address address) {
1451 return reinterpret_cast<FreeListNode*>(HeapObject::FromAddress(address));
1452 }
1453
Steve Block3ce2e202009-11-05 08:53:23 +00001454 static inline bool IsFreeListNode(HeapObject* object);
1455
Steve Blocka7e24c12009-10-30 11:49:00 +00001456 // Set the size in bytes, which can be read with HeapObject::Size(). This
1457 // function also writes a map to the first word of the block so that it
1458 // looks like a heap object to the garbage collector and heap iteration
1459 // functions.
1460 void set_size(int size_in_bytes);
1461
1462 // Accessors for the next field.
1463 inline Address next();
1464 inline void set_next(Address next);
1465
1466 private:
1467 static const int kNextOffset = POINTER_SIZE_ALIGN(ByteArray::kHeaderSize);
1468
1469 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeListNode);
1470};
1471
1472
1473// The free list for the old space.
1474class OldSpaceFreeList BASE_EMBEDDED {
1475 public:
1476 explicit OldSpaceFreeList(AllocationSpace owner);
1477
1478 // Clear the free list.
1479 void Reset();
1480
1481 // Return the number of bytes available on the free list.
1482 int available() { return available_; }
1483
1484 // Place a node on the free list. The block of size 'size_in_bytes'
1485 // starting at 'start' is placed on the free list. The return value is the
1486 // number of bytes that have been lost due to internal fragmentation by
1487 // freeing the block. Bookkeeping information will be written to the block,
1488 // ie, its contents will be destroyed. The start address should be word
1489 // aligned, and the size should be a non-zero multiple of the word size.
1490 int Free(Address start, int size_in_bytes);
1491
1492 // Allocate a block of size 'size_in_bytes' from the free list. The block
1493 // is unitialized. A failure is returned if no block is available. The
1494 // number of bytes lost to fragmentation is returned in the output parameter
1495 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
1496 Object* Allocate(int size_in_bytes, int* wasted_bytes);
1497
1498 private:
1499 // The size range of blocks, in bytes. (Smaller allocations are allowed, but
1500 // will always result in waste.)
1501 static const int kMinBlockSize = 2 * kPointerSize;
1502 static const int kMaxBlockSize = Page::kMaxHeapObjectSize;
1503
1504 // The identity of the owning space, for building allocation Failure
1505 // objects.
1506 AllocationSpace owner_;
1507
1508 // Total available bytes in all blocks on this free list.
1509 int available_;
1510
1511 // Blocks are put on exact free lists in an array, indexed by size in words.
1512 // The available sizes are kept in an increasingly ordered list. Entries
1513 // corresponding to sizes < kMinBlockSize always have an empty free list
1514 // (but index kHead is used for the head of the size list).
1515 struct SizeNode {
1516 // Address of the head FreeListNode of the implied block size or NULL.
1517 Address head_node_;
1518 // Size (words) of the next larger available size if head_node_ != NULL.
1519 int next_size_;
1520 };
1521 static const int kFreeListsLength = kMaxBlockSize / kPointerSize + 1;
1522 SizeNode free_[kFreeListsLength];
1523
1524 // Sentinel elements for the size list. Real elements are in ]kHead..kEnd[.
1525 static const int kHead = kMinBlockSize / kPointerSize - 1;
1526 static const int kEnd = kMaxInt;
1527
1528 // We keep a "finger" in the size list to speed up a common pattern:
1529 // repeated requests for the same or increasing sizes.
1530 int finger_;
1531
1532 // Starting from *prev, find and return the smallest size >= index (words),
1533 // or kEnd. Update *prev to be the largest size < index, or kHead.
1534 int FindSize(int index, int* prev) {
1535 int cur = free_[*prev].next_size_;
1536 while (cur < index) {
1537 *prev = cur;
1538 cur = free_[cur].next_size_;
1539 }
1540 return cur;
1541 }
1542
1543 // Remove an existing element from the size list.
1544 void RemoveSize(int index) {
1545 int prev = kHead;
1546 int cur = FindSize(index, &prev);
1547 ASSERT(cur == index);
1548 free_[prev].next_size_ = free_[cur].next_size_;
1549 finger_ = prev;
1550 }
1551
1552 // Insert a new element into the size list.
1553 void InsertSize(int index) {
1554 int prev = kHead;
1555 int cur = FindSize(index, &prev);
1556 ASSERT(cur != index);
1557 free_[prev].next_size_ = index;
1558 free_[index].next_size_ = cur;
1559 }
1560
1561 // The size list is not updated during a sequence of calls to Free, but is
1562 // rebuilt before the next allocation.
1563 void RebuildSizeList();
1564 bool needs_rebuild_;
1565
1566#ifdef DEBUG
1567 // Does this free list contain a free block located at the address of 'node'?
1568 bool Contains(FreeListNode* node);
1569#endif
1570
1571 DISALLOW_COPY_AND_ASSIGN(OldSpaceFreeList);
1572};
1573
1574
1575// The free list for the map space.
1576class FixedSizeFreeList BASE_EMBEDDED {
1577 public:
1578 FixedSizeFreeList(AllocationSpace owner, int object_size);
1579
1580 // Clear the free list.
1581 void Reset();
1582
1583 // Return the number of bytes available on the free list.
1584 int available() { return available_; }
1585
1586 // Place a node on the free list. The block starting at 'start' (assumed to
1587 // have size object_size_) is placed on the free list. Bookkeeping
1588 // information will be written to the block, ie, its contents will be
1589 // destroyed. The start address should be word aligned.
1590 void Free(Address start);
1591
1592 // Allocate a fixed sized block from the free list. The block is unitialized.
1593 // A failure is returned if no block is available.
1594 Object* Allocate();
1595
1596 private:
1597 // Available bytes on the free list.
1598 int available_;
1599
1600 // The head of the free list.
1601 Address head_;
1602
1603 // The identity of the owning space, for building allocation Failure
1604 // objects.
1605 AllocationSpace owner_;
1606
1607 // The size of the objects in this space.
1608 int object_size_;
1609
1610 DISALLOW_COPY_AND_ASSIGN(FixedSizeFreeList);
1611};
1612
1613
1614// -----------------------------------------------------------------------------
1615// Old object space (excluding map objects)
1616
1617class OldSpace : public PagedSpace {
1618 public:
1619 // Creates an old space object with a given maximum capacity.
1620 // The constructor does not allocate pages from OS.
1621 explicit OldSpace(int max_capacity,
1622 AllocationSpace id,
1623 Executability executable)
1624 : PagedSpace(max_capacity, id, executable), free_list_(id) {
1625 page_extra_ = 0;
1626 }
1627
1628 // The bytes available on the free list (ie, not above the linear allocation
1629 // pointer).
1630 int AvailableFree() { return free_list_.available(); }
1631
1632 // The top of allocation in a page in this space. Undefined if page is unused.
1633 virtual Address PageAllocationTop(Page* page) {
1634 return page == TopPageOf(allocation_info_) ? top() : page->ObjectAreaEnd();
1635 }
1636
1637 // Give a block of memory to the space's free list. It might be added to
1638 // the free list or accounted as waste.
1639 void Free(Address start, int size_in_bytes) {
1640 int wasted_bytes = free_list_.Free(start, size_in_bytes);
1641 accounting_stats_.DeallocateBytes(size_in_bytes);
1642 accounting_stats_.WasteBytes(wasted_bytes);
1643 }
1644
1645 // Prepare for full garbage collection. Resets the relocation pointer and
1646 // clears the free list.
1647 virtual void PrepareForMarkCompact(bool will_compact);
1648
1649 // Updates the allocation pointer to the relocation top after a mark-compact
1650 // collection.
1651 virtual void MCCommitRelocationInfo();
1652
Leon Clarkee46be812010-01-19 14:06:41 +00001653 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1654
Steve Blocka7e24c12009-10-30 11:49:00 +00001655#ifdef DEBUG
1656 // Reports statistics for the space
1657 void ReportStatistics();
1658 // Dump the remembered sets in the space to stdout.
1659 void PrintRSet();
1660#endif
1661
1662 protected:
1663 // Virtual function in the superclass. Slow path of AllocateRaw.
1664 HeapObject* SlowAllocateRaw(int size_in_bytes);
1665
1666 // Virtual function in the superclass. Allocate linearly at the start of
1667 // the page after current_page (there is assumed to be one).
1668 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1669
1670 private:
1671 // The space's free list.
1672 OldSpaceFreeList free_list_;
1673
1674 public:
1675 TRACK_MEMORY("OldSpace")
1676};
1677
1678
1679// -----------------------------------------------------------------------------
1680// Old space for objects of a fixed size
1681
1682class FixedSpace : public PagedSpace {
1683 public:
1684 FixedSpace(int max_capacity,
1685 AllocationSpace id,
1686 int object_size_in_bytes,
1687 const char* name)
1688 : PagedSpace(max_capacity, id, NOT_EXECUTABLE),
1689 object_size_in_bytes_(object_size_in_bytes),
1690 name_(name),
1691 free_list_(id, object_size_in_bytes) {
1692 page_extra_ = Page::kObjectAreaSize % object_size_in_bytes;
1693 }
1694
1695 // The top of allocation in a page in this space. Undefined if page is unused.
1696 virtual Address PageAllocationTop(Page* page) {
1697 return page == TopPageOf(allocation_info_) ? top()
1698 : page->ObjectAreaEnd() - page_extra_;
1699 }
1700
1701 int object_size_in_bytes() { return object_size_in_bytes_; }
1702
1703 // Give a fixed sized block of memory to the space's free list.
1704 void Free(Address start) {
1705 free_list_.Free(start);
1706 accounting_stats_.DeallocateBytes(object_size_in_bytes_);
1707 }
1708
1709 // Prepares for a mark-compact GC.
1710 virtual void PrepareForMarkCompact(bool will_compact);
1711
1712 // Updates the allocation pointer to the relocation top after a mark-compact
1713 // collection.
1714 virtual void MCCommitRelocationInfo();
1715
Leon Clarkee46be812010-01-19 14:06:41 +00001716 virtual void PutRestOfCurrentPageOnFreeList(Page* current_page);
1717
Steve Blocka7e24c12009-10-30 11:49:00 +00001718#ifdef DEBUG
1719 // Reports statistic info of the space
1720 void ReportStatistics();
1721
1722 // Dump the remembered sets in the space to stdout.
1723 void PrintRSet();
1724#endif
1725
1726 protected:
1727 // Virtual function in the superclass. Slow path of AllocateRaw.
1728 HeapObject* SlowAllocateRaw(int size_in_bytes);
1729
1730 // Virtual function in the superclass. Allocate linearly at the start of
1731 // the page after current_page (there is assumed to be one).
1732 HeapObject* AllocateInNextPage(Page* current_page, int size_in_bytes);
1733
Leon Clarkee46be812010-01-19 14:06:41 +00001734 void ResetFreeList() {
1735 free_list_.Reset();
1736 }
1737
Steve Blocka7e24c12009-10-30 11:49:00 +00001738 private:
1739 // The size of objects in this space.
1740 int object_size_in_bytes_;
1741
1742 // The name of this space.
1743 const char* name_;
1744
1745 // The space's free list.
1746 FixedSizeFreeList free_list_;
1747};
1748
1749
1750// -----------------------------------------------------------------------------
1751// Old space for all map objects
1752
1753class MapSpace : public FixedSpace {
1754 public:
1755 // Creates a map space object with a maximum capacity.
1756 MapSpace(int max_capacity, AllocationSpace id)
1757 : FixedSpace(max_capacity, id, Map::kSize, "map") {}
1758
1759 // Prepares for a mark-compact GC.
1760 virtual void PrepareForMarkCompact(bool will_compact);
1761
1762 // Given an index, returns the page address.
1763 Address PageAddress(int page_index) { return page_addresses_[page_index]; }
1764
1765 // Constants.
1766 static const int kMaxMapPageIndex = (1 << MapWord::kMapPageIndexBits) - 1;
1767
Leon Clarkee46be812010-01-19 14:06:41 +00001768 // Are map pointers encodable into map word?
1769 bool MapPointersEncodable() {
1770 if (!FLAG_use_big_map_space) {
1771 ASSERT(CountTotalPages() <= kMaxMapPageIndex);
1772 return true;
1773 }
1774 int n_of_pages = Capacity() / Page::kObjectAreaSize;
1775 ASSERT(n_of_pages == CountTotalPages());
1776 return n_of_pages <= kMaxMapPageIndex;
1777 }
1778
1779 // Should be called after forced sweep to find out if map space needs
1780 // compaction.
1781 bool NeedsCompaction(int live_maps) {
1782 return !MapPointersEncodable() && live_maps <= kCompactionThreshold;
1783 }
1784
1785 Address TopAfterCompaction(int live_maps) {
1786 ASSERT(NeedsCompaction(live_maps));
1787
1788 int pages_left = live_maps / kMapsPerPage;
1789 PageIterator it(this, PageIterator::ALL_PAGES);
1790 while (pages_left-- > 0) {
1791 ASSERT(it.has_next());
1792 it.next()->ClearRSet();
1793 }
1794 ASSERT(it.has_next());
1795 Page* top_page = it.next();
1796 top_page->ClearRSet();
1797 ASSERT(top_page->is_valid());
1798
1799 int offset = live_maps % kMapsPerPage * Map::kSize;
1800 Address top = top_page->ObjectAreaStart() + offset;
1801 ASSERT(top < top_page->ObjectAreaEnd());
1802 ASSERT(Contains(top));
1803
1804 return top;
1805 }
1806
1807 void FinishCompaction(Address new_top, int live_maps) {
1808 Page* top_page = Page::FromAddress(new_top);
1809 ASSERT(top_page->is_valid());
1810
1811 SetAllocationInfo(&allocation_info_, top_page);
1812 allocation_info_.top = new_top;
1813
1814 int new_size = live_maps * Map::kSize;
1815 accounting_stats_.DeallocateBytes(accounting_stats_.Size());
1816 accounting_stats_.AllocateBytes(new_size);
1817
1818#ifdef DEBUG
1819 if (FLAG_enable_slow_asserts) {
1820 int actual_size = 0;
1821 for (Page* p = first_page_; p != top_page; p = p->next_page())
1822 actual_size += kMapsPerPage * Map::kSize;
1823 actual_size += (new_top - top_page->ObjectAreaStart());
1824 ASSERT(accounting_stats_.Size() == actual_size);
1825 }
1826#endif
1827
1828 Shrink();
1829 ResetFreeList();
1830 }
1831
Steve Blocka7e24c12009-10-30 11:49:00 +00001832 protected:
1833#ifdef DEBUG
1834 virtual void VerifyObject(HeapObject* obj);
1835#endif
1836
1837 private:
Leon Clarkee46be812010-01-19 14:06:41 +00001838 static const int kMapsPerPage = Page::kObjectAreaSize / Map::kSize;
1839
1840 // Do map space compaction if there is a page gap.
1841 static const int kCompactionThreshold = kMapsPerPage * (kMaxMapPageIndex - 1);
1842
Steve Blocka7e24c12009-10-30 11:49:00 +00001843 // An array of page start address in a map space.
1844 Address page_addresses_[kMaxMapPageIndex + 1];
1845
1846 public:
1847 TRACK_MEMORY("MapSpace")
1848};
1849
1850
1851// -----------------------------------------------------------------------------
1852// Old space for all global object property cell objects
1853
1854class CellSpace : public FixedSpace {
1855 public:
1856 // Creates a property cell space object with a maximum capacity.
1857 CellSpace(int max_capacity, AllocationSpace id)
1858 : FixedSpace(max_capacity, id, JSGlobalPropertyCell::kSize, "cell") {}
1859
1860 protected:
1861#ifdef DEBUG
1862 virtual void VerifyObject(HeapObject* obj);
1863#endif
1864
1865 public:
1866 TRACK_MEMORY("CellSpace")
1867};
1868
1869
1870// -----------------------------------------------------------------------------
1871// Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
1872// the large object space. A large object is allocated from OS heap with
1873// extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
1874// A large object always starts at Page::kObjectStartOffset to a page.
1875// Large objects do not move during garbage collections.
1876
1877// A LargeObjectChunk holds exactly one large object page with exactly one
1878// large object.
1879class LargeObjectChunk {
1880 public:
1881 // Allocates a new LargeObjectChunk that contains a large object page
1882 // (Page::kPageSize aligned) that has at least size_in_bytes (for a large
1883 // object and possibly extra remembered set words) bytes after the object
1884 // area start of that page. The allocated chunk size is set in the output
1885 // parameter chunk_size.
1886 static LargeObjectChunk* New(int size_in_bytes,
1887 size_t* chunk_size,
1888 Executability executable);
1889
1890 // Interpret a raw address as a large object chunk.
1891 static LargeObjectChunk* FromAddress(Address address) {
1892 return reinterpret_cast<LargeObjectChunk*>(address);
1893 }
1894
1895 // Returns the address of this chunk.
1896 Address address() { return reinterpret_cast<Address>(this); }
1897
1898 // Accessors for the fields of the chunk.
1899 LargeObjectChunk* next() { return next_; }
1900 void set_next(LargeObjectChunk* chunk) { next_ = chunk; }
1901
1902 size_t size() { return size_; }
1903 void set_size(size_t size_in_bytes) { size_ = size_in_bytes; }
1904
1905 // Returns the object in this chunk.
1906 inline HeapObject* GetObject();
1907
1908 // Given a requested size (including any extra remembered set words),
1909 // returns the physical size of a chunk to be allocated.
1910 static int ChunkSizeFor(int size_in_bytes);
1911
1912 // Given a chunk size, returns the object size it can accommodate (not
1913 // including any extra remembered set words). Used by
1914 // LargeObjectSpace::Available. Note that this can overestimate the size
1915 // of object that will fit in a chunk---if the object requires extra
1916 // remembered set words (eg, for large fixed arrays), the actual object
1917 // size for the chunk will be smaller than reported by this function.
1918 static int ObjectSizeFor(int chunk_size) {
1919 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
1920 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
1921 }
1922
1923 private:
1924 // A pointer to the next large object chunk in the space or NULL.
1925 LargeObjectChunk* next_;
1926
1927 // The size of this chunk.
1928 size_t size_;
1929
1930 public:
1931 TRACK_MEMORY("LargeObjectChunk")
1932};
1933
1934
1935class LargeObjectSpace : public Space {
1936 public:
1937 explicit LargeObjectSpace(AllocationSpace id);
1938 virtual ~LargeObjectSpace() {}
1939
1940 // Initializes internal data structures.
1941 bool Setup();
1942
1943 // Releases internal resources, frees objects in this space.
1944 void TearDown();
1945
1946 // Allocates a (non-FixedArray, non-Code) large object.
1947 Object* AllocateRaw(int size_in_bytes);
1948 // Allocates a large Code object.
1949 Object* AllocateRawCode(int size_in_bytes);
1950 // Allocates a large FixedArray.
1951 Object* AllocateRawFixedArray(int size_in_bytes);
1952
1953 // Available bytes for objects in this space, not including any extra
1954 // remembered set words.
1955 int Available() {
1956 return LargeObjectChunk::ObjectSizeFor(MemoryAllocator::Available());
1957 }
1958
1959 virtual int Size() {
1960 return size_;
1961 }
1962
1963 int PageCount() {
1964 return page_count_;
1965 }
1966
1967 // Finds an object for a given address, returns Failure::Exception()
1968 // if it is not found. The function iterates through all objects in this
1969 // space, may be slow.
1970 Object* FindObject(Address a);
1971
1972 // Clears remembered sets.
1973 void ClearRSet();
1974
1975 // Iterates objects whose remembered set bits are set.
1976 void IterateRSet(ObjectSlotCallback func);
1977
1978 // Frees unmarked objects.
1979 void FreeUnmarkedObjects();
1980
1981 // Checks whether a heap object is in this space; O(1).
1982 bool Contains(HeapObject* obj);
1983
1984 // Checks whether the space is empty.
1985 bool IsEmpty() { return first_chunk_ == NULL; }
1986
Leon Clarkee46be812010-01-19 14:06:41 +00001987 // See the comments for ReserveSpace in the Space class. This has to be
1988 // called after ReserveSpace has been called on the paged spaces, since they
1989 // may use some memory, leaving less for large objects.
1990 virtual bool ReserveSpace(int bytes);
1991
Steve Blocka7e24c12009-10-30 11:49:00 +00001992#ifdef ENABLE_HEAP_PROTECTION
1993 // Protect/unprotect the space by marking it read-only/writable.
1994 void Protect();
1995 void Unprotect();
1996#endif
1997
1998#ifdef DEBUG
1999 virtual void Verify();
2000 virtual void Print();
2001 void ReportStatistics();
2002 void CollectCodeStatistics();
2003 // Dump the remembered sets in the space to stdout.
2004 void PrintRSet();
2005#endif
2006 // Checks whether an address is in the object area in this space. It
2007 // iterates all objects in the space. May be slow.
2008 bool SlowContains(Address addr) { return !FindObject(addr)->IsFailure(); }
2009
2010 private:
2011 // The head of the linked list of large object chunks.
2012 LargeObjectChunk* first_chunk_;
2013 int size_; // allocated bytes
2014 int page_count_; // number of chunks
2015
2016
2017 // Shared implementation of AllocateRaw, AllocateRawCode and
2018 // AllocateRawFixedArray.
2019 Object* AllocateRawInternal(int requested_size,
2020 int object_size,
2021 Executability executable);
2022
2023 // Returns the number of extra bytes (rounded up to the nearest full word)
2024 // required for extra_object_bytes of extra pointers (in bytes).
2025 static inline int ExtraRSetBytesFor(int extra_object_bytes);
2026
2027 friend class LargeObjectIterator;
2028
2029 public:
2030 TRACK_MEMORY("LargeObjectSpace")
2031};
2032
2033
2034class LargeObjectIterator: public ObjectIterator {
2035 public:
2036 explicit LargeObjectIterator(LargeObjectSpace* space);
2037 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2038
2039 bool has_next() { return current_ != NULL; }
2040 HeapObject* next();
2041
2042 // implementation of ObjectIterator.
2043 virtual bool has_next_object() { return has_next(); }
2044 virtual HeapObject* next_object() { return next(); }
2045
2046 private:
2047 LargeObjectChunk* current_;
2048 HeapObjectCallback size_func_;
2049};
2050
2051
2052} } // namespace v8::internal
2053
2054#endif // V8_SPACES_H_