source: trunk/Include/system/gc.sbp@ 449

Last change on this file since 449 was 449, checked in by dai, 16 years ago

GCがオブジェクト内の参照をスキャンする際、平たくスキャンするのではなく、基底クラスをたどるような実装に変更した。

File size: 22.5 KB
Line 
1/*!
2 @brief このファイルでは、ABのガベージコレクションの実装を行います。
3*/
4
5
6/*
7※これらの変数はコンパイラが自動的に定義します。
8Dim _System_gc_StackRoot_StartPtr As VoidPtr
9*/
10
11Const _System_GC_FLAG_ATOMIC = 1
12Const _System_GC_FLAG_NEEDFREE = 2
13Const _System_GC_FLAG_INITZERO = 4
14Const _System_GC_FLAG_OBJECT = 8
15
16Type _System_GlobalRoot
17 ptr As *LONG_PTR
18 count As Long
19End Type
20
21Type _System_MemoryObject
22 ptr As VoidPtr
23 size As SIZE_T
24 flags As DWord
25 generationCount As Long
26End Type
27
28Class _System_CGarbageCollection
29
30 hHeap As HANDLE ' GC用のヒープ
31
32 pMemoryObjects As *_System_MemoryObject ' メモリオブジェクト
33 countOfMemoryObjects As Long ' 管理するメモリオブジェクトの個数
34
35 iAllSize As SIZE_T
36
37 isSweeping As Boolean ' スウィープ中かどうか
38
39 minPtr As ULONG_PTR
40 maxPtr As ULONG_PTR
41
42 ' クリティカルセクション
43 CriticalSection As CRITICAL_SECTION
44
45 ' メモリの上限値(この値を超えるとGCが発動します)
46 limitMemorySize As LONG_PTR ' バイト単位
47 limitMemoryObjectNum As Long ' メモリオブジェクトの個数単位
48
49 isFinish As Boolean ' GC管理が終了したかどうか
50
51
52 ' Global Root
53 pGlobalRoots As *_System_GlobalRoot
54 globalRootNum As Long
55 Sub AddGlobalRootPtr( ptr As *LONG_PTR, count As Long )
56 pGlobalRoots = _System_realloc( pGlobalRoots, (globalRootNum + 1) * SizeOf(_System_GlobalRoot) )
57 pGlobalRoots[globalRootNum].ptr = ptr
58 pGlobalRoots[globalRootNum].count = count
59 globalRootNum++
60 End Sub
61
62 Sub RegisterGlobalRoots()
63 ' このメソッドの実装はコンパイラが自動生成する
64
65 ' AddGlobalRootPtr(...)
66 ' ...
67 End Sub
68
69 ' 特殊クラスのため、コンストラクタ・デストラクタは呼ばれません
70 Sub _System_CGarbageCollection()
71 End Sub
72 Sub ~_System_CGarbageCollection()
73 End Sub
74
75Public
76
77 /*!
78 @brief 環境変数にGCを登録する
79 @author Daisuke Yamamoto
80 @date 2007/10/21
81 */
82 Static Sub Initialize()
83 Dim temporary[255] As Char
84 If GetEnvironmentVariable( "ActiveBasicGarbageCollection", temporary, 255 ) Then
85 ' 既にGCがプロセスに存在するとき
86 _stscanf( temporary, "%08x", VarPtr( _System_pGC ) )
87 MessageBox(0,temporary,"GetEnvironmentVariable",0)
88 Else
89 _System_pGC = _System_calloc( SizeOf( _System_CGarbageCollection ) )
90 _System_pGC->Begin()
91
92 ' GCをプロセスに登録する
93 _stprintf( temporary, "%08x", _System_pGC )
94 SetEnvironmentVariable( "ActiveBasicGarbageCollection", temporary )
95 End If
96 End Sub
97
98 /*!
99 @brief メモリサイズの上限を指定する
100 @param limitMemorySize メモリサイズの上限(単位はバイト)
101 limitMemoryObjectNum メモリ個数の上限
102 @author Daisuke Yamamoto
103 @date 2007/10/21
104 */
105 Sub SetLimit( limitMemorySize As LONG_PTR, limitMemoryObjectNum As Long )
106 This.limitMemorySize = limitMemorySize
107 This.limitMemoryObjectNum = limitMemoryObjectNum
108 End Sub
109
110 /*!
111 @brief 初期化
112 @author Daisuke Yamamoto
113 @date 2007/10/21
114 */
115 Sub Begin()
116 If pMemoryObjects Then Exit Sub
117
118 isFinish = False
119
120 'メモリの上限値(この値を超えるとGCが発動します)
121 SetLimit(
122 1024*1024, ' バイト単位
123 2000 ' メモリオブジェクトの個数単位
124 )
125
126 hHeap = HeapCreate( 0, 0, 0 )
127
128 pMemoryObjects = _System_calloc( 1 )
129 countOfMemoryObjects=0
130
131 ' Global Root
132 pGlobalRoots = _System_calloc( 1 )
133 globalRootNum = 0
134 RegisterGlobalRoots()
135
136 iAllSize=0
137
138 ' スウィープ中かどうか
139 isSweeping = False
140
141 minPtr = &HFFFFFFFFFFFFFFFF As ULONG_PTR
142 maxPtr = 0
143
144 'クリティカルセッションを生成
145 InitializeCriticalSection(CriticalSection)
146
147
148 '---------------------------
149 ' 開始時のスレッドを通知
150 '---------------------------
151 Dim hTargetThread As HANDLE
152 DuplicateHandle(GetCurrentProcess(),
153 GetCurrentThread(),
154 GetCurrentProcess(),
155 hTargetThread, 0, FALSE, DUPLICATE_SAME_ACCESS) 'カレントスレッドのハンドルを複製
156
157 ' スレッド管理用オブジェクトを生成
158 _System_pobj_AllThreads = New Detail._System_CThreadCollection()
159
160 ' 自身のThreadオブジェクトを生成
161 Dim thread = New Thread(hTargetThread, GetCurrentThreadId(), 0)
162 thread.Name = "main"
163
164 _System_pobj_AllThreads->BeginThread(thread, _System_gc_StackRoot_StartPtr As *LONG_PTR)
165
166 End Sub
167
168 /*!
169 @brief 終了処理
170 @author Daisuke Yamamoto
171 @date 2007/10/21
172 */
173 Sub Finish()
174 If pMemoryObjects = NULL Then Exit Sub
175
176 isFinish = True
177
178 ' スレッド管理用オブジェクトを破棄
179 Delete _System_pobj_AllThreads
180
181 ' 自分以外のスレッドを一時停止
182 '_System_pobj_AllThreads->SuspendAnotherThread()
183
184 _System_DebugOnly_OutputDebugString( Ex"garbage colletion sweeping all memory objects!\r\n" )
185 DeleteAllGarbageMemories()
186
187 ' 未解放のメモリオブジェクトをトレース
188 DumpMemoryLeaks()
189
190 ' 自分以外のスレッドを再開
191 '_System_pobj_AllThreads->ResumeAnotherThread()
192
193 _System_free( pMemoryObjects )
194 pMemoryObjects = NULL
195
196 _System_free( pGlobalRoots )
197 pGlobalRoots = NULL
198
199 'クリティカルセッションを破棄
200 DeleteCriticalSection(CriticalSection)
201
202 End Sub
203
204 /*!
205 @brief メモリオブジェクトからインデックスを取得する
206 @param new_ptr メモリオブジェクトへのポインタ
207 @author Daisuke Yamamoto
208 @date 2007/10/21
209 */
210 Function GetMemoryObjectPtr( ptr As VoidPtr ) As *_System_MemoryObject
211 ' メモリオブジェクトの先頭部分からインデックスを取得する
212 Dim index = Get_LONG_PTR( ptr - SizeOf(LONG_PTR) ) As Long
213
214 If pMemoryObjects[index].ptr <> ptr Then
215 ' メモリイメージが壊れている(先頭に存在するインデックスの整合性が取れない)
216 Dim temporary[1024] As Char
217#ifdef _WIN64
218 'wsprintfでは、Windows 2000以降でしか%pが使えない。
219 wsprintf( temporary, Ex"indexOfMemoryObjects: %d\r\npMemoryObjects[index].ptr: &H%p\r\nptr: &H%p\r\n",
220 index,
221 pMemoryObjects[index].ptr,
222 ptr )
223#else
224 wsprintf( temporary, Ex"indexOfMemoryObjects: %d\r\npMemoryObjects[index].ptr: &H%08x\r\nptr: &H%08x\r\n",
225 index,
226 pMemoryObjects[index].ptr,
227 ptr )
228#endif
229 _System_DebugOnly_OutputDebugString( temporary )
230 debug
231 End If
232
233 Return VarPtr( pMemoryObjects[index] )
234 End Function
235
236 /*!
237 @brief メモリオブジェクトを追加する
238 @param new_ptr メモリオブジェクトへのポインタ
239 size メモリオブジェクトのサイズ
240 flags メモリオブジェクトの属性
241 @author Daisuke Yamamoto
242 @date 2007/10/21
243 */
244 Sub add(new_ptr As VoidPtr, size As SIZE_T, flags As DWord)
245 EnterCriticalSection(CriticalSection)
246 iAllSize+=size
247
248 ' メモリオブジェクトインスタンスの先頭にインデックスをセットする
249 Set_LONG_PTR( new_ptr - SizeOf( LONG_PTR ), countOfMemoryObjects )
250
251 pMemoryObjects = _System_realloc( pMemoryObjects, (countOfMemoryObjects+1)*SizeOf(_System_MemoryObject) )
252 pMemoryObjects[countOfMemoryObjects].ptr = new_ptr
253 pMemoryObjects[countOfMemoryObjects].size = size
254 pMemoryObjects[countOfMemoryObjects].flags = flags
255 pMemoryObjects[countOfMemoryObjects].generationCount = 0
256
257 If minPtr > new_ptr As ULONG_PTR Then
258 minPtr = new_ptr As ULONG_PTR
259 End If
260 If maxPtr < ( new_ptr + size ) As ULONG_PTR Then
261 maxPtr = ( new_ptr + size ) As ULONG_PTR
262 End If
263
264 countOfMemoryObjects++
265 LeaveCriticalSection(CriticalSection)
266
267 /*
268 ' デバッグ用
269 If countOfMemoryObjects = 1996 Then
270 debug
271 End If
272 */
273 End Sub
274
275
276 /*!
277 @brief メモリオブジェクトを確保する
278 @param size メモリオブジェクトのサイズ
279 flags メモリオブジェクトの属性
280 @author Daisuke Yamamoto
281 @date 2007/10/21
282 */
283 Function __malloc(size As SIZE_T,flags As Byte) As VoidPtr
284 Dim dwFlags As DWord
285 If flags and _System_GC_FLAG_INITZERO Then
286 dwFlags=HEAP_ZERO_MEMORY
287 Else
288 dwFlags=0
289 End If
290
291 ' 実際のメモリバッファはインデックスの分だけ多めに確保する
292 __malloc = HeapAlloc( hHeap, dwFlags, size + SizeOf( LONG_PTR ) )
293 throwIfAllocationFailed( __malloc, size )
294 __malloc += SizeOf( LONG_PTR )
295
296 ' 管理対象のメモリオブジェクトとして追加
297 add( __malloc, size, flags )
298 End Function
299
300 /*!
301 @brief メモリオブジェクトを再確保する
302 @param lpMem メモリオブジェクトへのポインタ
303 size メモリオブジェクトのサイズ
304 flags メモリオブジェクトの属性
305 @author Daisuke Yamamoto
306 @date 2007/10/21
307 */
308 Function __realloc(lpMem As VoidPtr, size As SIZE_T) As VoidPtr
309 EnterCriticalSection(CriticalSection)
310
311 ' メモリオブジェクトを取得
312 Dim pTempMemoryObject = GetMemoryObjectPtr( lpMem )
313
314 iAllSize += size - pTempMemoryObject->size
315
316 pTempMemoryObject->size = size
317 __realloc = HeapReAlloc( hHeap, HEAP_ZERO_MEMORY, pTempMemoryObject->ptr - SizeOf(LONG_PTR), size + SizeOf(LONG_PTR) )
318 If __realloc = 0 Then
319 LeaveCriticalSection(CriticalSection)
320 throwIfAllocationFailed(0, size)
321 End If
322 __realloc += SizeOf(LONG_PTR)
323 pTempMemoryObject->ptr = __realloc
324
325
326 If minPtr > pTempMemoryObject->ptr As ULONG_PTR Then
327 minPtr = pTempMemoryObject->ptr As ULONG_PTR
328 End If
329 If maxPtr < ( pTempMemoryObject->ptr + size ) As ULONG_PTR Then
330 maxPtr = ( pTempMemoryObject->ptr + size ) As ULONG_PTR
331 End If
332 LeaveCriticalSection(CriticalSection)
333 End Function
334
335 /*!
336 @brief メモリ確保に失敗したか(NULLかどうか)を調べ、失敗していたら例外を投げる。
337 @param[in] p メモリへのポインタ
338 @param[in] size 確保しようとした大きさ
339 @exception OutOfMemoryException pがNULLだったとき
340 @author Egtra
341 @date 2007/12/24
342 ただし、sizeがあまりにも小さい場合は、例外を投げず、即座に終了する。
343 */
344 Sub throwIfAllocationFailed(p As VoidPtr, size As SIZE_T)
345 If p = 0 Then
346 If size < 256 Then
347 /*
348  これだけのメモリも確保できない状況では、OutOfMemoryException
349 のインスタンスすら作成できないかもしれないし、例え作成できても、
350 その後、結局メモリ不足でろくなことを行えないはず。そのため、
351 ここですぐに終了することにする。
352  なお、この値は特に根拠があって定められた値ではない。
353 */
354 HeapDestroy(hHeap)
355 OutputDebugString("AB malloc: Out of memory.")
356 ExitProcess(-1)
357 End If
358 Dim s2 = Nothing As Object '#145
359 s2 = New System.UInt64(size)
360 Throw New System.OutOfMemoryException(ActiveBasic.Strings.SPrintf("malloc: Failed to allocate %zu (%&zx) byte(s) memory.", s2, s2))
361 End If
362 End Sub
363
364 /*!
365 @brief メモリオブジェクトを解放する
366 @param lpMem メモリオブジェクトへのポインタ
367 isSweeping スウィープ中にこのメソッドが呼ばれるときはTrue、それ以外はFalse
368 @author Daisuke Yamamoto
369 @date 2007/10/21
370 */
371 Sub __free_ex(lpMem As VoidPtr, isSweeping As Boolean)
372 EnterCriticalSection(CriticalSection)
373
374 ' メモリオブジェクトを取得
375 Dim pTempMemoryObject = GetMemoryObjectPtr( lpMem )
376
377 If (pTempMemoryObject->flags and _System_GC_FLAG_NEEDFREE)<>0 or isSweeping Then
378 iAllSize -= pTempMemoryObject->size
379
380 HeapFree( hHeap, 0, pTempMemoryObject->ptr - SizeOf(LONG_PTR) )
381 pTempMemoryObject->ptr = NULL
382 pTempMemoryObject->size = 0
383 Else
384 If isFinish = False Then
385 _System_DebugOnly_OutputDebugString( Ex"heap free missing!\r\n" )
386 End If
387 End If
388 LeaveCriticalSection(CriticalSection)
389 End Sub
390
391 /*!
392 @brief メモリオブジェクトを解放する
393 @param lpMem メモリオブジェクトへのポインタ
394 @author Daisuke Yamamoto
395 @date 2007/10/21
396 */
397 Sub __free(lpMem As VoidPtr)
398 __free_ex( lpMem, False )
399 End Sub
400
401 /*!
402 @brief 必要であればスウィープする
403 @author Daisuke Yamamoto
404 @date 2007/10/21
405 */
406 Sub TrySweep()
407 If isSweeping <> False or (iAllSize<limitMemorySize and countOfMemoryObjects<limitMemoryObjectNum) Then
408 'メモリ使用量が上限値を超えていないとき
409 Exit Sub
410 End If
411
412 Sweep()
413 End Sub
414
415 /*!
416 @brief スウィープする
417 @author Daisuke Yamamoto
418 @date 2007/10/21
419 */
420 Sub Sweep()
421 Dim hThread As HANDLE
422 Dim ThreadId As DWord
423 hThread=_beginthreadex(NULL,0,AddressOf(SweepOnOtherThread),VarPtr(This),0,ThreadId)
424 WaitForSingleObject(hThread,INFINITE)
425 CloseHandle(hThread)
426 isSweeping = False
427 End Sub
428
429Private
430
431 Static Function IsNull( object As Object ) As Boolean
432 Return Object.ReferenceEquals(object, Nothing)
433 End Function
434
435 /*!
436 @brief メモリオブジェクトの生存検地
437 @param pSample メモリオブジェクトへのポインタ
438 @author Daisuke Yamamoto
439 @date 2007/10/21
440 */
441 Function HitTest(pSample As VoidPtr) As Long
442 If pSample = NULL Then
443 Return -1
444 End If
445 If not( minPtr <= pSample and pSample <= maxPtr ) Then
446 Return -1
447 End If
448
449 Dim i As Long
450 For i=0 To ELM(countOfMemoryObjects)
451 If (pMemoryObjects[i].ptr As LONG_PTR)<=(pSample As LONG_PTR) and (pSample As LONG_PTR)<((pMemoryObjects[i].ptr As LONG_PTR)+pMemoryObjects[i].size) Then
452 Return i
453 End If
454 Next
455 Return -1
456 End Function
457
458 /*!
459 @brief オブジェクトのスキャン
460 @param pObject オブジェクトへのポインタ
461 pbMark マークリスト
462 @author Daisuke Yamamoto
463 @date 2007/10/21
464 */
465 Function ScanObject( classTypeInfo As ActiveBasic.Core._System_TypeForClass, pObject As *Object, pbMark As *Byte) As Boolean
466 If IsNull( classTypeInfo ) Then
467 Return False
468 End If
469
470 ' 基底クラスをスキャン
471 If Not IsNull( classTypeInfo.BaseType ) Then
472 Dim baseClassTypeInfo = Nothing As ActiveBasic.Core._System_TypeForClass
473 baseClassTypeInfo = classTypeInfo.BaseType As ActiveBasic.Core._System_TypeForClass
474 ScanObject( baseClassTypeInfo, pObject, pbMark )
475 End If
476
477 /*
478 _System_DebugOnly_OutputDebugString( " (scanning object)" )
479 _System_DebugOnly_OutputDebugString( classTypeInfo.Name )
480 _System_DebugOnly_OutputDebugString( Ex"\r\n" )
481 */
482
483 Dim i As Long
484 For i = 0 To ELM(classTypeInfo.numOfReference)
485 Scan( (pObject + classTypeInfo.referenceOffsets[i]) As *LONG_PTR, 1, pbMark )
486 Next
487
488 Return True
489 End Function
490 Function ScanObject(pObject As *Object, pbMark As *Byte) As Boolean
491 Dim classTypeInfo = Nothing As ActiveBasic.Core._System_TypeForClass
492 classTypeInfo = pObject->GetType() As ActiveBasic.Core._System_TypeForClass
493
494 If Object.ReferenceEquals( classTypeInfo, ActiveBasic.Core._System_TypeBase.selfTypeInfo ) Then
495 ' TypeInfoクラスの場合はTypeBaseImplクラスとして扱う
496 classTypeInfo = _System_TypeBase_Search( "ActiveBasic.Core.TypeBaseImpl" ) As ActiveBasic.Core._System_TypeForClass
497 End If
498
499 Return ScanObject( classTypeInfo, pObject, pbMark )
500 End Function
501
502 /*!
503 @brief メモリオブジェクトのスキャン
504 @param pStartPtr メモリオブジェクトへのポインタ
505 maxNum スキャンするメモリオブジェクトの個数
506 pbMark マークリスト
507 @author Daisuke Yamamoto
508 @date 2007/10/21
509 */
510 Sub Scan(pStartPtr As *LONG_PTR, maxNum As Long, pbMark As *Byte)
511 Dim i As Long, index As Long
512
513 For i=0 To ELM(maxNum)
514 index=HitTest(pStartPtr[i] As VoidPtr)
515 If index<>-1 Then
516 If pbMark[index]=0 Then
517 pbMark[index]=1
518
519 ' ジェネレーションカウントを増やす
520 pMemoryObjects[index].generationCount ++
521
522 If pMemoryObjects[index].flags and _System_GC_FLAG_OBJECT Then
523 ' オブジェクトの場合
524 If ScanObject( (pMemoryObjects[index].ptr + 4*SizeOf(LONG_PTR)) As *Object, pbMark) = False Then
525 Dim maxNum = (pMemoryObjects[index].size\SizeOf(LONG_PTR)) As Long
526 Scan(pMemoryObjects[index].ptr As *LONG_PTR, maxNum, pbMark)
527 End If
528
529 ElseIf (pMemoryObjects[index].flags and _System_GC_FLAG_ATOMIC)=0 Then
530 ' ヒープ領域がポインタ値を含む可能性があるとき
531 If pMemoryObjects[index].ptr = NULL Then
532 'エラー
533
534 End If
535
536 Dim maxNum = (pMemoryObjects[index].size\SizeOf(LONG_PTR)) As Long
537 Scan(pMemoryObjects[index].ptr As *LONG_PTR, maxNum, pbMark)
538 End If
539 End If
540 End If
541 Next
542 End Sub
543
544 /*!
545 @brief グローバル領域をルートに指定してスキャン
546 @param pbMark マークリスト
547 @author Daisuke Yamamoto
548 @date 2007/10/21
549 */
550 Sub GlobalScan( pbMark As *Byte )
551 Dim i As Long
552 For i = 0 To ELM( globalRootNum )
553 Scan( pGlobalRoots[i].ptr, pGlobalRoots[i].count, pbMark )
554 Next
555 End Sub
556
557 /*!
558 @brief ローカル領域をルートに指定してスキャン
559 @param pbMark マークリスト
560 @author Daisuke Yamamoto
561 @date 2007/10/21
562 */
563 Sub LocalScan( pbMark As *Byte )
564 Dim Context As CONTEXT
565 Dim NowSp As *LONG_PTR
566 Dim size As LONG_PTR
567 Dim i As Long
568 For i=0 To ELM(_System_pobj_AllThreads->ThreadNum)
569 Dim thread = _System_pobj_AllThreads->collection[i].thread
570 If Not ActiveBasic.IsNothing(thread) Then
571 FillMemory(VarPtr(Context),SizeOf(CONTEXT),0)
572 Context.ContextFlags=CONTEXT_CONTROL
573 If thread.__GetContext(Context)=0 Then
574 _System_DebugOnly_OutputDebugString(Ex"レジスタ情報の取得に失敗しました。\r\n")
575 End If
576
577#ifdef _WIN64
578 NowSp=Context.Rsp As *LONG_PTR
579#else
580 NowSp=Context.Esp As *LONG_PTR
581#endif
582
583 Dim size=(_System_pobj_AllThreads->collection[i].stackBase As LONG_PTR)-(NowSp As LONG_PTR)
584 Dim maxNum = (size\SizeOf(LONG_PTR)) As Long
585
586 If NowSp = 0 Then
587 debug
588 Exit Sub
589 End If
590
591 /*
592 _System_DebugOnly_OutputDebugString( "(scanning thread local)" )
593 _System_DebugOnly_OutputDebugString( thread.Name )
594 _System_DebugOnly_OutputDebugString( Ex"\r\n" )
595 */
596
597 Scan( NowSp, maxNum, pbMark )
598 End If
599 Next
600 End Sub
601
602 /*!
603 @brief 生存していないメモリオブジェクトを解放する
604 @param pbMark マークリスト
605 @author Daisuke Yamamoto
606 @date 2007/10/21
607 */
608 Sub DeleteGarbageMemories( pbMark As *Byte )
609
610 Dim isAllDelete = False
611 If pbMark = NULL Then
612 ' すべてを破棄するとき
613 isAllDelete = True
614 pbMark = _System_calloc( countOfMemoryObjects )
615 End If
616
617 Dim i As Long
618 For i=0 To ELM(countOfMemoryObjects)
619 If pbMark[i]=0 and pMemoryObjects[i].ptr<>0 and (pMemoryObjects[i].flags and _System_GC_FLAG_NEEDFREE)=0 Then
620 If pMemoryObjects[i].ptr = NULL Then
621 If isAllDelete Then
622 Continue
623 Else
624 debug
625 End If
626 End If
627
628 Dim ptr = pMemoryObjects[i].ptr
629 Dim size = pMemoryObjects[i].size
630
631 If (pMemoryObjects[i].flags and _System_GC_FLAG_OBJECT) <> 0 Then
632 /* ・オブジェクトの個数
633 ・オブジェクトのサイズ
634 ・デストラクタの関数ポインタ
635 ・リザーブ領域
636 を考慮 */
637 _System_SweepingDelete (ptr + SizeOf( LONG_PTR ) * 4 )
638 Else
639 __free_ex( ptr, True )
640 End If
641 End If
642 Next
643
644 If isAllDelete Then
645 _System_free( pbMark )
646 End If
647
648 End Sub
649
650 /*!
651 @brief GCが管理するすべてのメモリオブジェクトを解放する
652 @author Daisuke Yamamoto
653 @date 2007/10/21
654 */
655 Sub DeleteAllGarbageMemories()
656 DeleteGarbageMemories( NULL )
657 End Sub
658
659 /*!
660 @brief コンパクション
661 @author Daisuke Yamamoto
662 @date 2007/10/21
663 */
664 Sub Compaction()
665 Dim i As Long, i2 = 0 As Long
666 For i=0 To ELM(countOfMemoryObjects)
667 pMemoryObjects[i2] = pMemoryObjects[i]
668
669 If pMemoryObjects[i2].ptr Then
670 ' メモリオブジェクトの先頭部分にあるインデックスを書き換える
671 Set_LONG_PTR( pMemoryObjects[i2].ptr - SizeOf(LONG_PTR), i2 )
672
673 i2++
674 End If
675 Next
676 countOfMemoryObjects = i2
677 End Sub
678
679 /*!
680 @brief スウィープ(新規スレッドで呼び出す必要あり)
681 @author Daisuke Yamamoto
682 @date 2007/10/21
683 */
684 Function SweepOnOtherThread() As Long
685 Imports System.Threading.Detail
686 EnterCriticalSection(CriticalSection)
687
688 Dim startTime = GetTickCount()
689
690 _System_DebugOnly_OutputDebugString( Ex"garbage colletion sweep start!\r\n" )
691
692
693 'If isSweeping <> False or (iAllSize<limitMemorySize and countOfMemoryObjects<limitMemoryObjectNum) Then
694 ' ExitThread(0)
695 'End If
696 isSweeping = True
697
698 ' すべてのスレッドを一時停止
699 _System_pobj_AllThreads->SuspendAllThread()
700
701 ' マークリストを生成
702 Dim pbMark = _System_calloc(countOfMemoryObjects*SizeOf(Byte)) As *Byte
703
704 ' グローバル領域をルートに指定してスキャン
705 GlobalScan( pbMark )
706
707 ' ローカル領域をルートに指定してスキャン
708 LocalScan( pbMark )
709
710 ' スウィープ前のメモリサイズを退避
711 Dim iBackAllSize = iAllSize
712
713 ' スウィープ前のメモリオブジェクトの数
714 Dim iBeforeN = countOfMemoryObjects
715
716 '使われていないメモリを解放する
717 DeleteGarbageMemories(pbMark)
718
719 'コンパクション
720 Compaction()
721
722 'マークリストを解放
723 _System_free(pbMark)
724
725 If iBackAllSize <= iAllSize * 2 Then
726 If iAllSize > limitMemorySize Then
727 limitMemorySize = iAllSize
728 End If
729
730 '許容量を拡張する
731 limitMemorySize *= 2
732 limitMemoryObjectNum *= 2
733
734 _System_DebugOnly_OutputDebugString( Ex"memory size is extended for gc!\r\n" )
735 End If
736
737 Dim temp[100] As Char
738 wsprintf(temp,Ex"object items ... %d -> %d ( %d MB -> %d MB )\r\n",iBeforeN,countOfMemoryObjects, iBackAllSize\1024\1024, iAllSize\1024\1024)
739 _System_DebugOnly_OutputDebugString( temp )
740 wsprintf(temp,Ex"limit size of memory ... %d\r\n",limitMemorySize)
741 _System_DebugOnly_OutputDebugString( temp )
742 wsprintf(temp,Ex"garbage colletion sweep finish! (%d ms)\r\n\r\n", GetTickCount()-startTime)
743 _System_DebugOnly_OutputDebugString( temp )
744
745
746 '-------------------------------------
747 ' すべてのスレッドを再開
748 '-------------------------------------
749 _System_pobj_AllThreads->ResumeAllThread()
750
751 LeaveCriticalSection(CriticalSection)
752 End Function
753
754 /*!
755 @brief 未解放のメモリオブジェクトをデバッグ出力する
756 @author Daisuke Yamamoto
757 @date 2007/10/21
758 */
759 Sub DumpMemoryLeaks()
760 Dim isLeak = False
761 Dim i As Long
762 For i=0 To ELM(countOfMemoryObjects)
763 If pMemoryObjects[i].ptr Then
764 If (pMemoryObjects[i].flags and _System_GC_FLAG_NEEDFREE)<>0 Then
765 If isLeak = False Then
766 _System_DebugOnly_OutputDebugString( Ex"Detected memory leaks!\r\n" )
767 isLeak = True
768 End If
769
770 Dim temp[100] As Char
771 _System_DebugOnly_OutputDebugString( Ex"heap free missing!\r\n" )
772#ifdef _WIN64
773 wsprintf(temp,Ex"{%d} normal block at &H%p, %d bytes long.\r\n", i, pMemoryObjects[i].ptr, pMemoryObjects[i].size)
774#else
775 wsprintf(temp,Ex"{%d} normal block at &H%08X, %d bytes long.\r\n", i, pMemoryObjects[i].ptr, pMemoryObjects[i].size)
776#endif
777 _System_DebugOnly_OutputDebugString( temp )
778 End If
779 End If
780 Next
781
782 If isLeak Then
783 _System_DebugOnly_OutputDebugString( Ex"Object dump complete.\r\n" )
784 End If
785
786 End Sub
787
788End Class
789
790'GC管理用の特殊なシステムオブジェクト(デストラクタは最終のタイミングで呼び出されます)
791Dim _System_pGC As *_System_CGarbageCollection
792
793
794
795Function GC_malloc(size As Long) As VoidPtr
796 ' sweep
797 _System_pGC->TrySweep()
798
799 'allocate
800 Return _System_pGC->__malloc(size,0)
801End Function
802
803Function GC_malloc_atomic(size As Long) As VoidPtr
804 ' sweep
805 _System_pGC->TrySweep()
806
807 'allocate
808 Return _System_pGC->__malloc(size,_System_GC_FLAG_ATOMIC)
809End Function
810
811Function _System_GC_malloc_ForObject(size As Long) As VoidPtr
812 ' sweep
813 _System_pGC->TrySweep()
814
815 'allocate
816 Return _System_pGC->__malloc(size,_System_GC_FLAG_OBJECT or _System_GC_FLAG_INITZERO)
817End Function
818
819Function _System_GC_malloc_ForObjectPtr(size As Long) As VoidPtr
820 ' sweep
821 _System_pGC->TrySweep()
822
823 'allocate
824 Return _System_pGC->__malloc(size,_System_GC_FLAG_OBJECT or _System_GC_FLAG_INITZERO or _System_GC_FLAG_NEEDFREE)
825End Function
826
827Sub _System_GC_free_for_SweepingDelete( ptr As *Object )
828 ' free
829 _System_pGC->__free_ex( ptr, True )
830End Sub
Note: See TracBrowser for help on using the repository browser.