1/*
2 * Copyright (c) 2010 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LLVM_LICENSE_HEADER@
5 */
6
7//
8//  weakblockrecover.m
9//  testObjects
10//
11//  Created by Blaine Garst on 11/3/08.
12//  Copyright 2008 __MyCompanyName__. All rights reserved.
13//
14
15// TEST_CFLAGS -framework Foundation
16
17// rdar://5847976
18
19
20
21#import <Foundation/Foundation.h>
22#import <Block.h>
23#import <objc/objc-auto.h>
24#import "test.h"
25
26int Allocated = 0;
27int Recovered = 0;
28
29@interface TestObject : NSObject
30@end
31
32@implementation TestObject
33
34- (id)init {
35    ++Allocated;
36    return self;
37}
38- (void)dealloc {
39    ++Recovered;
40    [super dealloc];
41}
42- (void)finalize {
43    ++Recovered;
44    [super finalize];
45}
46
47
48@end
49
50void testRecovery() {
51    NSMutableArray *listOfBlocks = [NSMutableArray new];
52    for (int i = 0; i < 1000; ++i) {
53        __block TestObject *__weak to = [[TestObject alloc] init];
54        void (^block)(void) = ^ { printf("is it still real? %p\n", to); };
55        [listOfBlocks addObject:[block copy]];
56        [to release];
57    }
58    // let's see if we can recover any under GC circumstances
59    objc_collect(OBJC_EXHAUSTIVE_COLLECTION | OBJC_WAIT_UNTIL_DONE);
60
61    [listOfBlocks self]; // by using it here we keep listOfBlocks alive across the GC
62}
63
64int main() {
65    testRecovery();
66    if ((Recovered + 10) < Allocated) {
67        fail("Only %d weakly referenced test objects recovered, vs %d allocated\n", Recovered, Allocated);
68    }
69
70    succeed(__FILE__);
71}
72