Merge branch 'master' into nsgeometry-missing-func

This commit is contained in:
rfm 2024-11-19 14:10:12 +00:00 committed by GitHub
commit e0b37c4a1b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
146 changed files with 2155 additions and 1302 deletions

View file

@ -7,6 +7,33 @@
NSSizeFromCGSize and NSSizeToCGSizea functions.
* MISSING:
2024-11-19 Richard Frith-Macdonald <rfm@gnu.org>
* GSMime: fixed buffer overrun in rare circumstances when decoding
an encoded word in a header.
fix to cope with dealloc of uninitialised instances of GSMimeSMTPClient
* GSTLS: clean up used resources on exit
* NSCharacterSet: Fix retain count of cached character sets
* NSDateFormatter: fix to cope with dealloc of uninitialised instances
* NSFileManager: fix leak of enumerator when enumerating files at
a directory specified by URL
* NSHTTPCookie: fix buffer overrun parsing cookie header fields
* NSInvocation: fix leak of type information memory when passing
general struct argument/return values
* NSNumberFormatter: fix to cope with dealloc of uninitialised instances
* NSOperation: fix to cope with dealloc of uninitialised instances
* NSPredicate: fix leaks of keypath and set expressions
also fix leak of objects if exception occurs while scanning predicate
string
* NSPropertyList: fix leaks if exception occurs while parsing
* NSRegularExpression: fix leaks if exception occurs while parsing
* NSString: fix lead in dataUsingEncoding:allowLossyConversion:
* NSTimeZone: fix retain cycle in absolute time zones
fix leak of ICU calendar in -localizedName:locale:
* NSURL: fix leaks when initialising with unparseable string etc
* Testcases: fix many leaks so that most tests run to completion
without any leaked memory.
2024-11-14 Richard Frith-Macdonald <rfm@gnu.org>
* Source/NSBundle.m: Restructure a bit to expose resource lookup

View file

@ -46,6 +46,11 @@ extern "C" {
@class NSString;
@class NSPredicate;
/**
* This class provides an ordered set, a set where the order of the elements matters and
* is preserved. Once created the set cannot be modified. NSMutableOrderedSet can be
* modified.
*/
GS_EXPORT_CLASS
@interface GS_GENERIC_CLASS(NSOrderedSet, __covariant ElementT) : NSObject <NSCoding,
NSCopying,
@ -53,154 +58,530 @@ GS_EXPORT_CLASS
NSFastEnumeration>
// class methods
/**
* Create and return an empty ordered set.
*/
+ (instancetype) orderedSet;
/**
* Create and return an empty ordered set with the provided NSArray instance.
*/
+ (instancetype) orderedSetWithArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)objects;
/**
* Create and return an empty ordered set with the provided NSArray instance.
* Use the range to determine which elements to use. If flag is YES copy the
* elements.
*/
+ (instancetype) orderedSetWithArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)objects
range: (NSRange)range
copyItems: (BOOL)flag;
/**
* Create and return an ordered set with anObject as the sole member.
*/
+ (instancetype) orderedSetWithObject: (GS_GENERIC_TYPE(ElementT))anObject;
/**
* Create and return an ordered set with list of arguments starting with
* firstObject and terminated with nil.
*/
+ (instancetype) orderedSetWithObjects: (GS_GENERIC_TYPE(ElementT))firstObject, ...;
/**
* Create and return an ordered set using the C array of objects with count.
*/
+ (instancetype) orderedSetWithObjects: (const GS_GENERIC_TYPE(ElementT)[])objects
count: (NSUInteger) count;
/**
* Create and return an ordered set with the provided ordered set aSet.
*/
+ (instancetype) orderedSetWithOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet;
/**
* Create and return an ordered set with set aSet.
*/
+ (instancetype) orderedSetWithSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet;
/**
* Create and return an ordered set with the elements in aSet. If flag is YES,
* copy the elements.
*/
+ (instancetype) orderedSetWithSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet
copyItems: (BOOL)flag;
// instance methods
/**
* Initialize and return an empty ordered set with the provided NSArray instance.
*/
- (instancetype) initWithArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)array;
/**
* Initialize and return an empty ordered set with the provided NSArray instance.
* If flag is YES copy the elements.
*/
- (instancetype) initWithArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)array copyItems: (BOOL)flag;
/**
* Initialize and return an empty ordered set with the provided NSArray instance.
* Use the range to determine which elements to use. If flag is YES copy the
* elements.
*/
- (instancetype) initWithArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)array
range: (NSRange)range
copyItems: (BOOL)flag;
/**
* Initialize and return an ordered set with anObject as the sole member.
*/
- (instancetype) initWithObject: (id)object;
/**
* Initialize and return an ordered set with list of arguments starting with
* firstObject and terminated with nil.
*/
- (instancetype) initWithObjects: (GS_GENERIC_TYPE(ElementT))firstObject, ...;
- (instancetype) initWithObjects: (const GS_GENERIC_TYPE(ElementT)[])objects
count: (NSUInteger)count;
/**
* Initialize and return an ordered set using the C array of objects with count.
*/
- (instancetype) initWithOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet;
/**
* Initialize and return an ordered set with the elements in aSet. If flag is YES,
* copy the elements.
*/
- (instancetype) initWithOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet
copyItems: (BOOL)flag;
/**
* Initialize and return an empty ordered set with the provided NSArray instance.
* Use the range to determine which elements to use. If flag is YES copy the
* elements.
*/
- (instancetype) initWithOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet
range: (NSRange)range
copyItems: (BOOL)flag;
/**
* Initialize and return an ordered set with set aSet.
*/
- (instancetype) initWithSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet;
/**
* Initialize and return an ordered set with set aSet. If flag is YES, then copy the elements.
*/
- (instancetype) initWithSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet copyItems:(BOOL)flag;
/**
* Initialize an empty ordered set.
*/
- (instancetype) init;
/**
* Return the number of elements in the receiver.
*/
- (NSUInteger) count;
/**
* Returns YES if the receiver contains anObject.
*/
- (BOOL)containsObject: (GS_GENERIC_TYPE(ElementT))anObject;
/**
* Enumerate over the objects whose indexes are contained in indexSet, with the opts provided
* using aBlock.
*/
- (void) enumerateObjectsAtIndexes: (NSIndexSet *)indexSet
options: (NSEnumerationOptions)opts
usingBlock: (GSEnumeratorBlock)aBlock;
/**
* Enumerate over all objects in the receiver using aBlock.
*/
- (void) enumerateObjectsUsingBlock: (GSEnumeratorBlock)aBlock;
/**
* Enumerate over all objects in the receiver with aBlock utilizing the options specified by opts.
*/
- (void) enumerateObjectsWithOptions: (NSEnumerationOptions)opts
usingBlock: (GSEnumeratorBlock)aBlock;
/**
* First object in the receiver.
*/
- (GS_GENERIC_TYPE(ElementT)) firstObject;
/**
* Last object in the receiver.
*/
- (GS_GENERIC_TYPE(ElementT)) lastObject;
/**
* Returns the object at index in the receiver.
*/
- (GS_GENERIC_TYPE(ElementT)) objectAtIndex: (NSUInteger)index;
/**
* Returns the object at index in the receiver.
*/
- (GS_GENERIC_TYPE(ElementT)) objectAtIndexedSubscript: (NSUInteger)index;
/**
* Returns objects at the indexes specified in the receiver.
*/
- (GS_GENERIC_CLASS(NSArray, ElementT)*) objectsAtIndexes: (NSIndexSet *)indexes;
- (NSUInteger) indexOfObject: (GS_GENERIC_TYPE(ElementT))objects;
/**
* Returns the index of anObject in the receiver.
*/
- (NSUInteger) indexOfObject: (GS_GENERIC_TYPE(ElementT))anObject;
/**
* Returns the index of object key, contained within range, using options, and the provided comparator.
*/
- (NSUInteger) indexOfObject: (id)key
inSortedRange: (NSRange)range
options: (NSBinarySearchingOptions)options
usingComparator: (NSComparator)comparator;
/**
* Returns the index of objects at indexSet that pass the test in predicate with enumeration options opts.
*/
- (NSUInteger) indexOfObjectAtIndexes: (NSIndexSet *)indexSet
options: (NSEnumerationOptions)opts
passingTest: (GSPredicateBlock)predicate;
/**
* Returns the index of the first object passing test predicate.
*/
- (NSUInteger) indexOfObjectPassingTest: (GSPredicateBlock)predicate;
/**
* Returns the index of the first object passing test predicate using enumeration options opts.
*/
- (NSUInteger) indexOfObjectWithOptions: (NSEnumerationOptions)opts
passingTest: (GSPredicateBlock)predicate;
/**
* Returns an NSIndexSet containing indexes of object at indexes in indexSet matching predicate
* with enumeration options opts.
*/
- (NSIndexSet *) indexesOfObjectsAtIndexes: (NSIndexSet *)indexSet
options: (NSEnumerationOptions)opts
passingTest: (GSPredicateBlock)predicate;
- (NSIndexSet *)indexesOfObjectsPassingTest: (GSPredicateBlock)predicate;
/**
* Returns an NSIndexSet containing indexes that match predicate.
*/
- (NSIndexSet *) indexesOfObjectsPassingTest: (GSPredicateBlock)predicate;
/**
* Returns an NSIndexSet containing indexes that match predicate using opts.
*/
- (NSIndexSet *) indexesOfObjectsWithOptions: (NSEnumerationOptions)opts
passingTest: (GSPredicateBlock)predicate;
/**
* Returns an NSEnumerator to iterate over each object in the receiver.
*/
- (GS_GENERIC_CLASS(NSEnumerator, ElementT)*) objectEnumerator;
/**
* Returns an NSEnumerator to iterate over each object in the receiver in reverse order.
*/
- (GS_GENERIC_CLASS(NSEnumerator, ElementT)*) reverseObjectEnumerator;
/**
* Returns an NSOrderedSet that contains the same objects as the receiver, but in reverse order.
*/
- (NSOrderedSet *)reversedOrderedSet;
/**
* Returns a C array of objects in aBuffer at indexes specified by aRange.
*/
- (void) getObjects: (__unsafe_unretained GS_GENERIC_TYPE(ElementT)[])aBuffer
range: (NSRange)aRange;
// Key value coding support
/**
* Set value for key.
*/
- (void) setValue: (id)value forKey: (NSString*)key;
/**
* Returns the value for a given key.
*/
- (id) valueForKey: (NSString*)key;
// Comparing Sets
/**
* Returns YES if the receiver is equal to aSet.
*/
- (BOOL) isEqualToOrderedSet: (NSOrderedSet *)aSet;
// Set operations
/**
* Returns YES if the receiver intersects with ordered set aSet.
*/
- (BOOL) intersectsOrderedSet: (NSOrderedSet *)aSet;
/**
* Returns YES if the receiver intersects with set aSet.
*/
- (BOOL) intersectsSet: (NSSet *)aSet;
/**
* Returns YES if the receiver is a subset of ordered set aSet.
*/
- (BOOL) isSubsetOfOrderedSet: (NSOrderedSet *)aSet;
/**
* Returns YES if the receiver is a subset of set aSet.
*/
- (BOOL) isSubsetOfSet:(NSSet *)aSet;
// Creating a Sorted Array
/**
* Returns an NSArray instance containing the elements from the receiver sorted using sortDescriptors.
*/
- (GS_GENERIC_CLASS(NSArray, ElementT) *) sortedArrayUsingDescriptors: (NSArray *)sortDescriptors;
/**
* Returns an NSArray instance containing the elements from the receiver sorted using comparator.
*/
- (GS_GENERIC_CLASS(NSArray, ElementT) *) sortedArrayUsingComparator:
(NSComparator)comparator;
/**
* Returns an NSArray instance containing the elements from the receiver using options, sorted
* using comparator.
*/
- (GS_GENERIC_CLASS(NSArray, ElementT) *)
sortedArrayWithOptions: (NSSortOptions)options
usingComparator: (NSComparator)comparator;
// Filtering Ordered Sets
- (NSOrderedSet *)filteredOrderedSetUsingPredicate: (NSPredicate *)predicate;
/**
* Returns an NSOrderedSet instance containing elements filtered using predicate.
*/
- (NSOrderedSet *) filteredOrderedSetUsingPredicate: (NSPredicate *)predicate;
// Describing a set
/**
* Description of this NSOrderedSet.
*/
- (NSString *) description;
/**
* Localized description of this NSOrderedSet.
*/
- (NSString *) descriptionWithLocale: (NSLocale *)locale;
/**
* Localized description, indented if flag is YES.
*/
- (NSString *) descriptionWithLocale: (NSLocale *)locale indent: (BOOL)flag;
// Convert to other types
// Convert to other types
/**
* Returns an NSArray instance with the objects contained in the receiver.
*/
- (GS_GENERIC_CLASS(NSArray, ElementT) *) array;
/**
* Returns an NSSet instance with the objects contained in the receiver.
*/
- (GS_GENERIC_CLASS(NSSet, ElementT) *) set;
@end
// Mutable Ordered Set
/**
* This class provides a mutable ordered set.
*/
GS_EXPORT_CLASS
@interface GS_GENERIC_CLASS(NSMutableOrderedSet, ElementT) : GS_GENERIC_CLASS(NSOrderedSet, ElementT)
// Creating a Mutable Ordered Set
+ (instancetype)orderedSetWithCapacity: (NSUInteger)capacity;
- (instancetype)initWithCapacity: (NSUInteger)capacity;
/**
* Returns an ordered set with capacity.
*/
+ (instancetype) orderedSetWithCapacity: (NSUInteger)capacity;
/**
* Initializes an ordered set with capacity.
*/
- (instancetype) initWithCapacity: (NSUInteger)capacity;
/**
* Initializes an empty ordered set.
*/
- (instancetype) init;
- (void)addObject: (GS_GENERIC_TYPE(ElementT))anObject;
- (void)addObjects: (const GS_GENERIC_TYPE(ElementT)[])objects count: (NSUInteger)count;
- (void)addObjectsFromArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)otherArray;
- (void)insertObject: (GS_GENERIC_TYPE(ElementT))object atIndex: (NSUInteger)index;
- (void)setObject: (GS_GENERIC_TYPE(ElementT))object atIndexedSubscript: (NSUInteger)index;
- (void)insertObjects: (GS_GENERIC_CLASS(NSArray, ElementT)*)array atIndexes: (NSIndexSet *)indexes;
- (void)removeObject: (GS_GENERIC_TYPE(ElementT))object;
- (void)removeObjectAtIndex: (NSUInteger)index;
- (void)removeObjectsAtIndexes: (NSIndexSet *)indexes;
- (void)removeObjectsInArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)otherArray;
- (void)removeObjectsInRange: (NSRange)range;
- (void)removeAllObjects;
- (void)replaceObjectAtIndex: (NSUInteger)index
withObject: (GS_GENERIC_TYPE(ElementT))object;
/**
* Adds an object to the receiver.
*/
- (void) addObject: (GS_GENERIC_TYPE(ElementT))anObject;
/**
* Adds items in the C array whose length is indicated by count to the receiver.
*/
- (void) addObjects: (const GS_GENERIC_TYPE(ElementT)[])objects count: (NSUInteger)count;
/**
* Adds objects from otherArray to the receiver.
*/
- (void) addObjectsFromArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)otherArray;
/**
* Inserts object into the receiver at index.
*/
- (void) insertObject: (GS_GENERIC_TYPE(ElementT))object atIndex: (NSUInteger)index;
/**
* Sets the object at index/
*/
- (void) setObject: (GS_GENERIC_TYPE(ElementT))object atIndexedSubscript: (NSUInteger)index;
/**
* Inserts objects at indexes from array. The number of elements in indexes must be the same as the number of
* elements in array.
*/
- (void) insertObjects: (GS_GENERIC_CLASS(NSArray, ElementT)*)array atIndexes: (NSIndexSet *)indexes;
/**
* Remove object from receiver.
*/
- (void) removeObject: (GS_GENERIC_TYPE(ElementT))object;
/**
* Remove object at index.
*/
- (void) removeObjectAtIndex: (NSUInteger)index;
/**
* Remove objects at indexes.
*/
- (void) removeObjectsAtIndexes: (NSIndexSet *)indexes;
/**
* Remove objects matching items in otherArray.
*/
- (void) removeObjectsInArray: (GS_GENERIC_CLASS(NSArray, ElementT)*)otherArray;
/**
* Remove objects at indexes matching range.
*/
- (void) removeObjectsInRange: (NSRange)range;
/**
* Remove all objects from the set.
*/
- (void) removeAllObjects;
/**
* Replace the object at index with object.
*/
- (void) replaceObjectAtIndex: (NSUInteger)index
withObject: (GS_GENERIC_TYPE(ElementT))object;
/**
* Replace objects at indexes with objects. The number of objects must correspond to the number of indexes.
*/
- (void) replaceObjectsAtIndexes: (NSIndexSet *)indexes
withObjects: (GS_GENERIC_CLASS(NSArray, ElementT)*)objects;
/**
* Replace objects in the given range with items from the C array objects.
*/
- (void) replaceObjectsInRange: (NSRange)range
withObjects: (const GS_GENERIC_TYPE(ElementT)[])objects
count: (NSUInteger)count;
- (void)setObject: (GS_GENERIC_TYPE(ElementT))object atIndex: (NSUInteger)index;
- (void)moveObjectsAtIndexes: (NSIndexSet *)indexes toIndex: (NSUInteger)index;
/**
* Set object at index.
*/
- (void) setObject: (GS_GENERIC_TYPE(ElementT))object atIndex: (NSUInteger)index;
/**
* Move objects at indexes to index.
*/
- (void) moveObjectsAtIndexes: (NSIndexSet *)indexes toIndex: (NSUInteger)index;
/**
* Exchange object at index with object at otherIndex.
*/
- (void) exchangeObjectAtIndex: (NSUInteger)index withObjectAtIndex: (NSUInteger)otherIndex;
- (void)filterUsingPredicate: (NSPredicate *)predicate;
/**
* Filter objects using predicate.
*/
- (void) filterUsingPredicate: (NSPredicate *)predicate;
/**
* Sort using descriptors.
*/
- (void) sortUsingDescriptors: (NSArray *)descriptors;
/**
* Sort using comparator
*/
- (void) sortUsingComparator: (NSComparator)comparator;
/**
* Sort with options and comparator.
*/
- (void) sortWithOptions: (NSSortOptions)options
usingComparator: (NSComparator)comparator;
/**
* Sort the given range using options and comparator.
*/
- (void) sortRange: (NSRange)range
options: (NSSortOptions)options
usingComparator: (NSComparator)comparator;
/**
* This method leaves only objects that interesect with ordered set aSet in the receiver.
*/
- (void) intersectOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet;
/**
* This method leaves only objects that intersect with set aSet in the receiver.
*/
- (void) intersectSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet;
/**
* Receiver contains itself minus those elements in ordered set aSet.
*/
- (void) minusOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet;
/**
* Receiver contains itself minus those elements in aSet.
*/
- (void) minusSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet;
/**
* Receiver contains the union of itself and ordered set aSet.
*/
- (void) unionOrderedSet: (GS_GENERIC_CLASS(NSOrderedSet, ElementT)*)aSet;
/**
* Receiver contains the union of itself and aSet.
*/
- (void) unionSet: (GS_GENERIC_CLASS(NSSet, ElementT)*)aSet;
/**
* Implementation of NSCopying protocol.
*/
- (instancetype) initWithCoder: (NSCoder *)coder;
@end

View file

@ -219,16 +219,17 @@ extern "C" {
* set to YES).<br />
* Your class then has two options for performing clean-up when the process
* ends:
* <p>1. Use the +leaked: method to register objects which are simply to be
* retained until the process ends, and then either ignored or released
* depending on the clean-up setting in force. This mechanism is simple
* and should be sufficient for many classes.
* <p>1. Use the +keep:at: method to register static/global variables whose
* contents are to be retained for the lifetime of the program (up to exit)
* and either ignored or released depending on the clean-up setting in force
* when the program exits.<br />
* This mechanism is simple and should be sufficient for many classes.
* </p>
* <p>2. Implement a +atExit method to be run when the process ends and,
* within your +initialize implementation, call +shouldCleanUp to determine
* whether clean-up should be done, and if it returns YES then call
* +registerAtExit to have your +atExit method called when the process
* terminates.
* <p>2. Implement an +atExit method to be run when the process ends and,
* within your +initialize implementation, +registerAtExit to have your
* +atExit method called when the process exits. Within the +atExit method
* you may call +shouldCleanUp to determine whether celan up has been
* requested.
* </p>
* <p>The order in which 'leaked' objects are released and +atExit methods
* are called on process exist is the reverse of the order in which they
@ -241,25 +242,30 @@ extern "C" {
*/
+ (BOOL) isExiting;
/** This method informs the system that the object at anAddress has been
* intentionally leaked (will not be deallocated by higher level code)
* and should be cleaned up at process exit (and the address content
* zeroed out) if clean-up is enabled.
/** This method stores anObject at anAddress (which should be a static or
* global variable) and retains it. The code notes that the object should
* persist until the process exits. If clean-up is enabled the object will
* be released (and the address content zeroed out) upon process exit.
* If this method is called while the process is already exiting it
* simply zeros out the memory location then returns nil, otherwise
* it returns the object stored at the memory location.
* Raises an exception if anObject is nil or anAddress is NULL or the old
* value at anAddresss is not nil (unless the process is already exiting).
*/
+ (void) leaked: (id*)anAddress;
+ (id) NS_RETURNS_RETAINED keep: (id)anObject at: (id*)anAddress;
/** Deprecated: use +leaked: instead.
/** DEPRECATED ... use +keep:at: instead.
*/
+ (id) NS_RETURNS_RETAINED leak: (id)anObject ;//GS_DEPRECATED_FUNC;
+ (id) NS_RETURNS_RETAINED leak: (id)anObject;
/** Deprecated: use +leaked: instead.
/** DEPRECATED ... use +keep:at: instead.
*/
+ (id) NS_RETURNS_RETAINED leakAt: (id*)anAddress ;//GS_DEPRECATED_FUNC;
+ (id) NS_RETURNS_RETAINED leakAt: (id*)anAddress;
/** Sets the receiver to have its +atExit method called at the point when
* the process terminates.<br />
* Returns YES on success and NO on failure (if the class does not implement
* the method or if it is already registered to call it).<br />
* +atExit or if it is already registered to call it).<br />
* Implemented as a call to +registerAtExit: with the selector for the +atExit
* method as its argument.
*/
@ -268,7 +274,7 @@ extern "C" {
/** Sets the receiver to have the specified method called at the point when
* the process terminates.<br />
* Returns YES on success and NO on failure (if the class does not implement
* the method ir if it is already registered to call it).
* the method or if it is already registered to call a method at exit).
*/
+ (BOOL) registerAtExit: (SEL)aSelector;

View file

@ -3045,7 +3045,7 @@ unfold(const unsigned char *src, const unsigned char *end, BOOL *folded)
*/
if (tmp > src)
{
unsigned char buf[tmp - src];
unsigned char buf[tmp - src + 1];
unsigned char *ptr;
ptr = decodeWord(buf, src, tmp, encoding);
@ -8440,7 +8440,7 @@ GS_PRIVATE_INTERNAL(GSMimeSMTPClient)
- (void) dealloc
{
[self abort];
if (internal != nil)
if (GS_EXISTS_INTERNAL)
{
DESTROY(internal->reply);
DESTROY(internal->wdata);

View file

@ -180,8 +180,12 @@ handleExit()
BOOL unknownThread;
isExiting = YES;
/* We turn off zombies during exiting so that we don't leak deallocated
* objects during cleanup.
*/
// NSZombieEnabled = NO;
unknownThread = GSRegisterCurrentThread();
CREATE_AUTORELEASE_POOL(arp);
ENTER_POOL
while (exited != 0)
{
@ -193,6 +197,11 @@ handleExit()
Method method;
IMP msg;
if (shouldCleanUp)
{
fprintf(stderr, "*** clean-up +[%s %s]\n",
class_getName(tmp->obj), sel_getName(tmp->sel));
}
method = class_getClassMethod(tmp->obj, tmp->sel);
msg = method_getImplementation(method);
if (0 != msg)
@ -200,18 +209,28 @@ handleExit()
(*msg)(tmp->obj, tmp->sel);
}
}
else if (YES == shouldCleanUp)
else if (shouldCleanUp)
{
if (0 != tmp->at)
if (tmp->at)
{
tmp->obj = *(tmp->at);
if (tmp->obj != *(tmp->at))
{
fprintf(stderr,
"*** clean-up kept value %p at %p changed to %p\n",
tmp->obj, (const void*)tmp->at, *(tmp->at));
tmp->obj = *(tmp->at);
}
*(tmp->at) = nil;
}
fprintf(stderr, "*** clean-up -[%s release] %p %p\n",
class_getName(object_getClass(tmp->obj)),
tmp->obj, (const void*)tmp->at);
[tmp->obj release];
}
free(tmp);
}
DESTROY(arp);
LEAVE_POOL
if (unknownThread == YES)
{
GSUnregisterCurrentThread();
@ -226,26 +245,54 @@ handleExit()
return isExiting;
}
+ (void) leaked: (id*)anAddress
+ (id) keep: (id)anObject at: (id*)anAddress
{
struct exitLink *l;
NSAssert(*anAddress && [*anAddress isKindOfClass: [NSObject class]],
if (isExiting)
{
if (anAddress)
{
[*anAddress release];
*anAddress = nil;
}
return nil;
}
NSAssert([anObject isKindOfClass: [NSObject class]],
NSInvalidArgumentException);
l = (struct exitLink*)malloc(sizeof(struct exitLink));
l->at = anAddress;
l->obj = *anAddress;
l->sel = 0;
NSAssert(anAddress != NULL, NSInvalidArgumentException);
NSAssert(*anAddress == nil, NSInvalidArgumentException);
setup();
[exitLock lock];
for (l = exited; l != NULL; l = l->next)
{
if (l->at == anAddress)
{
[exitLock unlock];
[NSException raise: NSInvalidArgumentException
format: @"Repeated use of leak address %p", anAddress];
}
if (anObject != nil && anObject == l->obj)
{
[exitLock unlock];
[NSException raise: NSInvalidArgumentException
format: @"Repeated use of leak object %p", anObject];
}
}
ASSIGN(*anAddress, anObject);
l = (struct exitLink*)malloc(sizeof(struct exitLink));
l->at = anAddress;
l->obj = anObject;
l->sel = 0;
l->next = exited;
exited = l;
[exitLock unlock];
return l->obj;
}
+ (id) leakAt: (id*)anAddress
{
struct exitLink *l;
struct exitLink *l;
l = (struct exitLink*)malloc(sizeof(struct exitLink));
l->at = anAddress;
@ -263,12 +310,25 @@ handleExit()
{
struct exitLink *l;
if (nil == anObject || isExiting)
{
return nil;
}
setup();
[exitLock lock];
for (l = exited; l != NULL; l = l->next)
{
if (l->obj == anObject || (l->at != NULL && *l->at == anObject))
{
[exitLock unlock];
[NSException raise: NSInvalidArgumentException
format: @"Repeated use of leak object %p", anObject];
}
}
l = (struct exitLink*)malloc(sizeof(struct exitLink));
l->at = 0;
l->obj = [anObject retain];
l->sel = 0;
setup();
[exitLock lock];
l->next = exited;
exited = l;
[exitLock unlock];
@ -307,10 +367,16 @@ handleExit()
[exitLock lock];
for (l = exited; l != 0; l = l->next)
{
if (l->obj == self && sel_isEqual(l->sel, sel))
if (l->obj == self)
{
[exitLock unlock];
return NO; // Already registered
if (sel_isEqual(l->sel, sel))
{
fprintf(stderr,
"*** +[%s registerAtExit: %s] already registered for %s.\n",
class_getName(self), sel_getName(sel), sel_getName(l->sel));
[exitLock unlock];
return NO; // Already registered
}
}
}
l = (struct exitLink*)malloc(sizeof(struct exitLink));
@ -463,7 +529,13 @@ handleExit()
/* Dummy implementation
*/
@implementation NSObject(GSCleanup)
@implementation NSObject(GSCleanUp)
+ (id) keep: (id)anObject at: (id*)anAddress
{
ASSIGN(*anAddress, anObject);
return *anAddress;
}
+ (id) leakAt: (id*)anAddress
{

View file

@ -295,8 +295,7 @@ exitedThread(void *slot)
_sig = RETAIN(aSignature);
_numArgs = [aSignature numberOfArguments];
_info = [aSignature methodInfo];
_frame = cifframe_from_signature(_sig);
[_frame retain];
[self setupFrameFFI: _sig];
_cframe = [_frame mutableBytes];
/* Make sure we have somewhere to store the return value if needed.

View file

@ -1770,7 +1770,7 @@ NSDictionary *locale)
if (-1 == prec)
{
len = strlen(str); // Number of bytes to convert.
len = strlen(str); // Number of bytes to convert.
blen = len; // Size of unichar output buffer.
}
else

View file

@ -27,6 +27,7 @@
#import "Foundation/NSInvocation.h"
@class NSMutableData;
@class NSPointerArray;
typedef struct {
int offset;
@ -39,13 +40,17 @@ typedef struct {
} NSArgumentInfo;
@interface GSFFIInvocation : NSInvocation
@interface GSFFIInvocation : NSInvocation
{
@public
uint8_t _retbuf[32]; // Store return values of up to 32 bytes here.
NSMutableData *_frame;
uint8_t _retbuf[32]; // Return values of up to 32 bytes here.
NSMutableData *_frame; // Frame information for invoking.
NSPointerArray *_extra; // Extra FFI data to be released.
}
@end
@interface GSFFIInvocation (FFI)
- (void) setupFrameFFI: (NSMethodSignature*)sig;
@end
@interface GSFFCallInvocation : NSInvocation
{

View file

@ -24,6 +24,7 @@
#import "common.h"
#import "GSPrivate.h"
#import "GNUstepBase/GSLocale.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSLock.h"
@ -222,7 +223,7 @@ GSDomainFromDefaultLocale(void)
*/
if (saved == nil)
{
saved = [NSObject leak: dict];
[NSObject keep: AUTORELEASE([dict copy]) at: &saved];
}
/**
@ -261,6 +262,7 @@ GSLanguageFromLocale(NSString *locale)
|| [locale length] < 2)
return @"English";
ENTER_POOL
gbundle = [NSBundle bundleForLibrary: @"gnustep-base"];
aliases = [gbundle pathForResource: @"Locale"
ofType: @"aliases"
@ -270,22 +272,27 @@ GSLanguageFromLocale(NSString *locale)
NSDictionary *dict;
dict = [NSDictionary dictionaryWithContentsOfFile: aliases];
language = [dict objectForKey: locale];
language = [[dict objectForKey: locale] copy];
if (language == nil && [locale pathExtension] != nil)
{
locale = [locale stringByDeletingPathExtension];
if ([locale isEqual: @"C"] || [locale isEqual: @"POSIX"])
return @"English";
language = [dict objectForKey: locale];
{
language = @"English";
}
else
{
language = [[dict objectForKey: locale] copy];
}
}
if (language == nil)
{
locale = [locale substringWithRange: NSMakeRange(0, 2)];
language = [dict objectForKey: locale];
language = [[dict objectForKey: locale] copy];
}
}
return language;
LEAVE_POOL
return AUTORELEASE(language);
}
NSArray *

View file

@ -32,6 +32,7 @@
@class _GSMutableInsensitiveDictionary;
@class NSNotification;
@class NSPointerArray;
@class NSRecursiveLock;
#if ( (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) ) && HAVE_VISIBILITY_ATTRIBUTE )
@ -555,17 +556,18 @@ GSPrivateUnloadModule(FILE *errorStream,
*/
@interface GSCodeBuffer : NSObject
{
unsigned size;
void *buffer;
void *executable;
id frame;
unsigned size;
void *buffer;
void *executable;
id frame;
NSPointerArray *extra;
}
+ (GSCodeBuffer*) memoryWithSize: (NSUInteger)_size;
- (void*) buffer;
- (void*) executable;
- (id) initWithSize: (NSUInteger)_size;
- (void) protect;
- (void) setFrame: (id)aFrame;
- (void) setFrame: (id)aFrame extra: (NSPointerArray*)pa;
@end
/* For tuning socket connections

View file

@ -188,9 +188,22 @@ static gnutls_anon_client_credentials_t anoncred;
*/
@implementation GSTLSObject
static NSLock *certificateListLock = nil;
static NSMutableDictionary *certificateListCache = nil;
static NSLock *credentialsLock = nil;
static NSMutableDictionary *credentialsCache = nil;
static NSLock *fileLock = nil;
static NSMutableDictionary *fileMap = nil;
static NSLock *paramsLock = nil;
static NSMutableDictionary *paramsCache = nil;
static NSLock *privateKeyLock = nil;
static NSMutableDictionary *privateKeyCache0 = nil;
static NSMutableDictionary *privateKeyCache1 = nil;
+ (void) _defaultsChanged: (NSNotification*)n
{
NSBundle *bundle;
@ -289,6 +302,21 @@ static NSMutableDictionary *fileMap = nil;
gnutls_global_set_log_level(globalDebug);
}
+ (void) atExit
{
DESTROY(certificateListLock);
DESTROY(certificateListCache);
DESTROY(credentialsLock);
DESTROY(credentialsCache);
DESTROY(fileLock);
DESTROY(fileMap);
DESTROY(paramsLock);
DESTROY(paramsCache);
DESTROY(privateKeyLock);
DESTROY(privateKeyCache0);
DESTROY(privateKeyCache1);
}
+ (NSData*) dataForTLSFile: (NSString*)fileName
{
NSData *result;
@ -328,6 +356,8 @@ static NSMutableDictionary *fileMap = nil;
{
beenHere = YES;
[self registerAtExit];
fileLock = [NSLock new];
fileMap = [NSMutableDictionary new];
@ -397,8 +427,6 @@ static NSMutableDictionary *fileMap = nil;
@end
@implementation GSTLSDHParams
static NSLock *paramsLock = nil;
static NSMutableDictionary *paramsCache = nil;
static NSTimeInterval paramsWhen = 0.0;
static BOOL paramsGenerating = NO;
static GSTLSDHParams *paramsCurrent = nil;
@ -496,10 +524,8 @@ static GSTLSDHParams *paramsCurrent = nil;
if (nil == paramsLock)
{
paramsLock = [NSLock new];
[[NSObject leakAt: &paramsLock] release];
paramsWhen = [NSDate timeIntervalSinceReferenceDate];
paramsCache = [NSMutableDictionary new];
[[NSObject leakAt: &paramsCache] release];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
name: @"GSHousekeeping" object: nil];
@ -570,8 +596,6 @@ static GSTLSDHParams *paramsCurrent = nil;
@implementation GSTLSCertificateList
static NSLock *certificateListLock = nil;
static NSMutableDictionary *certificateListCache = nil;
+ (void) certInfo: (gnutls_x509_crt_t)cert to: (NSMutableString*)str
{
@ -700,9 +724,7 @@ static NSMutableDictionary *certificateListCache = nil;
if (nil == certificateListLock)
{
certificateListLock = [NSLock new];
[[NSObject leakAt: &certificateListLock] release];
certificateListCache = [NSMutableDictionary new];
[[NSObject leakAt: &certificateListCache] release];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
name: @"GSHousekeeping" object: nil];
@ -884,9 +906,6 @@ static NSMutableDictionary *certificateListCache = nil;
@implementation GSTLSPrivateKey
static NSLock *privateKeyLock = nil;
static NSMutableDictionary *privateKeyCache0 = nil;
static NSMutableDictionary *privateKeyCache1 = nil;
/* Method to purge older keys from cache.
*/
@ -940,11 +959,8 @@ static NSMutableDictionary *privateKeyCache1 = nil;
if (nil == privateKeyLock)
{
privateKeyLock = [NSLock new];
[[NSObject leakAt: &privateKeyLock] release];
privateKeyCache0 = [NSMutableDictionary new];
[[NSObject leakAt: &privateKeyCache0] release];
privateKeyCache1 = [NSMutableDictionary new];
[[NSObject leakAt: &privateKeyCache1] release];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)
@ -1074,8 +1090,6 @@ static NSMutableDictionary *privateKeyCache1 = nil;
@implementation GSTLSCredentials
static NSLock *credentialsLock = nil;
static NSMutableDictionary *credentialsCache = nil;
/* Method to purge older credentials from cache.
*/
@ -1106,9 +1120,7 @@ static NSMutableDictionary *credentialsCache = nil;
if (nil == credentialsLock)
{
credentialsLock = [NSLock new];
[[NSObject leakAt: &credentialsLock] release];
credentialsCache = [NSMutableDictionary new];
[[NSObject leakAt: &credentialsCache] release];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(housekeeping:)

View file

@ -114,7 +114,23 @@ static SEL rlSel;
defaultPlaceholderArray = nil;
NSDeallocateObject(o);
DESTROY(placeholderMap);
/* Deallocate all the placeholders in the map before destroying it.
*/
GS_MUTEX_LOCK(placeholderLock);
if (placeholderMap)
{
NSMapEnumerator mEnum = NSEnumerateMapTable(placeholderMap);
Class c;
id o;
while (NSNextMapEnumeratorPair(&mEnum, (void *)&c, (void *)&o))
{
NSDeallocateObject(o);
}
NSEndMapTableEnumeration(&mEnum);
DESTROY(placeholderMap);
}
GS_MUTEX_UNLOCK(placeholderLock);
}
+ (void) initialize
@ -176,7 +192,7 @@ static SEL rlSel;
*/
GS_MUTEX_LOCK(placeholderLock);
obj = (id)NSMapGet(placeholderMap, (void*)z);
if (obj == nil)
if (obj == nil && NO == [NSObject isExiting])
{
/*
* There is no placeholder object for this zone, so we

View file

@ -632,6 +632,15 @@ static Class concreteMutableClass = nil;
return abstractClass;
}
- (void) dealloc
{
if (cache_map[_index] == self)
{
cache_map[_index] = nil;
}
[super dealloc];
}
- (void) encodeWithCoder: (NSCoder*)aCoder
{
[aCoder encodeValueOfObjCType: @encode(int) at: &_index];
@ -707,6 +716,20 @@ static Class concreteMutableClass = nil;
@implementation NSCharacterSet
static gs_mutex_t cache_lock = GS_MUTEX_INIT_STATIC;
+ (void) atExit
{
unsigned i;
for (i = 0; i < MAX_STANDARD_SETS; i++)
{
GS_MUTEX_LOCK(cache_lock);
DESTROY(cache_set[i]);
GS_MUTEX_UNLOCK(cache_lock);
}
}
+ (void) initialize
{
static BOOL beenHere = NO;
@ -723,6 +746,7 @@ static Class concreteMutableClass = nil;
concreteMutableClass = [NSMutableBitmapCharSet class];
#endif
beenHere = YES;
[self registerAtExit];
}
}
@ -735,7 +759,7 @@ static Class concreteMutableClass = nil;
length: (unsigned)length
number: (int)number
{
static gs_mutex_t cache_lock = GS_MUTEX_INIT_STATIC;
NSCharacterSet *set;
GS_MUTEX_LOCK(cache_lock);
if (cache_set[number] == nil && bytes != 0)
@ -747,11 +771,11 @@ static Class concreteMutableClass = nil;
freeWhenDone: NO];
cache_set[number]
= [[_GSStaticCharSet alloc] initWithBitmap: bitmap number: number];
[[NSObject leakAt: &cache_set[number]] release];
RELEASE(bitmap);
}
set = RETAIN(cache_set[number]);
GS_MUTEX_UNLOCK(cache_lock);
return cache_set[number];
return AUTORELEASE(set);
}
+ (id) alphanumericCharacterSet

View file

@ -856,9 +856,9 @@ static NSLock *cached_proxies_gate = nil;
{
if (debug_connection)
NSLog(@"deallocating %@", self);
[self finalize];
if (internal != nil)
if (GS_EXISTS_INTERNAL)
{
[self finalize];
GS_DESTROY_INTERNAL(NSConnection);
}
[super dealloc];

View file

@ -155,7 +155,7 @@ static NSDateFormatterBehavior _defaultBehavior = 0;
- (void) dealloc
{
RELEASE(_dateFormat);
if (internal != 0)
if (GS_EXISTS_INTERNAL)
{
RELEASE(internal->_locale);
RELEASE(internal->_tz);

View file

@ -469,6 +469,7 @@ static SEL appSel;
if (objectCount != [keys count])
{
RELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"init with obj and key arrays of different sizes"];
}

View file

@ -114,6 +114,13 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
return nil;
}
+ (void) atExit
{
DESTROY(locCenter);
DESTROY(pubCenter);
DESTROY(netCenter);
}
/**
* Returns the default notification center ... a shared notification
* center for the local host. This is simply a convenience method
@ -125,6 +132,11 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
return [self notificationCenterForType: NSLocalNotificationCenterType];
}
+ (void) initialize
{
[self registerAtExit];
}
/**
* Returns a notification center of the specified type.<br />
* The <code>NSLocalNotificationCenterType</code> provides a shared access to
@ -144,7 +156,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
if (locCenter == nil)
{
GS_MUTEX_LOCK(classLock);
if (locCenter == nil)
if (locCenter == nil && NO == [NSObject isExiting])
{
NS_DURING
{
@ -154,8 +166,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
NSAllocateObject(self, 0, NSDefaultMallocZone());
tmp->_centerLock = [NSRecursiveLock new];
tmp->_type = RETAIN(NSLocalNotificationCenterType);
locCenter = [NSObject leak: tmp];
[tmp release];
locCenter = tmp;
}
NS_HANDLER
{
@ -173,7 +184,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
if (pubCenter == nil)
{
GS_MUTEX_LOCK(classLock);
if (pubCenter == nil)
if (pubCenter == nil && NO == [NSObject isExiting])
{
NS_DURING
{
@ -183,8 +194,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
NSAllocateObject(self, 0, NSDefaultMallocZone());
tmp->_centerLock = [NSRecursiveLock new];
tmp->_type = RETAIN(GSPublicNotificationCenterType);
pubCenter = [NSObject leak: tmp];
[tmp release];
pubCenter = tmp;
}
NS_HANDLER
{
@ -202,7 +212,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
if (netCenter == nil)
{
GS_MUTEX_LOCK(classLock);
if (netCenter == nil)
if (netCenter == nil && NO == [NSObject isExiting])
{
NS_DURING
{
@ -212,8 +222,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
NSAllocateObject(self, 0, NSDefaultMallocZone());
tmp->_centerLock = [NSRecursiveLock new];
tmp->_type = RETAIN(GSNetworkNotificationCenterType);
netCenter = [NSObject leak: tmp];
[tmp release];
netCenter = tmp;
}
NS_HANDLER
{

View file

@ -91,11 +91,11 @@ static Class NSFileHandle_ssl_class = nil;
{
if (self == NSFileHandle_abstract_class)
{
return NSAllocateObject (NSFileHandle_concrete_class, 0, z);
return NSAllocateObject(NSFileHandle_concrete_class, 0, z);
}
else
{
return NSAllocateObject (self, 0, z);
return NSAllocateObject(self, 0, z);
}
}

View file

@ -989,7 +989,7 @@ static gs_mutex_t classLock = GS_MUTEX_INIT_STATIC;
errorHandler: handler
for: self];
return direnum;
return AUTORELEASE(direnum);
}
- (NSArray*) contentsOfDirectoryAtPath: (NSString*)path error: (NSError**)error

View file

@ -197,19 +197,21 @@ static NSMutableArray *GSCookieStrings(NSString *string);
+ (NSArray *) cookiesWithResponseHeaderFields: (NSDictionary *)headerFields
forURL: (NSURL *)URL
{
NSEnumerator *henum = [headerFields keyEnumerator];
NSMutableArray *a = [NSMutableArray array];
NSString *header;
NSEnumerator *henum = [headerFields keyEnumerator];
NSMutableArray *a = [NSMutableArray array];
NSString *header;
while ((header = [henum nextObject]))
{
NSMutableArray *suba
= [self _parseField: [headerFields objectForKey: header]
forHeader: header andURL: URL];
NSString *field = [headerFields objectForKey: header];
NSMutableArray *suba = [self _parseField: field
forHeader: header
andURL: URL];
if (suba)
[a addObjectsFromArray: suba];
{
[a addObjectsFromArray: suba];
}
}
return a;
}
@ -825,7 +827,7 @@ GSPropertyListFromCookieFormat(NSString *string, int version)
}
RELEASE(key);
RELEASE(val);
if (pld->ptr[pld->pos] == ';')
if (pld->pos < pld->end && pld->ptr[pld->pos] == ';')
{
pld->pos++;
}

View file

@ -31,6 +31,7 @@
#import "Foundation/NSCoder.h"
#import "Foundation/NSData.h"
#import "Foundation/NSInvocation.h"
#import "Foundation/NSPointerArray.h"
#import "Foundation/NSZone.h"
#import "GSInvocation.h"
#import "GSPrivate.h"
@ -70,6 +71,7 @@
- (void) dealloc
{
DESTROY(frame);
DESTROY(extra);
if (size > 0)
{
#if defined(HAVE_FFI_PREP_CLOSURE_LOC)
@ -173,9 +175,10 @@
#endif
}
- (void) setFrame: (id)aFrame
- (void) setFrame: (id)aFrame extra: (NSPointerArray*)pa
{
ASSIGN(frame, aFrame);
ASSIGN(extra, pa);
}
@end

View file

@ -121,6 +121,7 @@
[_invocation getReturnValue: buffer];
result = [NSValue valueWithBytes: buffer objCType: returnType];
free(buffer);
}
}
return result;

View file

@ -48,7 +48,6 @@ static NSNull *null = 0;
if (null == 0)
{
null = (NSNull*)NSAllocateObject(self, 0, NSDefaultMallocZone());
[[NSObject leakAt: &null] release];
}
}

View file

@ -559,7 +559,7 @@ static NSUInteger _defaultBehavior = NSNumberFormatterBehavior10_4;
RELEASE(_attributedStringForNil);
RELEASE(_attributedStringForNotANumber);
RELEASE(_attributedStringForZero);
if (internal != 0)
if (GS_EXISTS_INTERNAL)
{
int idx;

View file

@ -171,13 +171,13 @@ extern void GSLogZombie(id o, SEL sel)
}
if (c == 0)
{
NSLog(@"*** -[??? %@]: message sent to deallocated instance %p",
NSStringFromSelector(sel), o);
fprintf(stderr, "*** -[??? %s]: message sent to deallocated instance %p",
sel_getName(sel), o);
}
else
{
NSLog(@"*** -[%@ %@]: message sent to deallocated instance %p",
c, NSStringFromSelector(sel), o);
fprintf(stderr, "*** -[%s %s]: message sent to deallocated instance %p",
class_getName(c), sel_getName(sel), o);
}
if (GSPrivateEnvironmentFlag("CRASH_ON_ZOMBIE", NO) == YES)
{
@ -814,7 +814,7 @@ NSDeallocateObject(id anObject)
(*finalize_imp)(anObject, finalize_sel);
AREM(aClass, (id)anObject);
if (NSZombieEnabled == YES)
if (NSZombieEnabled)
{
#ifdef OBJC_CAP_ARC
if (0 != zombieMap)
@ -1086,12 +1086,14 @@ static id gs_weak_load(id obj)
+ (void) _atExit
{
/*
NSMapTable *m = nil;
GS_MUTEX_LOCK(allocationLock);
m = zombieMap;
zombieMap = nil;
GS_MUTEX_UNLOCK(allocationLock);
DESTROY(m);
*/
}
/**

View file

@ -75,8 +75,6 @@ static void *isFinishedCtxt = (void*)"isFinished";
static void *isReadyCtxt = (void*)"isReady";
static void *queuePriorityCtxt = (void*)"queuePriority";
static NSArray *empty = nil;
@interface NSOperation (Private)
- (void) _finish;
- (void) _updateReadyState;
@ -91,12 +89,6 @@ static NSArray *empty = nil;
return NO;
}
+ (void) initialize
{
empty = [NSArray new];
RELEASE([NSObject leakAt: &empty]);
}
- (void) addDependency: (NSOperation *)op
{
if (NO == [op isKindOfClass: [NSOperation class]])
@ -201,7 +193,7 @@ static NSArray *empty = nil;
{
/* Only clean up if ivars have been initialised
*/
if (internal && internal->lock)
if (GS_EXISTS_INTERNAL && internal->lock != nil)
{
NSOperation *op;
@ -219,7 +211,7 @@ static NSArray *empty = nil;
RELEASE(internal->completionBlock);
GS_DESTROY_INTERNAL(NSOperation);
}
[super dealloc];
DEALLOC
}
- (NSArray *) dependencies
@ -228,7 +220,7 @@ static NSArray *empty = nil;
if (internal->dependencies == nil)
{
a = empty; // OSX return an empty array
a = [NSArray array]; // OSX return an empty array
}
else
{
@ -576,7 +568,7 @@ static NSArray *empty = nil;
- (void) dealloc
{
RELEASE(_executionBlocks);
[super dealloc];
DEALLOC
}
- (NSArray *) executionBlocks
@ -807,15 +799,18 @@ static NSOperationQueue *mainQueue = nil;
- (void) dealloc
{
[self cancelAllOperations];
DESTROY(internal->operations);
DESTROY(internal->starting);
DESTROY(internal->waiting);
DESTROY(internal->name);
DESTROY(internal->cond);
DESTROY(internal->lock);
GS_DESTROY_INTERNAL(NSOperationQueue);
[super dealloc];
if (GS_EXISTS_INTERNAL && internal->lock != nil)
{
[self cancelAllOperations];
DESTROY(internal->operations);
DESTROY(internal->starting);
DESTROY(internal->waiting);
DESTROY(internal->name);
DESTROY(internal->cond);
DESTROY(internal->lock);
GS_DESTROY_INTERNAL(NSOperationQueue);
}
DEALLOC
}
- (id) init
@ -834,7 +829,8 @@ static NSOperationQueue *mainQueue = nil;
internal->cond = [[NSConditionLock alloc] initWithCondition: 0];
[internal->cond setName:
[NSString stringWithFormat: @"cond-for-op-%p", self]];
internal->name = [[NSString alloc] initWithFormat: @"NSOperationQueue %p", self];
internal->name
= [[NSString alloc] initWithFormat: @"NSOperationQueue %p", self];
/* Ensure that default thread name can be displayed on systems with a
* limited thread name length.

View file

@ -133,36 +133,26 @@ extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
}
@end
@interface GSKeyPathCompositionExpression : NSExpression
@interface GSBinaryExpression : NSExpression
{
@public
NSExpression *_left;
NSExpression *_right;
}
- (NSExpression *) leftExpression;
- (NSExpression *) rightExpression;
@end
@interface GSUnionSetExpression : NSExpression
{
@public
NSExpression *_left;
NSExpression *_right;
}
@interface GSKeyPathCompositionExpression : GSBinaryExpression
@end
@interface GSIntersectSetExpression : NSExpression
{
@public
NSExpression *_left;
NSExpression *_right;
}
@interface GSUnionSetExpression : GSBinaryExpression
@end
@interface GSMinusSetExpression : NSExpression
{
@public
NSExpression *_left;
NSExpression *_right;
}
@interface GSIntersectSetExpression : GSBinaryExpression
@end
@interface GSMinusSetExpression : GSBinaryExpression
@end
@interface GSSubqueryExpression : NSExpression
@ -224,10 +214,9 @@ extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
GSPredicateScanner *s;
NSPredicate *p;
s = [[GSPredicateScanner alloc] initWithString: format
args: args];
s = AUTORELEASE([[GSPredicateScanner alloc] initWithString: format
args: args]);
p = [s parse];
RELEASE(s);
return p;
}
@ -357,10 +346,9 @@ extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
}
}
}
s = [[GSPredicateScanner alloc] initWithString: format
args: arr];
s = AUTORELEASE([[GSPredicateScanner alloc] initWithString: format
args: arr]);
p = [s parse];
RELEASE(s);
return p;
}
@ -519,7 +507,7 @@ extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
- (void) dealloc
{
RELEASE(_subs);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone *)z
@ -755,7 +743,7 @@ extern void GSPropertyListMake(id,NSDictionary*,BOOL,BOOL,unsigned,id*);
{
RELEASE(_left);
RELEASE(_right);
[super dealloc];
DEALLOC
}
- (NSComparisonPredicateModifier) comparisonPredicateModifier
@ -1245,10 +1233,10 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
{
GSConstantValueExpression *e;
e = [[GSConstantValueExpression alloc]
initWithExpressionType: NSConstantValueExpressionType];
e = AUTORELEASE([[GSConstantValueExpression alloc]
initWithExpressionType: NSConstantValueExpressionType]);
ASSIGN(e->_obj, obj);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForEvaluatedObject
@ -1262,8 +1250,8 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
GSFunctionExpression *e;
NSString *s;
e = [[GSFunctionExpression alloc]
initWithExpressionType: NSFunctionExpressionType];
e = AUTORELEASE([[GSFunctionExpression alloc]
initWithExpressionType: NSFunctionExpressionType]);
s = [NSString stringWithFormat: @"_eval_%@:", name];
e->_selector = NSSelectorFromString(s);
if (![e respondsToSelector: e->_selector])
@ -1279,7 +1267,7 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
else if ([name isEqualToString: @"_mul"]) e->_op = @"*";
else if ([name isEqualToString: @"_div"]) e->_op = @"/";
else if ([name isEqualToString: @"_pow"]) e->_op = @"**";
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForKeyPath: (NSString *)path
@ -1291,10 +1279,10 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
[NSException raise: NSInvalidArgumentException
format: @"Keypath is not NSString: %@", path];
}
e = [[GSKeyPathExpression alloc]
initWithExpressionType: NSKeyPathExpressionType];
e = AUTORELEASE([[GSKeyPathExpression alloc]
initWithExpressionType: NSKeyPathExpressionType]);
ASSIGN(e->_keyPath, path);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForKeyPathCompositionWithLeft: (NSExpression*)left
@ -1302,21 +1290,21 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
{
GSKeyPathCompositionExpression *e;
e = [[GSKeyPathCompositionExpression alloc]
initWithExpressionType: NSKeyPathCompositionExpressionType];
e = AUTORELEASE([[GSKeyPathCompositionExpression alloc]
initWithExpressionType: NSKeyPathCompositionExpressionType]);
ASSIGN(e->_left, left);
ASSIGN(e->_right, right);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForVariable: (NSString *)string
{
GSVariableExpression *e;
e = [[GSVariableExpression alloc]
initWithExpressionType: NSVariableExpressionType];
e = AUTORELEASE([[GSVariableExpression alloc]
initWithExpressionType: NSVariableExpressionType]);
ASSIGN(e->_variable, string);
return AUTORELEASE(e);
return e;
}
// 10.5 methods...
@ -1325,23 +1313,23 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
{
GSIntersectSetExpression *e;
e = [[GSIntersectSetExpression alloc]
initWithExpressionType: NSIntersectSetExpressionType];
e = AUTORELEASE([[GSIntersectSetExpression alloc]
initWithExpressionType: NSIntersectSetExpressionType]);
ASSIGN(e->_left, left);
ASSIGN(e->_right, right);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForAggregate: (NSArray *)subExpressions
{
GSAggregateExpression *e;
e = [[GSAggregateExpression alloc]
initWithExpressionType: NSAggregateExpressionType];
e = AUTORELEASE([[GSAggregateExpression alloc]
initWithExpressionType: NSAggregateExpressionType]);
ASSIGN(e->_collection, [NSSet setWithArray: subExpressions]);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForUnionSet: (NSExpression *)left
@ -1349,12 +1337,12 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
{
GSUnionSetExpression *e;
e = [[GSUnionSetExpression alloc]
initWithExpressionType: NSUnionSetExpressionType];
e = AUTORELEASE([[GSUnionSetExpression alloc]
initWithExpressionType: NSUnionSetExpressionType]);
ASSIGN(e->_left, left);
ASSIGN(e->_right, right);
return AUTORELEASE(e);
return e;
}
+ (NSExpression *) expressionForMinusSet: (NSExpression *)left
@ -1362,12 +1350,12 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
{
GSMinusSetExpression *e;
e = [[GSMinusSetExpression alloc]
initWithExpressionType: NSMinusSetExpressionType];
e = AUTORELEASE([[GSMinusSetExpression alloc]
initWithExpressionType: NSMinusSetExpressionType]);
ASSIGN(e->_left, left);
ASSIGN(e->_right, right);
return AUTORELEASE(e);
return e;
}
// end 10.5 methods
@ -1587,7 +1575,7 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
- (void) dealloc
{
RELEASE(_obj);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone*)zone
@ -1651,7 +1639,7 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
- (void) dealloc;
{
RELEASE(_variable);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone*)zone
@ -1700,7 +1688,7 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
- (void) dealloc;
{
RELEASE(_keyPath);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone*)zone
@ -1719,6 +1707,37 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
@end
@implementation GSBinaryExpression
- (id) copyWithZone: (NSZone*)zone
{
GSBinaryExpression *copy;
copy = (GSBinaryExpression *)[super copyWithZone: zone];
copy->_left = [_left copyWithZone: zone];
copy->_right = [_right copyWithZone: zone];
return copy;
}
- (void) dealloc
{
RELEASE(_left);
RELEASE(_right);
DEALLOC
}
- (NSExpression *) leftExpression
{
return _left;
}
- (NSExpression *) rightExpression
{
return _right;
}
@end
@implementation GSKeyPathCompositionExpression
- (NSString *) description
@ -1738,23 +1757,6 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
return nil;
}
- (void) dealloc
{
RELEASE(_left);
RELEASE(_right);
[super dealloc];
}
- (id) copyWithZone: (NSZone*)zone
{
GSKeyPathCompositionExpression *copy;
copy = (GSKeyPathCompositionExpression *)[super copyWithZone: zone];
copy->_left = [_left copyWithZone: zone];
copy->_right = [_right copyWithZone: zone];
return copy;
}
- (id) _expressionWithSubstitutionVariables: (NSDictionary*)variables
{
NSExpression *left;
@ -1766,16 +1768,6 @@ GSICUStringMatchesRegex(NSString *string, NSString *regex, NSStringCompareOption
right: right];
}
- (NSExpression *) leftExpression
{
return _left;
}
- (NSExpression *) rightExpression
{
return _right;
}
@end
// Macro for checking set related expressions
@ -1808,16 +1800,6 @@ do { \
return [NSString stringWithFormat: @"%@.%@", _left, _right];
}
- (NSExpression *) leftExpression
{
return _left;
}
- (NSExpression *) rightExpression
{
return _right;
}
- (id) expressionValueWithObject: (id)object
context: (NSMutableDictionary *)context
{
@ -1844,16 +1826,6 @@ do { \
return [NSString stringWithFormat: @"%@.%@", _left, _right];
}
- (NSExpression *) leftExpression
{
return _left;
}
- (NSExpression *) rightExpression
{
return _right;
}
- (id) expressionValueWithObject: (id)object
context: (NSMutableDictionary *)context
{
@ -1880,16 +1852,6 @@ do { \
return [NSString stringWithFormat: @"%@.%@", _left, _right];
}
- (NSExpression *) leftExpression
{
return _left;
}
- (NSExpression *) rightExpression
{
return _right;
}
- (id) expressionValueWithObject: (id)object
context: (NSMutableDictionary *)context
{
@ -1914,6 +1876,21 @@ do { \
@implementation GSAggregateExpression
- (id) copyWithZone: (NSZone*)zone
{
GSAggregateExpression *copy;
copy = (GSAggregateExpression *)[super copyWithZone: zone];
copy->_collection = [_collection copyWithZone: zone];
return copy;
}
- (void) dealloc
{
DESTROY(_collection);
DEALLOC
}
- (NSString *) description
{
return [NSString stringWithFormat: @"%@", _collection];
@ -2016,7 +1993,7 @@ do { \
{
RELEASE(_args);
RELEASE(_function);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone*)zone
@ -3173,8 +3150,8 @@ do { \
- (instancetype) predicateWithSubstitutionVariables:
(GS_GENERIC_CLASS(NSDictionary,NSString*,id)*)variables
{
return [[[GSBoundBlockPredicate alloc] initWithBlock: _block
bindings: variables] autorelease];
return AUTORELEASE([[GSBoundBlockPredicate alloc] initWithBlock: _block
bindings: variables]);
}
- (BOOL) evaluateWithObject: (id)object
@ -3194,7 +3171,7 @@ do { \
{
[(id)_block release];
_block = NULL;
[super dealloc];
DEALLOC
}
- (NSString*) predicateFormat
@ -3226,7 +3203,7 @@ do { \
- (void) dealloc
{
DESTROY(_bindings);
[super dealloc];
DEALLOC
}
@end

View file

@ -2734,8 +2734,9 @@ GSPropertyListMake(id obj, NSDictionary *loc, BOOL xml,
GSBinaryPLParser *p = [GSBinaryPLParser alloc];
p = [p initWithData: data mutability: anOption];
result = [p rootObject];
RELEASE(p);
/* to avoid a leak on exception, autorelease before parse
*/
result = [AUTORELEASE(p) rootObject];
}
break;

View file

@ -131,6 +131,7 @@ NSRegularExpressionOptionsToURegexpFlags(NSRegularExpressionOptions opts)
exp = [NSException exceptionWithName: NSInvalidArgumentException
reason: @"nil argument"
userInfo: nil];
RELEASE(self);
[exp raise];
}
@ -961,10 +962,9 @@ prepareResult(NSRegularExpression *regex,
return nil;
}
utext_clone(&ret->txt, output, TRUE, TRUE, &s);
uregex_close(r);
utext_close(&txt);
utext_close(output);
uregex_close(r);
utext_close(&txt);
utext_close(&replacement);
return AUTORELEASE(ret);
}

View file

@ -786,7 +786,7 @@ static inline BOOL timerInvalidated(NSTimer *t)
NSTimer *timer;
SEL sel;
#ifdef RL_INTEGRATE_DISPATCH
GSMainQueueDrainer *drain;
static GSMainQueueDrainer *drainer = nil;
#endif
ctr = [NSNotificationCenter defaultCenter];
@ -810,17 +810,20 @@ static inline BOOL timerInvalidated(NSTimer *t)
[current addTimer: timer forMode: NSDefaultRunLoopMode];
#ifdef RL_INTEGRATE_DISPATCH
/* We leak the queue drainer, because it's integral part of RL
* operations
*/
drain = [NSObject leak: [[GSMainQueueDrainer new] autorelease]];
if (nil == drainer)
{
/* We leak the queue drainer, because it's integral part of RL
* operations
*/
drainer = [GSMainQueueDrainer new];
}
[current addEvent: [GSMainQueueDrainer mainQueueFileDescriptor]
#ifdef _WIN32
type: ET_HANDLE
#else
type: ET_RDESC
#endif
watcher: drain
watcher: drainer
forMode: NSDefaultRunLoopMode];
#endif

View file

@ -169,6 +169,7 @@ static gs_mutex_t placeholderLock = GS_MUTEX_INIT_STATIC;
static SEL cMemberSel = 0;
static NSCharacterSet *nonBase = nil;
static BOOL (*nonBaseImp)(id, SEL, unichar) = 0;
static gs_mutex_t nonBaseLock = GS_MUTEX_INIT_STATIC;
static NSCharacterSet *wPathSeps = nil;
static NSCharacterSet *uPathSeps = nil;
@ -231,8 +232,24 @@ uni_isnonsp(unichar u)
* to a number of issues with UTF-16
*/
if ((u >= 0xdc00) && (u <= 0xdfff))
return YES;
{
return YES;
}
if (0 == nonBaseImp)
{
GS_MUTEX_LOCK(nonBaseLock);
if (nil == nonBase)
{
nonBase = RETAIN([NSCharacterSet nonBaseCharacterSet]);
nonBaseImp
= (BOOL(*)(id,SEL,unichar))[nonBase methodForSelector: cMemberSel];
}
GS_MUTEX_UNLOCK(nonBaseLock);
if (0 == nonBaseImp)
{
return NO; // if charset is missing (prerhaps during process exit)
}
}
return (*nonBaseImp)(nonBase, cMemberSel, u);
}
@ -878,7 +895,23 @@ register_printf_atsign ()
+ (void) atExit
{
DESTROY(placeholderMap);
/* Deallocate all the placeholders in the map before destroying it.
*/
GS_MUTEX_LOCK(placeholderLock);
if (placeholderMap)
{
NSMapEnumerator mEnum = NSEnumerateMapTable(placeholderMap);
Class c;
id o;
while (NSNextMapEnumeratorPair(&mEnum, (void *)&c, (void *)&o))
{
NSDeallocateObject(o);
}
NSEndMapTableEnumeration(&mEnum);
DESTROY(placeholderMap);
}
GS_MUTEX_UNLOCK(placeholderLock);
DESTROY(nonBase);
DESTROY(rPathSeps);
DESTROY(uPathSeps);
@ -901,10 +934,6 @@ register_printf_atsign ()
gcrSel = @selector(getCharacters:range:);
ranSel = @selector(rangeOfComposedCharacterSequenceAtIndex:);
nonBase = [NSCharacterSet nonBaseCharacterSet];
nonBaseImp
= (BOOL(*)(id,SEL,unichar))[nonBase methodForSelector: cMemberSel];
_DefaultStringEncoding = GSPrivateDefaultCStringEncoding();
_ByteEncodingOk = GSPrivateIsByteEncoding(_DefaultStringEncoding);
@ -956,7 +985,7 @@ register_printf_atsign ()
*/
GS_MUTEX_LOCK(placeholderLock);
obj = (id)NSMapGet(placeholderMap, (void*)z);
if (obj == nil)
if (obj == nil && NO == [NSObject isExiting])
{
/*
* There is no placeholder object for this zone, so we
@ -6563,6 +6592,7 @@ static NSFileManager *fm = nil;
&stop);
}
}
ubrk_close(breakIterator);
#else
NSWarnLog(@"NSStringEnumerationByWords and NSStringEnumerationBySentences"
@" are not supported when GNUstep-base is compiled without ICU.");

View file

@ -189,12 +189,12 @@ _NSToICUTZDisplayStyle(NSTimeZoneNameStyle style)
static inline UCalendar *
ICUCalendarSetup (NSTimeZone *tz, NSLocale *locale)
{
NSString *tzStr;
int32_t tzLen;
const char *cLocale;
UChar tzName[BUFFER_SIZE];
UCalendar *cal;
UErrorCode err = U_ZERO_ERROR;
NSString *tzStr;
int32_t tzLen;
const char *cLocale;
UChar tzName[BUFFER_SIZE];
UCalendar *cal;
UErrorCode err = U_ZERO_ERROR;
tzStr = [tz name];
if ((tzLen = [tzStr length]) > BUFFER_SIZE)
@ -225,6 +225,7 @@ static NSString *tzdir = nil;
static GSPlaceholderTimeZone *defaultPlaceholderTimeZone;
static NSMapTable *placeholderMap;
static GSAbsTimeZone *commonAbsolutes[145] = { 0 };
static NSMapTable *absolutes = 0;
/*
* Temporary structure for holding time zone details.
@ -287,6 +288,9 @@ static NSMutableDictionary *abbreviationDictionary = nil;
/* one-to-many abbreviation to time zone name dictionary. */
static NSMutableDictionary *abbreviationMap = nil;
static NSArray *namesArray = nil;
static NSArray *regionsArray = nil;
/* Lock for creating time zones. */
static gs_mutex_t zone_mutex;
@ -313,7 +317,6 @@ static NSString *_time_zone_path(NSString *subpath, NSString *type)
{
@public
NSString *name;
id detail;
int offset; // Offset from UTC in seconds.
}
@ -635,17 +638,6 @@ static NSString *_time_zone_path(NSString *subpath, NSString *type)
@implementation GSAbsTimeZone
static int uninitialisedOffset = 100000;
static NSMapTable *absolutes = 0;
+ (void) initialize
{
if (self == [GSAbsTimeZone class])
{
absolutes = NSCreateMapTable(NSIntegerMapKeyCallBacks,
NSNonOwnedPointerMapValueCallBacks, 0);
[[NSObject leakAt: (id*)&absolutes] release];
}
}
- (NSString*) abbreviationForDate: (NSDate*)aDate
{
@ -661,7 +653,6 @@ static NSMapTable *absolutes = 0;
GS_MUTEX_UNLOCK(zone_mutex);
}
RELEASE(name);
RELEASE(detail);
DEALLOC;
}
@ -703,66 +694,60 @@ static NSMapTable *absolutes = 0;
}
anOffset *= sign;
GS_MUTEX_LOCK(zone_mutex);
if (anOffset % 900 == 0)
{
z = commonAbsolutes[anOffset/900 + 72];
if (z != nil)
{
IF_NO_ARC(RETAIN(z);)
DESTROY(self);
return z;
}
}
GS_MUTEX_LOCK(zone_mutex);
z = (GSAbsTimeZone*)NSMapGet(absolutes, (void*)(uintptr_t)anOffset);
if (z != nil)
{
IF_NO_ARC(RETAIN(z);)
DESTROY(self);
}
else
{
if (aName == nil)
z = (GSAbsTimeZone*)NSMapGet(absolutes, (void*)(uintptr_t)anOffset);
}
if (z)
{
IF_NO_ARC(RETAIN(z);)
DESTROY(self);
return z;
}
if (aName == nil)
{
if (anOffset % 60 == 0)
{
if (anOffset % 60 == 0)
{
char s = (anOffset >= 0) ? '+' : '-';
unsigned i = (anOffset >= 0) ? anOffset / 60 : -anOffset / 60;
unsigned h = (i / 60) % 24;
unsigned m = i % 60;
char buf[9];
char s = (anOffset >= 0) ? '+' : '-';
unsigned i = (anOffset >= 0) ? anOffset / 60 : -anOffset / 60;
unsigned h = (i / 60) % 24;
unsigned m = i % 60;
char buf[9];
snprintf(buf, sizeof(buf), "GMT%c%02u%02u", s, h, m);
name = [[NSString alloc] initWithUTF8String: buf];
}
else
{
/*
* Should never happen now we round to the minute
* for MacOS-X compatibnility.
*/
name = [[NSString alloc]
initWithFormat: @"NSAbsoluteTimeZone:%"PRIdPTR, anOffset];
}
snprintf(buf, sizeof(buf), "GMT%c%02u%02u", s, h, m);
name = [[NSString alloc] initWithUTF8String: buf];
}
else
{
name = [aName copy];
/*
* Should never happen now we round to the minute
* for MacOS-X compatibnility.
*/
name = [[NSString alloc]
initWithFormat: @"NSAbsoluteTimeZone:%"PRIdPTR, anOffset];
}
detail = [[GSAbsTimeZoneDetail alloc] initWithTimeZone: self];
offset = anOffset;
z = self;
NSMapInsert(absolutes, (void*)(uintptr_t)anOffset, (void*)z);
[zoneDictionary setObject: self forKey: (NSString*)name];
}
else
{
name = [aName copy];
}
z = self;
offset = anOffset;
NSMapInsert(absolutes, (void*)(uintptr_t)anOffset, (void*)z);
[zoneDictionary setObject: z forKey: name];
if (anOffset % 900 == 0)
{
int index = anOffset/900 + 72;
if (nil == commonAbsolutes[index])
{
commonAbsolutes[index] = RETAIN(self);
commonAbsolutes[index] = RETAIN(z);
}
}
GS_MUTEX_UNLOCK(zone_mutex);
@ -786,12 +771,12 @@ static NSMapTable *absolutes = 0;
- (NSArray*) timeZoneDetailArray
{
return [NSArray arrayWithObject: detail];
return [NSArray arrayWithObject: [self timeZoneDetailForDate: nil]];
}
- (NSTimeZoneDetail*) timeZoneDetailForDate: (NSDate*)date
{
return detail;
return AUTORELEASE([[GSAbsTimeZoneDetail alloc] initWithTimeZone: self]);
}
- (NSString*) timeZoneName
@ -992,7 +977,7 @@ static NSMapTable *absolutes = 0;
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSString *path;
path = _time_zone_path (ABBREV_DICT, @"plist");
path = _time_zone_path(ABBREV_DICT, @"plist");
if (path != nil)
{
/*
@ -1196,8 +1181,6 @@ static NSMapTable *absolutes = 0;
*/
+ (NSArray*) knownTimeZoneNames
{
static NSArray *namesArray = nil;
/* We create the array only when we need it to reduce overhead. */
if (namesArray != nil)
{
@ -1205,7 +1188,7 @@ static NSMapTable *absolutes = 0;
}
GS_MUTEX_LOCK(zone_mutex);
if (namesArray == nil)
if (namesArray == nil && NO == [NSObject isExiting])
{
unsigned i;
NSMutableArray *ma;
@ -1281,6 +1264,43 @@ static NSMapTable *absolutes = 0;
}
}
+ (void) atExit
{
id o;
/* Deallocate all the placeholders in the map before destroying it.
*/
GS_MUTEX_LOCK(zone_mutex);
if (placeholderMap)
{
NSMapEnumerator mEnum = NSEnumerateMapTable(placeholderMap);
Class c;
id o;
while (NSNextMapEnumeratorPair(&mEnum, (void *)&c, (void *)&o))
{
NSDeallocateObject(o);
}
NSEndMapTableEnumeration(&mEnum);
DESTROY(placeholderMap);
}
GS_MUTEX_UNLOCK(zone_mutex);
DESTROY(zoneDictionary);
DESTROY(localTimeZone);
DESTROY(defaultTimeZone);
DESTROY(systemTimeZone);
DESTROY(abbreviationDictionary);
DESTROY(abbreviationMap);
DESTROY(absolutes);
DESTROY(namesArray);
DESTROY(regionsArray);
o = defaultPlaceholderTimeZone;
defaultPlaceholderTimeZone = nil;
NSDeallocateObject(o);
}
/**
* Return the default time zone for this process.
*/
@ -1303,37 +1323,36 @@ static NSMapTable *absolutes = 0;
+ (void) initialize
{
if (self == [NSTimeZone class])
static BOOL beenHere = NO;
if (NO == beenHere && self == [NSTimeZone class])
{
beenHere = YES;
NSTimeZoneClass = self;
GS_MUTEX_INIT_RECURSIVE(zone_mutex);
GSPlaceholderTimeZoneClass = [GSPlaceholderTimeZone class];
zoneDictionary = [[NSMutableDictionary alloc] init];
[[NSObject leakAt: &zoneDictionary] release];
/*
* Set up infrastructure for placeholder timezones.
/* Set up infrastructure for placeholder timezones.
*/
defaultPlaceholderTimeZone = (GSPlaceholderTimeZone*)
NSAllocateObject(GSPlaceholderTimeZoneClass, 0, NSDefaultMallocZone());
[[NSObject leakAt: &defaultPlaceholderTimeZone] release];
placeholderMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
NSNonRetainedObjectMapValueCallBacks, 0);
[[NSObject leakAt: (id*)&placeholderMap] release];
/* Hash table lookup for absolute time zones.
*/
absolutes = NSCreateMapTable(NSIntegerMapKeyCallBacks,
NSNonOwnedPointerMapValueCallBacks, 0);
localTimeZone = [[NSLocalTimeZone alloc] init];
[[NSObject leakAt: (id*)&localTimeZone] release];
[[NSObject leakAt: (id*)&defaultTimeZone] release];
[[NSObject leakAt: (id*)&systemTimeZone] release];
[[NSObject leakAt: (id*)&abbreviationDictionary] release];
[[NSObject leakAt: (id*)&abbreviationMap] release];
[[NSObject leakAt: (id*)&absolutes] release];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(_notified:)
name: NSUserDefaultsDidChangeNotification
object: nil];
[self registerAtExit];
}
}
@ -1644,7 +1663,8 @@ static NSMapTable *absolutes = 0;
if (localZoneString != nil)
{
NSDebugLLog (@"NSTimeZone", @"Using zone %@", localZoneString);
zone = [defaultPlaceholderTimeZone initWithName: localZoneString];
zone = AUTORELEASE([defaultPlaceholderTimeZone
initWithName: localZoneString]);
if (zone == nil)
{
NSArray *possibleZoneNames;
@ -1680,7 +1700,7 @@ static NSMapTable *absolutes = 0;
&& [dflt contentsEqualAtPath: fileName
andPath: SYSTEM_TIME_FILE])
{
zone = [[self timeZoneWithName: zoneName] retain];
zone = [self timeZoneWithName: zoneName];
if (zone != nil)
{
@ -1728,7 +1748,7 @@ zoneName, LOCALDBKEY, LOCALDBKEY, zoneName);
@"See '%@'\n"
@"for the standard timezones such as 'GB-Eire' or 'America/Chicago'.\n",
LOCALDBKEY, LOCALDBKEY, _time_zone_path (ZONES_DIR, nil));
zone = [[self timeZoneWithAbbreviation: localZoneString] retain];
zone = [self timeZoneWithAbbreviation: localZoneString];
if (zone != nil)
{
NSInteger s;
@ -1762,7 +1782,7 @@ localZoneString, [zone name], sign, s/3600, (s/60)%60);
if (zone == nil)
{
NSLog(@"Using time zone with absolute offset 0.");
zone = systemTimeZone;
zone = [self timeZoneForSecondsFromGMT: 0];
}
ASSIGN(systemTimeZone, zone);
}
@ -1777,17 +1797,15 @@ localZoneString, [zone name], sign, s/3600, (s/60)%60);
* Each element contains an array of NSStrings which are
* the region names.
*/
+ (NSArray *)timeZoneArray
+ (NSArray*) timeZoneArray
{
static NSArray *regionsArray = nil;
/* We create the array only when we need it to reduce overhead. */
if (regionsArray != nil)
{
return regionsArray;
}
GS_MUTEX_LOCK(zone_mutex);
if (regionsArray == nil)
if (regionsArray == nil && NO == [NSObject isExiting])
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSMutableArray *temp_array[24];
@ -1829,9 +1847,9 @@ localZoneString, [zone name], sign, s/3600, (s/60)%60);
newLineSet = [NSCharacterSet newlineCharacterSet];
scanner = [NSScanner scannerWithString: contents];
while ([scanner scanInteger: &index] &&
[scanner scanUpToCharactersFromSet: newLineSet
intoString: &name])
while ([scanner scanInteger: &index]
&& [scanner scanUpToCharactersFromSet: newLineSet
intoString: &name])
{
if (index < 0)
index = 0;
@ -1842,7 +1860,7 @@ localZoneString, [zone name], sign, s/3600, (s/60)%60);
}
}
else
{
{
NSString *zonedir = [NSTimeZone _getTimeZoneFile: @"WET"];
if (tzdir != nil)
@ -2358,21 +2376,21 @@ localZoneString, [zone name], sign, s/3600, (s/60)%60);
UCalendar *cal;
UErrorCode err = U_ZERO_ERROR;
cal = ICUCalendarSetup (self, locale);
cal = ICUCalendarSetup(self, locale);
if (cal == NULL)
return nil;
cLocale = [[locale localeIdentifier] UTF8String];
result = NSZoneMalloc ([self zone], BUFFER_SIZE * sizeof(UChar));
len = ucal_getTimeZoneDisplayName (cal, _NSToICUTZDisplayStyle(style),
result = NSZoneMalloc([self zone], BUFFER_SIZE * sizeof(UChar));
len = ucal_getTimeZoneDisplayName(cal, _NSToICUTZDisplayStyle(style),
cLocale, result, BUFFER_SIZE, &err);
if (len > BUFFER_SIZE)
{
result = NSZoneRealloc ([self zone], result, len * sizeof(UChar));
ucal_getTimeZoneDisplayName (cal, _NSToICUTZDisplayStyle(style),
result = NSZoneRealloc([self zone], result, len * sizeof(UChar));
ucal_getTimeZoneDisplayName(cal, _NSToICUTZDisplayStyle(style),
cLocale, result, len, &err);
}
ucal_close(cal);
return AUTORELEASE([[NSString alloc] initWithCharactersNoCopy: result
length: len freeWhenDone: YES]);
#else

View file

@ -658,14 +658,17 @@ static NSUInteger urlAlign;
isDirectory: (BOOL)isDir
relativeToURL: (NSURL *)baseURL
{
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL flag = NO;
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL flag = NO;
if (nil == aPath)
{
NSString *name = NSStringFromClass([self class]);
RELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"[%@ %@] nil string parameter",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
name, NSStringFromSelector(_cmd)];
}
if ([aPath isAbsolutePath] == NO)
{
@ -803,16 +806,22 @@ static NSUInteger urlAlign;
}
if ([aUrlString isKindOfClass: [NSString class]] == NO)
{
NSString *name = NSStringFromClass([self class]);
RELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"[%@ %@] bad string parameter",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
name, NSStringFromSelector(_cmd)];
}
if (aBaseUrl != nil
&& [aBaseUrl isKindOfClass: [NSURL class]] == NO)
{
NSString *name = NSStringFromClass([self class]);
RELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"[%@ %@] bad base URL parameter",
NSStringFromClass([self class]), NSStringFromSelector(_cmd)];
name, NSStringFromSelector(_cmd)];
}
ASSIGNCOPY(_urlString, aUrlString);
ASSIGN(_baseURL, [aBaseUrl absoluteURL]);
@ -1270,7 +1279,7 @@ static NSUInteger urlAlign;
}
DESTROY(_urlString);
DESTROY(_baseURL);
[super dealloc];
DEALLOC
}
- (id) copyWithZone: (NSZone*)zone
@ -2207,10 +2216,13 @@ GS_PRIVATE_INTERNAL(NSURLQueryItem)
- (void) dealloc
{
RELEASE(internal->_name);
RELEASE(internal->_value);
GS_DESTROY_INTERNAL(NSURLQueryItem);
[super dealloc];
if (GS_EXISTS_INTERNAL)
{
RELEASE(internal->_name);
RELEASE(internal->_value);
GS_DESTROY_INTERNAL(NSURLQueryItem);
}
DEALLOC
}
// Reading a name and value from a query
@ -2301,14 +2313,14 @@ static NSCharacterSet *queryItemCharSet = nil;
// Creating URL components...
+ (instancetype) componentsWithString: (NSString *)urlString
{
return AUTORELEASE([[NSURLComponents alloc] initWithString: urlString]);
return AUTORELEASE([[NSURLComponents alloc] initWithString: urlString]);
}
+ (instancetype) componentsWithURL: (NSURL *)url
resolvingAgainstBaseURL: (BOOL)resolve
{
return AUTORELEASE([[NSURLComponents alloc] initWithURL: url
resolvingAgainstBaseURL: resolve]);
return AUTORELEASE([[NSURLComponents alloc] initWithURL: url
resolvingAgainstBaseURL: resolve]);
}
- (instancetype) init
@ -2342,6 +2354,7 @@ static NSCharacterSet *queryItemCharSet = nil;
}
else
{
RELEASE(self);
return nil;
}
}
@ -2365,17 +2378,20 @@ static NSCharacterSet *queryItemCharSet = nil;
- (void) dealloc
{
RELEASE(internal->_string);
RELEASE(internal->_fragment);
RELEASE(internal->_host);
RELEASE(internal->_password);
RELEASE(internal->_path);
RELEASE(internal->_port);
RELEASE(internal->_queryItems);
RELEASE(internal->_scheme);
RELEASE(internal->_user);
GS_DESTROY_INTERNAL(NSURLComponents);
[super dealloc];
if (GS_EXISTS_INTERNAL)
{
RELEASE(internal->_string);
RELEASE(internal->_fragment);
RELEASE(internal->_host);
RELEASE(internal->_password);
RELEASE(internal->_path);
RELEASE(internal->_port);
RELEASE(internal->_queryItems);
RELEASE(internal->_scheme);
RELEASE(internal->_user);
GS_DESTROY_INTERNAL(NSURLComponents);
}
DEALLOC
}
- (id) copyWithZone: (NSZone *)zone

View file

@ -431,6 +431,7 @@ typedef struct
this->_delegate = nil;
[o connection: self didFailWithError: error];
DESTROY(o);
DESTROY(this->_protocol);
}
- (void) URLProtocol: (NSURLProtocol *)protocol
@ -510,6 +511,7 @@ typedef struct
this->_delegate = nil;
[o connectionDidFinishLoading: self];
DESTROY(o);
DESTROY(this->_protocol);
}
- (void) URLProtocol: (NSURLProtocol *)protocol

View file

@ -180,6 +180,13 @@ debugWrite(id handle, int len, const unsigned char *ptr)
static NSMutableArray *pairCache = nil;
static NSLock *pairLock = nil;
+ (void) atExit
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
DESTROY(pairLock);
DESTROY(pairCache);
}
+ (void) initialize
{
if (pairCache == nil)
@ -196,6 +203,7 @@ static NSLock *pairLock = nil;
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(purge:)
name: @"GSHousekeeping" object: nil];
[self registerAtExit];
}
}
@ -468,19 +476,36 @@ typedef struct {
return o;
}
+ (void) atExit
{
if (placeholder)
{
id o = placeholder;
placeholder = nil;
NSDeallocateObject(o);
}
fprintf(stderr, "Registered retain count %d\n", (int)[registered retainCount]);
DESTROY(registered);
DESTROY(regLock);
}
+ (void) initialize
{
if (registered == nil)
static BOOL beenHere = NO;
if (NO == beenHere)
{
beenHere = YES;
abstractClass = [NSURLProtocol class];
placeholderClass = [NSURLProtocolPlaceholder class];
[self registerAtExit];
placeholder = (NSURLProtocol*)NSAllocateObject(placeholderClass, 0,
NSDefaultMallocZone());
[[NSObject leakAt: &placeholder] release];
registered = [NSMutableArray new];
[[NSObject leakAt: &registered] release];
regLock = [NSLock new];
[[NSObject leakAt: &regLock] release];
[self registerClass: [_NSHTTPURLProtocol class]];
[self registerClass: [_NSHTTPSURLProtocol class]];
[self registerClass: [_NSFTPURLProtocol class]];
@ -547,9 +572,9 @@ typedef struct {
[this->output close];
DESTROY(this->input);
DESTROY(this->output);
DESTROY(this->in);
DESTROY(this->out);
}
DESTROY(this->in);
DESTROY(this->out);
DESTROY(this->cachedResponse);
DESTROY(this->request);
#if GS_HAVE_NSURLSESSION
@ -1744,18 +1769,18 @@ typedef struct {
{
NSLog(@"%@ HTTP output stream opened", self);
}
this->in = [[NSString alloc]
initWithFormat: @"(%@:%@ <-- %@:%@)",
s = [NSString stringWithFormat: @"(%@:%@ <-- %@:%@)",
[stream propertyForKey: GSStreamLocalAddressKey],
[stream propertyForKey: GSStreamLocalPortKey],
[stream propertyForKey: GSStreamRemoteAddressKey],
[stream propertyForKey: GSStreamRemotePortKey]];
this->out = [[NSString alloc]
initWithFormat: @"(%@:%@ --> %@:%@)",
ASSIGN(this->in, s);
s = [NSString stringWithFormat: @"(%@:%@ --> %@:%@)",
[stream propertyForKey: GSStreamLocalAddressKey],
[stream propertyForKey: GSStreamLocalPortKey],
[stream propertyForKey: GSStreamRemoteAddressKey],
[stream propertyForKey: GSStreamRemotePortKey]];
ASSIGN(this->out, s);
DESTROY(_writeData);
DESTROY(_masked);
_writeOffset = 0;

View file

@ -488,6 +488,7 @@ static unsigned encodingVersion;
{
if (anObject == nil)
{
RELEASE(self);
[NSException raise: NSInvalidArgumentException
format: @"nil data passed to initForReadingWithData:"];
}

View file

@ -685,13 +685,16 @@ newLanguages(NSArray *oldNames)
+ (void) initialize
{
if (self == [NSUserDefaults class])
static BOOL beenHere = NO;
if (NO == beenHere && self == [NSUserDefaults class])
{
ENTER_POOL
NSEnumerator *enumerator;
NSArray *args;
NSString *key;
beenHere = YES;
nextObjectSel = @selector(nextObject);
objectForKeySel = @selector(objectForKey:);
addSel = @selector(addEntriesFromDictionary:);
@ -1347,6 +1350,7 @@ newLanguages(NSArray *oldNames)
RELEASE(_tempDomains);
RELEASE(_changedDomains);
RELEASE(_dictionaryRep);
RELEASE(_defaultsDatabase);
RELEASE(_fileLock);
RELEASE(_lock);
[super dealloc];

View file

@ -35,6 +35,7 @@
#import "Foundation/NSMapTable.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSData.h"
#import "GSPThread.h"
@interface GSPlaceholderValue : NSValue
@end
@ -78,10 +79,41 @@ static Class GSPlaceholderValueClass;
static GSPlaceholderValue *defaultPlaceholderValue;
static NSMapTable *placeholderMap;
static NSLock *placeholderLock;
static gs_mutex_t placeholderLock = GS_MUTEX_INIT_STATIC;
@implementation NSValue
+ (void) atExit
{
id o;
/* The default placeholder array overrides -dealloc so we must get rid of
* it directly.
*/
o = defaultPlaceholderValue;
defaultPlaceholderValue = nil;
NSDeallocateObject(o);
/* Deallocate all the placeholders in the map before destroying it.
*/
GS_MUTEX_LOCK(placeholderLock);
if (placeholderMap)
{
NSMapEnumerator mEnum = NSEnumerateMapTable(placeholderMap);
Class c;
id o;
while (NSNextMapEnumeratorPair(&mEnum, (void *)&c, (void *)&o))
{
NSDeallocateObject(o);
}
NSEndMapTableEnumeration(&mEnum);
DESTROY(placeholderMap);
}
GS_MUTEX_UNLOCK(placeholderLock);
}
+ (void) initialize
{
if (self == [NSValue class])
@ -102,12 +134,9 @@ static NSLock *placeholderLock;
*/
defaultPlaceholderValue = (GSPlaceholderValue*)
NSAllocateObject(GSPlaceholderValueClass, 0, NSDefaultMallocZone());
[[NSObject leakAt: (id*)&defaultPlaceholderValue] release];
placeholderMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
NSNonRetainedObjectMapValueCallBacks, 0);
[[NSObject leakAt: (id*)&placeholderMap] release];
placeholderLock = [NSLock new];
[[NSObject leakAt: (id*)&placeholderLock] release];
[self registerAtExit];
}
}
@ -132,9 +161,9 @@ static NSLock *placeholderLock;
* locate the correct placeholder in the (lock protected)
* table of placeholders.
*/
[placeholderLock lock];
GS_MUTEX_LOCK(placeholderLock);
obj = (id)NSMapGet(placeholderMap, (void*)z);
if (obj == nil)
if (obj == nil && NO == [NSObject isExiting])
{
/*
* There is no placeholder object for this zone, so we
@ -143,7 +172,7 @@ static NSLock *placeholderLock;
obj = (id)NSAllocateObject(GSPlaceholderValueClass, 0, z);
NSMapInsert(placeholderMap, (void*)z, (void*)obj);
}
[placeholderLock unlock];
GS_MUTEX_UNLOCK(placeholderLock);
return obj;
}
}
@ -720,11 +749,13 @@ static NSLock *placeholderLock;
- (oneway void) release
{
NSWarnLog(@"-release sent to uninitialised value");
return; // placeholders never get released.
}
- (id) retain
{
NSWarnLog(@"-retain sent to uninitialised value");
return self; // placeholders never get retained.
}
@end

View file

@ -52,16 +52,14 @@ typedef struct _cifframe_t {
@class NSMutableData;
extern NSMutableData *cifframe_from_signature (NSMethodSignature *info);
extern GSCodeBuffer* cifframe_closure (NSMethodSignature *sig, void (*func)());
extern GSCodeBuffer* cifframe_closure(NSMethodSignature *sig, void (*func)());
extern void cifframe_set_arg(cifframe_t *cframe, int index, void *buffer,
int size);
extern void cifframe_get_arg(cifframe_t *cframe, int index, void *buffer,
int size);
extern void *cifframe_arg_addr(cifframe_t *cframe, int index);
extern BOOL cifframe_decode_arg (const char *type, void* buffer);
extern BOOL cifframe_encode_arg (const char *type, void* buffer);
extern BOOL cifframe_decode_arg(const char *type, void* buffer);
extern BOOL cifframe_encode_arg(const char *type, void* buffer);
#endif

View file

@ -39,6 +39,7 @@
#endif
#include "cifframe.h"
#import "Foundation/NSPointerArray.h"
#import "Foundation/NSException.h"
#import "Foundation/NSData.h"
#import "GSInvocation.h"
@ -91,7 +92,8 @@
#endif
#endif
ffi_type *cifframe_type(const char *typePtr, const char **advance);
static ffi_type *
cifframe_type(const char *typePtr, const char **adv, NSPointerArray **extra);
/* Best guess at the space needed for a structure, since we don't know
for sure until it's calculated in ffi_prep_cif, which is too late */
@ -122,30 +124,30 @@ cifframe_guess_struct_size(ffi_type *stype)
return size;
}
NSMutableData *
cifframe_from_signature (NSMethodSignature *info)
static void
cifframe_from_signature(NSMethodSignature *info,
NSMutableData **frame, NSPointerArray **extra)
{
unsigned size = sizeof(cifframe_t);
unsigned align = __alignof(double);
unsigned type_offset = 0;
unsigned offset = 0;
NSMutableData *result;
void *buf;
int i;
int numargs = [info numberOfArguments];
ffi_type *rtype;
ffi_type *arg_types[numargs];
cifframe_t *cframe;
unsigned size = sizeof(cifframe_t);
unsigned align = __alignof(double);
unsigned type_offset = 0;
unsigned offset = 0;
NSMutableData *result;
void *buf;
int i;
int numargs = [info numberOfArguments];
ffi_type *rtype;
ffi_type *arg_types[numargs];
cifframe_t *cframe;
/* FIXME: in cifframe_type, return values/arguments that are structures
have custom ffi_types with are allocated separately. We should allocate
them in our cifframe so we don't leak memory. Or maybe we could
cache structure types? */
rtype = cifframe_type([info methodReturnType], NULL);
/* The extra parameter returns an array of any allocated memory which
* needs freeing at the end of the invocation.
*/
rtype = cifframe_type([info methodReturnType], NULL, extra);
for (i = 0; i < numargs; i++)
{
arg_types[i] = cifframe_type([info getArgumentTypeAtIndex: i], NULL);
arg_types[i]
= cifframe_type([info getArgumentTypeAtIndex: i], NULL, extra);
}
if (numargs > 0)
@ -220,9 +222,21 @@ cifframe_from_signature (NSMethodSignature *info)
}
}
}
return result;
*frame = result;
}
@implementation GSFFIInvocation (FFI)
- (void) setupFrameFFI: (NSMethodSignature*)info
{
NSMutableData *f = nil;
NSPointerArray *e = nil;
cifframe_from_signature(info, &f, &e);
ASSIGN(_frame, f);
ASSIGN(_extra, e);
}
@end
void
cifframe_set_arg(cifframe_t *cframe, int index, void *buffer, int size)
{
@ -250,8 +264,8 @@ cifframe_arg_addr(cifframe_t *cframe, int index)
/*
* Get the ffi_type for this type
*/
ffi_type *
cifframe_type(const char *typePtr, const char **advance)
static ffi_type *
cifframe_type(const char *typePtr, const char **advance, NSPointerArray **extra)
{
static ffi_type stypeNSPoint = { 0 };
static ffi_type stypeNSRange = { 0 };
@ -309,7 +323,7 @@ cifframe_type(const char *typePtr, const char **advance)
else
{
const char *adv;
cifframe_type(typePtr, &adv);
cifframe_type(typePtr, &adv, extra);
typePtr = adv;
}
break;
@ -328,7 +342,7 @@ cifframe_type(const char *typePtr, const char **advance)
{
typePtr++;
}
cifframe_type(typePtr, &adv);
cifframe_type(typePtr, &adv, extra);
typePtr = adv;
typePtr++; /* Skip end-of-array */
}
@ -433,8 +447,8 @@ cifframe_type(const char *typePtr, const char **advance)
/* An NSRect is an NSPoint and an NSSize, but those
* two structures are actually identical.
*/
elems[0] = cifframe_type(@encode(NSSize), NULL);
elems[1] = cifframe_type(@encode(NSPoint), NULL);
elems[0] = cifframe_type(@encode(NSSize), NULL, extra);
elems[1] = cifframe_type(@encode(NSPoint), NULL, extra);
elems[2] = 0;
ftype->elements = elems;
ftype->type = FFI_TYPE_STRUCT;
@ -471,7 +485,7 @@ cifframe_type(const char *typePtr, const char **advance)
*/
while (*typePtr != _C_STRUCT_E)
{
local = cifframe_type(typePtr, &adv);
local = cifframe_type(typePtr, &adv, extra);
typePtr = adv;
NSCAssert(typePtr, @"End of signature while parsing");
ftype->elements[types++] = local;
@ -485,6 +499,13 @@ cifframe_type(const char *typePtr, const char **advance)
}
ftype->elements[types] = NULL;
typePtr++; /* Skip end-of-struct */
if (nil == *extra)
{
*extra = [NSPointerArray pointerArrayWithOptions:
NSPointerFunctionsOpaquePersonality
| NSPointerFunctionsMallocMemory];
}
[*extra addPointer: ftype];
}
break;
@ -508,19 +529,11 @@ cifframe_type(const char *typePtr, const char **advance)
{
ffi_type *local;
int align = objc_alignof_type(typePtr);
local = cifframe_type(typePtr, &adv);
local = cifframe_type(typePtr, &adv, extra);
typePtr = adv;
NSCAssert(typePtr, @"End of signature while parsing");
if (align > max_align)
{
if (ftype && ftype->type == FFI_TYPE_STRUCT
&& ftype != &stypeNSPoint
&& ftype != &stypeNSRange
&& ftype != &stypeNSRect
&& ftype != &stypeNSSize)
{
free(ftype);
}
ftype = local;
max_align = align;
}
@ -557,21 +570,22 @@ cifframe_type(const char *typePtr, const char **advance)
}
GSCodeBuffer*
cifframe_closure (NSMethodSignature *sig, void (*cb)())
cifframe_closure(NSMethodSignature *sig, void (*cb)())
{
NSMutableData *frame;
NSMutableData *frame = nil;
NSPointerArray *extra = nil;
cifframe_t *cframe;
ffi_closure *cclosure;
void *executable;
GSCodeBuffer *memory;
/* Construct the frame (stored in an NSMutableDate object) and sety it
/* Construct the frame (stored in an NSMutableDate object) and set it
* in a new closure.
*/
frame = cifframe_from_signature(sig);
cifframe_from_signature(sig, &frame, &extra);
cframe = [frame mutableBytes];
memory = [GSCodeBuffer memoryWithSize: sizeof(ffi_closure)];
[memory setFrame: frame];
[memory setFrame: frame extra: extra];
cclosure = [memory buffer];
executable = [memory executable];
if (cframe == NULL || cclosure == NULL)

View file

@ -76,8 +76,8 @@ int main()
"NSZoneFromPointer() returns zone where memory came from");
NS_DURING
[NSString allocWithZone:aZone];
NSRecycleZone(aZone);
NSZoneMalloc(aZone, 42);
NSRecycleZone(aZone);
PASS(1,"NSRecycleZone seems to operate");
NS_HANDLER
PASS(0,"NSRecycleZone seems to operate");

View file

@ -94,6 +94,8 @@ main(int argc, char *argv[])
const char *t0;
const char *t1;
const char *n;
unsigned u;
int i;
t0 = "1@1:@";
t1 = NSGetSizeAndAlignment(t0, &s, &a);
@ -118,7 +120,7 @@ main(int argc, char *argv[])
PASS(0 == class_getVersion(Nil),
"class_getVersion() for Nil is 0");
obj = [NSObject new];
obj = AUTORELEASE([NSObject new]);
cls = [SubClass1 class];
PASS(c1initialize != 0, "+initialize was called");
@ -151,6 +153,55 @@ main(int argc, char *argv[])
ivar = class_getInstanceVariable(cls, "ivar1obj");
PASS(ivar != 0, "class_getInstanceVariable() works for superclass obj ivar");
i = objc_getClassList(NULL, 0);
PASS(i > 2, "class list contains a reasonable number of classes");
if (i > 2)
{
int classCount = i;
Class buf[classCount];
BOOL foundClass = NO;
BOOL foundSubClass = NO;
i = objc_getClassList(buf, classCount);
PASS(i == classCount, "retrieved all classes")
for (i = 0; i < classCount; i++)
{
n = class_getName(buf[i]);
if (n)
{
if (strcmp(n, "Class1") == 0)
{
foundClass = YES;
}
else if (strcmp(n, "SubClass1") == 0)
{
foundSubClass = YES;
}
}
}
PASS(foundClass && foundSubClass, "found classes in list")
}
u = 0;
protocols = objc_copyProtocolList(&u);
PASS(protocols && u, "we copied some protocols")
if (protocols)
{
BOOL found = NO;
for (i = 0; i < u; i++)
{
n = protocol_getName(protocols[i]);
if (strcmp(n, "SubProto") == 0)
{
found = YES;
}
}
free(protocols);
PASS(found, "we found our protocol in list")
}
methods = class_copyMethodList(cls, &count);
PASS(count == 3, "SubClass1 has three methods");
PASS(methods[count] == 0, "method list is terminated");
@ -188,6 +239,7 @@ main(int argc, char *argv[])
PASS(sel_isEqual(sel, sel_getUid("catMethod")),
"method 1 has expected name");
}
free(methods);
ivars = class_copyIvarList(cls, &count);
PASS(count == 1, "SubClass1 has one ivar");
@ -196,12 +248,14 @@ main(int argc, char *argv[])
"ivar has correct name");
PASS(strcmp(ivar_getTypeEncoding(ivars[0]), @encode(int)) == 0,
"ivar has correct type");
free(ivars);
protocols = class_copyProtocolList(cls, &count);
PASS(count == 1, "SubClass1 has one protocol");
PASS(protocols[count] == 0, "protocol list is terminated");
PASS(strcmp(protocol_getName(protocols[0]), "SubProto") == 0,
"protocol has correct name");
free(protocols);
cls = objc_allocateClassPair([NSString class], "runtime generated", 0);
PASS(cls != Nil, "can allocate a class pair");
@ -213,7 +267,7 @@ main(int argc, char *argv[])
"able to add iVar 'iv3'");
PASS(class_addIvar(cls, "iv4", 1, 3, "c") == YES,
"able to add iVar 'iv4'");
objc_registerClassPair (cls);
objc_registerClassPair(cls);
ivar = class_getInstanceVariable(cls, "iv1");
PASS(ivar != 0, "iv1 exists");
PASS(ivar_getOffset(ivar) == 64, "iv1 offset is 64");

View file

@ -25,29 +25,27 @@ int main(int argc,char **argv)
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSData *data = nil;
NSString *string = nil;
GSMimeDocument *doc = [[GSMimeDocument alloc] init];
GSMimeDocument *doc = AUTORELEASE([[GSMimeDocument alloc] init]);
GSMimeDocument *mul;
NSMutableDictionary *par = [[NSMutableDictionary alloc] init];
NSMutableDictionary *par = AUTORELEASE([[NSMutableDictionary alloc] init]);
[par setObject: @"my/type" forKey: @"type"];
[doc setContent: @"Hello\r\n"];
[doc setHeader: [[GSMimeHeader alloc] initWithName: @"content-type"
value: @"text/plain"
parameters: par]];
[doc setHeader: [GSMimeHeader headerWithName: @"content-type"
value: @"text/plain"
parameters: par]];
[doc setHeader:
[[GSMimeHeader alloc] initWithName: @"content-transfer-encoding"
value: @"binary"
parameters: nil]];
[doc setHeader: [GSMimeHeader headerWithName: @"content-transfer-encoding"
value: @"binary"
parameters: nil]];
data = [NSData dataWithContentsOfFile: @"mime8.dat"];
PASS([[doc rawMimeData] isEqual: data], "Can make a simple document");
string = @"ABCD credit card account more information about Peach Pay.";
[doc setHeader:
[[GSMimeHeader alloc] initWithName: @"subject"
value: string
parameters: nil]];
[doc setHeader: [GSMimeHeader headerWithName: @"subject"
value: string
parameters: nil]];
data = [doc rawMimeData];
PASS(data != nil, "Can use non-ascii character in subject");
doc = [GSMimeParser documentFromData: data];
@ -60,14 +58,15 @@ int main(int argc,char **argv)
PASS_EQUAL([[doc headerNamed: @"subject"] value], string,
"Can restore non-ascii character in subject form serialized document");
[doc setHeader:
[[GSMimeHeader alloc] initWithName: @"subject"
value: @"€"
parameters: nil]];
[doc setHeader: [GSMimeHeader headerWithName: @"subject"
value: @"€"
parameters: nil]];
data = [doc rawMimeData];
/*
const char *bytes = "MIME-Version: 1.0\r\n"
"Content-Type: text/plain; type=\"my/type\"\r\n"
"Subject: =?utf-8?B?4oKs?=\r\n\r\n";
*/
PASS(find((char*)[data bytes], (unsigned)[data length], "?B?4oKs?=") > 0,
"encodes utf-8 euro in subject");

View file

@ -8,8 +8,8 @@ int main()
NSAutoreleasePool *arp = [NSAutoreleasePool new];
GSMimeParser *parser = [GSMimeParser mimeParser];
NSStringEncoding enc = [GSMimeDocument encodingFromCharset: @"utf-8"];
NSData *data;
GSMimeDocument *doc = [[parser mimeDocument] retain];
NSData *data;
GSMimeDocument *doc = [parser mimeDocument];
GSMimeHeader *hdr;
NSString *val;
NSString *raw;
@ -50,41 +50,46 @@ int main()
PASS([doc contentType] == nil, "First Header not complete until next starts");
data = [@"Content-id: <" dataUsingEncoding:enc];
PASS([parser parse: data] &&
[parser isInHeaders],
"Adding partial headers is ok");
data = [@"Content-id: <" dataUsingEncoding: enc];
PASS([parser parse: data] && [parser isInHeaders],
"Adding partial headers is ok")
PASS([[doc contentType] isEqual: @"application"] &&
[[doc contentSubtype] isEqual:@"xxx"],"Parsed first header as expected");
PASS([[doc contentType] isEqual: @"application"]
&& [[doc contentSubtype] isEqual:@"xxx"],"Parsed first header as expected")
data = [@"hello>\r\n" dataUsingEncoding: enc];
PASS([parser parse: data] &&
[parser isInHeaders],
"Completing partial header is ok");
PASS([parser parse: data] && [parser isInHeaders],
"Completing partial header is ok")
PASS([doc contentID] == nil, "Partial header not complete until next starts");
PASS([doc contentID] == nil, "Partial header not complete until next starts")
data = [@"Folded\r\n : testing\r\n" dataUsingEncoding:enc];
PASS([parser parse:data] && [parser isInHeaders], "Folded header is ok");
PASS([parser parse: data] && [parser isInHeaders], "Folded header is ok")
PASS([@"<hello>" isEqual: [doc contentID]],"Parsed partial header as expected %s",[[doc contentID] UTF8String]);
PASS([@"<hello>" isEqual: [doc contentID]],
"Parsed partial header as expected %s", [[doc contentID] UTF8String])
PASS([doc headerNamed: @"Folded"] == nil,"Folded header not complete until next starts");
PASS([doc headerNamed: @"Folded"] == nil,
"Folded header not complete until next starts")
data = [@"\r" dataUsingEncoding:enc];
PASS([parser parse:data] && [parser isInHeaders], "partial end-of-line is ok");
data = [@"\r" dataUsingEncoding: enc];
PASS([parser parse:data] && [parser isInHeaders],
"partial end-of-line is ok")
PASS([[[doc headerNamed:@"Folded"] value] isEqual: @"testing"],"Parsed folded header as expected %s",[[[doc headerNamed:@"Folded"] value] UTF8String]);
PASS([[[doc headerNamed:@"Folded"] value] isEqual: @"testing"],
"Parsed folded header as expected %s",
[[[doc headerNamed:@"Folded"] value] UTF8String])
data = [@"\n" dataUsingEncoding:enc];
PASS([parser parse:data] && ![parser isInHeaders], "completing end-of-line is ok");
PASS([parser parse:data] && ![parser isInHeaders],
"completing end-of-line is ok")
doc = [GSMimeDocument documentWithContent:[@"\"\\UFE66???\"" propertyList]
type:@"text/plain"
name:nil];
doc = [GSMimeDocument documentWithContent: [@"\"\\UFE66???\"" propertyList]
type: @"text/plain"
name: nil];
[doc rawMimeData];
PASS([[[doc headerNamed:@"content-type"] parameterForKey:@"charset"] isEqual:@"utf-8"],"charset is inferred");
PASS([[[doc headerNamed: @"content-type"] parameterForKey: @"charset"]
isEqual: @"utf-8"], "charset is inferred")
val = @"by mail.turbocat.net (Postfix, from userid 1002) id 90885422ECBF; Sat, 22 Dec 2007 15:40:10 +0100 (CET)";
if ([[NSUserDefaults standardUserDefaults]
@ -96,7 +101,8 @@ int main()
{
raw = @"Received: by mail.turbocat.net (Postfix, from userid 1002) id 90885422ECBF;\r\n Sat, 22 Dec 2007 15:40:10 +0100 (CET)\r\n";
}
hdr = [[GSMimeHeader alloc] initWithName: @"Received" value: val];
hdr = AUTORELEASE([[GSMimeHeader alloc]
initWithName: @"Received" value: val]);
data = [hdr rawMimeDataPreservingCase: YES];
// NSLog(@"Header: '%*.*s'", [data length], [data length], [data bytes]);
PASS([data isEqual: [raw dataUsingEncoding: NSASCIIStringEncoding]],
@ -104,14 +110,14 @@ int main()
data = [NSData dataWithContentsOfFile: @"HTTP1.dat"];
parser = [GSMimeParser mimeParser];
PASS ([parser parse: data] == NO, "can parse HTTP 200 reponse in one go");
PASS ([parser isComplete], "parse is complete");
PASS([parser parse: data] == NO, "can parse HTTP 200 reponse in one go")
PASS([parser isComplete], "parse is complete")
data = [NSData dataWithContentsOfFile: @"HTTP2.dat"];
parser = [GSMimeParser mimeParser];
PASS ([parser parse: data] == NO, "can parse HTTP chunked in one go");
PASS ([parser isComplete], "parse is complete");
PASS ([parser isComplete], "parse is complete");
PASS([parser parse: data] == NO, "can parse HTTP chunked in one go")
PASS([parser isComplete], "parse is complete")
PASS([parser isComplete], "parse is complete")
PASS_EQUAL([[parser mimeDocument] convertToText],
@"This is the data in the first chunk\r\nand this is the second one\r\n"

View file

@ -6,30 +6,30 @@
#import "ObjectTesting.h"
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSFileManager *mgr;
GSXMLParser *parser;
GSXMLDocument *doc;
GSXMLNamespace *namespace;
NSMutableArray *iparams;
NSMutableArray *oparams;
GSXMLNode *node;
GSXMLRPC *rpc;
NSString *str;
NSString *testPath;
NSString *absolutePath;
NSData *dat;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSFileManager *mgr;
GSXMLParser *parser;
GSXMLDocument *doc;
GSXMLNamespace *namespace;
NSMutableArray *iparams;
NSMutableArray *oparams;
GSXMLNode *node;
GSXMLRPC *rpc;
NSString *str;
NSString *testPath;
NSString *absolutePath;
NSData *dat;
TEST_FOR_CLASS(@"GSXMLDocument",[GSXMLDocument alloc],
TEST_FOR_CLASS(@"GSXMLDocument", AUTORELEASE([GSXMLDocument alloc]),
"GSXMLDocument +alloc returns a GSXMLDocument");
TEST_FOR_CLASS(@"GSXMLDocument",[GSXMLDocument documentWithVersion: @"1.0"],
TEST_FOR_CLASS(@"GSXMLDocument", [GSXMLDocument documentWithVersion: @"1.0"],
"GSXMLDocument +documentWithVersion: returns a GSXMLDocument");
TEST_FOR_CLASS(@"GSXMLNode",[GSXMLNode alloc],
TEST_FOR_CLASS(@"GSXMLNode", AUTORELEASE([GSXMLNode alloc]),
"GSXMLNode +alloc returns a GSXMLNode");
TEST_FOR_CLASS(@"GSXMLRPC",[GSXMLRPC alloc],
TEST_FOR_CLASS(@"GSXMLRPC", AUTORELEASE([GSXMLRPC alloc]),
"GSXMLRPC +alloc returns a GSXMLRPC instance");
NS_DURING
@ -39,7 +39,7 @@ int main()
PASS(node == nil, "GSXMLNode +new returns nil");
NS_ENDHANDLER
TEST_FOR_CLASS(@"GSXMLNamespace",[GSXMLNamespace alloc],
TEST_FOR_CLASS(@"GSXMLNamespace", AUTORELEASE([GSXMLNamespace alloc]),
"GSXMLNamespace +alloc returns a GSXMLNamespace");
@ -54,7 +54,6 @@ int main()
node = [doc makeNodeWithNamespace: nil name: @"nicola" content: nil];
PASS (node != nil,"Can create a document node");
[doc setRoot: node];
PASS([[doc root] isEqual: node],"Can set document node as root node");
@ -85,7 +84,8 @@ int main()
"A namespace remembers its prefix");
rpc = [(GSXMLRPC*)[GSXMLRPC alloc] initWithURL: @"http://localhost/"];
rpc = AUTORELEASE([(GSXMLRPC*)[GSXMLRPC alloc]
initWithURL: @"http://localhost/"]);
PASS(rpc != nil, "Can initialise an RPC instance");
iparams = [NSMutableArray array];

View file

@ -45,7 +45,7 @@ int main(int argc,char **argv)
result = [[array valueForKeyPath:@"@count"] intValue] == 2;
PASS(result, "-[NSArray valueForKeyPath: @\"@count\"]");
aiv = [ArrayIVar new];
aiv = AUTORELEASE([ArrayIVar new]);
ivar = [NSArray arrayWithObjects: @"Joe", @"Foo", @"Bar", @"Cat", nil];
[aiv setTestArray: ivar];

View file

@ -43,9 +43,9 @@ int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
DefaultNil * defaultNil = [DefaultNil new];
DeprecatedNil * deprecatedNil = [DeprecatedNil new];
SetNil * setNil = [SetNil new];
DefaultNil *defaultNil = AUTORELEASE([DefaultNil new]);
DeprecatedNil *deprecatedNil = AUTORELEASE([DeprecatedNil new]);
SetNil *setNil = AUTORELEASE([SetNil new]);
PASS_EXCEPTION([defaultNil setValue: nil forKey: @"num"],
NSInvalidArgumentException, "KVC handles setting nil for a scalar")

View file

@ -30,10 +30,10 @@ print_matrix (const char *str, NSAffineTransformStruct MM)
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSAffineTransform *testObj;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSAffineTransform *testObj;
NSAffineTransformStruct flip = {1.0,0.0,0.0,-1.0,0.0,0.0};
NSMutableArray *testObjs = [NSMutableArray new];
NSMutableArray *testObjs = [NSMutableArray array];
NSAffineTransform *aa, *bb, *cc;
NSAffineTransformStruct as = {2, 3, 4, 5, 10, 20};
NSAffineTransformStruct bs = {6, 7, 8, 9, 14, 15};
@ -55,7 +55,7 @@ int main()
NSPoint p;
NSSize s;
testObj = [NSAffineTransform new];
testObj = AUTORELEASE([NSAffineTransform new]);
[testObjs addObject:testObj];
PASS(testObj != nil, "can create a new transfor");
@ -109,19 +109,19 @@ int main()
[bb setTransformStruct: bs];
/* Append matrix */
cc = [aa copy];
cc = AUTORELEASE([aa copy]);
[cc appendTransform: bb];
cs = [cc transformStruct];
PASS((is_equal_struct(cs, answer1)), "appendTransform:")
/* Prepend matrix */
cc = [aa copy];
cc = AUTORELEASE([aa copy]);
[cc prependTransform: bb];
cs = [cc transformStruct];
PASS((is_equal_struct(cs, answer2)), "prependTransform:")
/* scaling */
cc = [aa copy];
cc = AUTORELEASE([aa copy]);
[cc scaleXBy: 3 yBy: 2];
cs = [cc transformStruct];
PASS((is_equal_struct(cs, answer3)), "scaleXBy:yBy:")
@ -132,7 +132,7 @@ int main()
//print_matrix ("Trans X Scale X A", cs);
/* rotation */
cc = [aa copy];
cc = AUTORELEASE([aa copy]);
[cc rotateByDegrees: 2.5];
cs = [cc transformStruct];
PASS((is_equal_struct(cs, answer5)), "rotateByDegrees")

View file

@ -4,9 +4,11 @@ int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
test_alloc(@"NSArchiver");
test_NSObject(@"NSArchiver",[NSArray arrayWithObject:[[NSArchiver alloc] init]]);
test_NSObject(@"NSArchiver",
[NSArray arrayWithObject: AUTORELEASE([[NSArchiver alloc] init])]);
test_alloc(@"NSUnarchiver");
test_NSObject(@"NSUnarchiver",[NSArray arrayWithObject:[[NSUnarchiver alloc] init]]);
test_NSObject(@"NSUnarchiver",
[NSArray arrayWithObject: AUTORELEASE([[NSUnarchiver alloc] init])]);
[arp release]; arp = nil;
return 0;

View file

@ -7,23 +7,21 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id obj = [NSArchiver new];
NSMutableData *data1;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id obj = [NSArchiver new];
NSMutableData *data1;
PASS((obj != nil && [obj isKindOfClass:[NSArchiver class]] &&
[obj archiverData] != nil), "+new creates an empty NSArchiver");
[obj release];
obj = [NSArchiver alloc];
data1 = [NSMutableData dataWithLength: 0];
obj = [obj initForWritingWithMutableData: data1];
PASS((obj != nil && [obj isKindOfClass:[NSArchiver class]] && data1 == [obj archiverData]), "-initForWritingWithMutableData seems ok");
obj = AUTORELEASE([[NSArchiver alloc] initForWritingWithMutableData: data1]);
PASS((obj != nil && [obj isKindOfClass: [NSArchiver class]]
&& data1 == [obj archiverData]), "-initForWritingWithMutableData seems ok");
PASS_EXCEPTION([[NSUnarchiver alloc] initForReadingWithData:nil];,
@"NSInvalidArgumentException",
"Creating an NSUnarchiver with nil data throws an exception");
@"NSInvalidArgumentException",
"Creating an NSUnarchiver with nil data throws an exception");
[arp release]; arp = nil;
return 0;

View file

@ -4,44 +4,46 @@
int main()
{
NSArray *obj;
NSMutableArray *testObjs = [[NSMutableArray alloc] init];
NSString *str;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSArray *obj;
NSMutableArray *testObjs = [NSMutableArray array];
NSString *str;
test_alloc(@"NSArray");
obj = [NSArray new];
obj = [NSArray array];
PASS((obj != nil && [obj count] == 0),"can create an empty array");
str = @"hello";
[testObjs addObject: obj];
obj = [NSArray arrayWithObject:str];
PASS((obj != nil && [obj count] == 1), "can create an array with one element");
obj = [NSArray arrayWithObject: str];
PASS((obj != nil && [obj count] == 1),
"can create an array with one element")
[testObjs addObject: obj];
test_NSObject(@"NSArray", testObjs);
test_NSCoding(testObjs);
test_keyed_NSCoding(testObjs);
test_NSCopying(@"NSArray",@"NSMutableArray",testObjs,YES,NO);
test_NSMutableCopying(@"NSArray",@"NSMutableArray",testObjs);
test_NSCopying(@"NSArray", @"NSMutableArray", testObjs, YES, NO);
test_NSMutableCopying(@"NSArray", @"NSMutableArray", testObjs);
obj = [NSArray arrayWithContentsOfFile: @"test.plist"];
PASS((obj != nil && [obj count] > 0),"can create an array from file");
PASS((obj != nil && [obj count] > 0),"can create an array from file")
#if 1
/* The apple foundation is arguably buggy in that it seems to create a
* mutable array ... we currently copy that
*/
PASS([obj isKindOfClass: [NSMutableArray class]] == YES,"array mutable");
PASS_RUNS([(NSMutableArray*)obj addObject: @"x"],"can add to array");
PASS([obj isKindOfClass: [NSMutableArray class]] == YES, "array mutable")
PASS_RUNS([(NSMutableArray*)obj addObject: @"x"], "can add to array")
#else
PASS([obj isKindOfClass: [NSMutableArray class]] == NO,"array immutable");
PASS([obj isKindOfClass: [NSMutableArray class]] == NO, "array immutable")
#endif
obj = [obj objectAtIndex: 0];
PASS([obj isKindOfClass: [NSMutableArray class]] == YES,"array mutable");
PASS([obj isKindOfClass: [NSMutableArray class]] == YES, "array mutable")
START_SET("NSArray subscripting")
# ifndef __has_feature
# define __has_feature(x) 0
# endif
#if __has_feature(objc_subscripting)
NSArray *a = @[ @"foo", @"bar" ];
PASS([@"foo" isEqualToString:a[0]], "Array subscripting works");
PASS([@"foo" isEqualToString:a[0]], "Array subscripting works")
# else
SKIP("No collection subscripting support in the compiler.")
# endif

View file

@ -3,8 +3,10 @@
#import "ObjectTesting.h"
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSArray *arr = [NSArray arrayWithObject:[NSAttributedString new]];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSArray *arr;
arr = [NSArray arrayWithObject: AUTORELEASE([NSAttributedString new])];
test_alloc(@"NSAttributedString");
test_NSObject(@"NSAttributedString", arr);

View file

@ -5,46 +5,47 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSAttributedString *s;
NSString *key1, *val1, *str1;
NSRange r = NSMakeRange(0,6);
NSAttributedString *astr1, *astr2;
NSDictionary *dict1;
NSRange range = NSMakeRange(0,0);
id obj;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSAttributedString *s;
NSString *key1, *val1, *str1;
NSRange r = NSMakeRange(0,6);
NSAttributedString *astr1, *astr2;
NSDictionary *dict1;
NSRange range = NSMakeRange(0,0);
id obj;
s = [[[NSAttributedString alloc] initWithString: @"string"] autorelease];
PASS_EQUAL([s string], @"string", "equality OK for string value");
PASS([s length] == 6, "length reported correctly");
s = AUTORELEASE([[NSAttributedString alloc] initWithString: @"string"]);
PASS_EQUAL([s string], @"string", "equality OK for string value")
PASS([s length] == 6, "length reported correctly")
PASS_EQUAL([s attributesAtIndex: 0 effectiveRange: NULL],
[NSDictionary dictionary], "returnsempty attributes dictionary, not nil");
[NSDictionary dictionary], "returnsempty attributes dictionary, not nil")
key1 = @"Helvetica 12-point";
val1 = @"NSFontAttributeName";
str1 = @"Attributed string test";
dict1 = [NSDictionary dictionaryWithObject:val1 forKey:key1];
dict1 = [NSDictionary dictionaryWithObject: val1 forKey: key1];
astr1 = [[NSAttributedString alloc] initWithString: str1 attributes: dict1];
PASS(astr1 != nil && [astr1 isKindOfClass: [NSAttributedString class]] &&
[[astr1 string] isEqual: str1],"-initWithString:attributes: works");
astr1 = AUTORELEASE([[NSAttributedString alloc]
initWithString: str1 attributes: dict1]);
PASS(astr1 != nil && [astr1 isKindOfClass: [NSAttributedString class]]
&& [[astr1 string] isEqual: str1], "-initWithString:attributes: works")
obj = [astr1 attributesAtIndex: 0 effectiveRange: &range];
PASS(obj != nil && [obj isKindOfClass: [NSDictionary class]] &&
[obj count] == 1 && range.length != 0,
"-attributesAtIndex:effectiveRange: works");
PASS(obj != nil && [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 1 && range.length != 0,
"-attributesAtIndex:effectiveRange: works")
obj = [astr1 attribute: key1 atIndex: 0 effectiveRange: &range];
PASS(obj != nil && [obj isEqual: val1] && range.length != 0,
"-attribute:atIndex:effectiveRange: works");
"-attribute:atIndex:effectiveRange: works")
obj = [astr1 attributedSubstringFromRange: r];
PASS(obj != nil && [obj isKindOfClass: [NSAttributedString class]] &&
[obj length] == r.length,"-attributedSubstringFromRange works");
PASS(obj != nil && [obj isKindOfClass: [NSAttributedString class]]
&& [obj length] == r.length, "-attributedSubstringFromRange works")
r = NSMakeRange(0,[astr1 length]);
r = NSMakeRange(0, [astr1 length]);
astr2 = [astr1 attributedSubstringFromRange: r];
PASS(astr2 != nil && [astr1 isEqualToAttributedString: astr2],
"extract and compare using -isEqualToAttributedString works");
"extract and compare using -isEqualToAttributedString works")
[arp release]; arp = nil;
return 0;

View file

@ -3,13 +3,12 @@
#import <Foundation/NSException.h>
@interface TestClass : NSObject
- (void)runTest;
- (void)exceptionThrowingMethod;
- (void) runTest;
- (void) exceptionThrowingMethod;
@end
@implementation TestClass
- (void)runTest
- (void) runTest
{
int c = 0;
int i;
@ -19,21 +18,26 @@
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NS_DURING
[self exceptionThrowingMethod];
[self exceptionThrowingMethod];
NS_HANDLER
c++;
c++;
NS_ENDHANDLER
[pool release];
}
PASS(c == 10, "Caught the correct number of exceptions without breaking the autorelease pool\n");
PASS(c == 10, "Caught the correct number of exceptions"
" without breaking the autorelease pool")
}
- (void)exceptionThrowingMethod
- (void) exceptionThrowingMethod
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
[@"Hello" stringByAppendingString: @" something to create a autoreleased object"];
NSAutoreleasePool *pool = [NSAutoreleasePool new];
[@"Hello" stringByAppendingString:
@" something to create a autoreleased object"];
NSLog(@"Throwing an exception");
[[NSException exceptionWithName: @"MyFunException" reason: @"it was always meant to happen" userInfo: [NSDictionary dictionary]] raise];
[[NSException exceptionWithName: @"MyFunException"
reason: @"it was always meant to happen"
userInfo: [NSDictionary dictionary]] raise];
[pool release]; // Obviously this doesn't get run, but the [NSAutorelease new] at the top causes the problem
}
@ -41,8 +45,9 @@
int main(int argc, char** argv)
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];
TestClass *testClass = [[TestClass new] autorelease];
NSAutoreleasePool *pool = [NSAutoreleasePool new];
TestClass *testClass = [[TestClass new] autorelease];
[testClass runTest];
[pool release];
PASS(1, "Destroying pools in the wrong order didn't break anything...");

View file

@ -7,7 +7,8 @@ int main()
NSAutoreleasePool *arp = [NSAutoreleasePool new];
test_alloc(@"NSBundle");
test_NSObject(@"NSBundle", [NSArray arrayWithObject:[NSBundle new]]);
test_NSObject(@"NSBundle",
[NSArray arrayWithObject: AUTORELEASE([NSBundle new])]);
[arp release]; arp = nil;
return 0;
}

View file

@ -31,29 +31,38 @@ int main()
START_SET("NSCalendar getEra:year:month:day:fromDate and getHour:minute:second:nanosecond:fromDate tests");
/* Test getEra:year:month:day:fromDate:
*/
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale: [[NSLocale alloc] initWithLocaleIdentifier:
[NSLocale canonicalLocaleIdentifierFromString: @"en_US"]]];
dateFormatter = AUTORELEASE([[NSDateFormatter alloc] init]);
[dateFormatter setLocale: AUTORELEASE([[NSLocale alloc]
initWithLocaleIdentifier: [NSLocale
canonicalLocaleIdentifierFromString: @"en_US"]])];
cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithName: @"America/New_York"]];
[cal setTimeZone: [NSTimeZone timeZoneWithName: @"America/New_York"]];
[dateFormatter setDateFormat: @"d MMM yyyy HH:mm:ss Z"];
date = [dateFormatter dateFromString:@"22 Nov 1969 08:15:00 Z"];
date = [dateFormatter dateFromString: @"22 Nov 1969 08:15:00 Z"];
[cal getEra:&era year:&year month:&month day:&day fromDate:date];
[cal getEra: &era year: &year month: &month day: &day fromDate: date];
PASS(era == 1, "getEra:year:month:day:fromDate: returns correct era");
PASS(year == 1969, "getEra:year:month:day:fromDate: returns correct year");
PASS(month == 11, "getEra:year:month:day:fromDate: returns correct month");
PASS(day == 22, "getEra:year:month:day:fromDate: returns correct day");
PASS(era == 1, "getEra:year:month:day:fromDate: returns correct era")
PASS(year == 1969, "getEra:year:month:day:fromDate: returns correct year")
PASS(month == 11, "getEra:year:month:day:fromDate: returns correct month")
PASS(day == 22, "getEra:year:month:day:fromDate: returns correct day")
/* Test getHour:minute:second:nanosecond:fromDate:
*/
[cal getHour:&hour minute:&min second:&sec nanosecond:&nano fromDate:date];
[cal getHour: &hour
minute: &min
second: &sec
nanosecond: &nano
fromDate: date];
PASS(hour == 3, "getHour:minute:second:nanosecond:fromDate: returns correct hour");
PASS(min == 15, "getHour:minute:second:nanosecond:fromDate: returns correct minute");
PASS(sec == 0, "getHour:minute:second:nanosecond:fromDate: returns correct second");
PASS(nano == 0, "getHour:minute:second:nanosecond:fromDate: returns correct nanosecond");
PASS(hour == 3, "getHour:minute:second:nanosecond:fromDate:"
" returns correct hour")
PASS(min == 15, "getHour:minute:second:nanosecond:fromDate:"
" returns correct minute")
PASS(sec == 0, "getHour:minute:second:nanosecond:fromDate:"
" returns correct second")
PASS(nano == 0, "getHour:minute:second:nanosecond:fromDate:"
" returns correct nanosecond")
END_SET("NSCalendar getEra:year:month:day:fromDate and getHour:minute:second:nanosecond:fromDate tests");
return 0;

View file

@ -5,8 +5,8 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObj = [NSCalendarDate new];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObj = AUTORELEASE([NSCalendarDate new]);
test_NSObject(@"NSCalendarDate", [NSArray arrayWithObject: testObj]);
test_NSCoding([NSArray arrayWithObject: testObj]);

View file

@ -9,15 +9,15 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableArray *tmpArray;
NSMutableDictionary *myLocale;
NSCalendarDate *myBirthday;
NSCalendarDate *anotherDay;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableArray *tmpArray;
NSMutableDictionary *myLocale;
NSCalendarDate *myBirthday;
NSCalendarDate *anotherDay;
myLocale = westernLocale();
tmpArray = [NSMutableArray new];
tmpArray = [NSMutableArray array];
[tmpArray addObject: @"Gen"];
[tmpArray addObject: @"Feb"];
[tmpArray addObject: @"Mar"];
@ -32,7 +32,7 @@ int main()
[tmpArray addObject: @"Dic"];
[myLocale setObject: tmpArray forKey: NSShortMonthNameArray];
ASSIGN(tmpArray,[NSMutableArray new]);
tmpArray = [NSMutableArray array];
[tmpArray addObject: @"Gennaio"];
[tmpArray addObject: @"Febbraio"];
[tmpArray addObject: @"Marzo"];
@ -47,7 +47,7 @@ int main()
[tmpArray addObject: @"Dicembre"];
[myLocale setObject: tmpArray forKey: NSMonthNameArray];
ASSIGN(tmpArray,[NSMutableArray new]);
tmpArray = [NSMutableArray array];
[tmpArray addObject: @"Dom"];
[tmpArray addObject: @"Lun"];
[tmpArray addObject: @"Mar"];
@ -57,7 +57,7 @@ int main()
[tmpArray addObject: @"Sab"];
[myLocale setObject: tmpArray forKey: NSShortWeekDayNameArray];
ASSIGN(tmpArray,[NSMutableArray new]);
tmpArray = [NSMutableArray array];
[tmpArray addObject: @"Domencia"];
[tmpArray addObject: @"Lunedi"];
[tmpArray addObject: @"Martedi"];
@ -67,7 +67,7 @@ int main()
[tmpArray addObject: @"Sabato"];
[myLocale setObject: tmpArray forKey: NSWeekDayNameArray];
ASSIGN(tmpArray,[NSMutableArray new]);
tmpArray = [NSMutableArray array];
[tmpArray addObject: @"AM"];
[tmpArray addObject: @"PM"];
[myLocale setObject: tmpArray forKey: NSAMPMDesignation];

View file

@ -81,6 +81,7 @@ int main()
strEnc = [data base64EncodedStringWithOptions:0];
data = [[NSData alloc] initWithBase64EncodedString: strEnc options: 0];
str2 = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
[data release];
PASS_EQUAL(str1, str2, "Encode / Decode no lines")
[str2 release];
@ -90,6 +91,7 @@ int main()
data = [[NSData alloc] initWithBase64EncodedString: strEnc
options: NSDataBase64DecodingIgnoreUnknownCharacters];
str2 = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
[data release];
PASS_EQUAL(str1, str2, "Encode / Decode 64 - LF")
[str2 release];
@ -99,6 +101,7 @@ int main()
data = [[NSData alloc] initWithBase64EncodedString: strEnc
options: NSDataBase64DecodingIgnoreUnknownCharacters];
str2 = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
[data release];
PASS_EQUAL(str1, str2, "Encode / Decode 76 - LF")
[str2 release];
@ -108,6 +111,7 @@ int main()
data = [[NSData alloc] initWithBase64EncodedString: strEnc
options: NSDataBase64DecodingIgnoreUnknownCharacters];
str2 = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
[data release];
PASS_EQUAL(str1, str2, "Encode / Decode 64 - CR")
[str2 release];
@ -117,6 +121,7 @@ int main()
data = [[NSData alloc] initWithBase64EncodedString: strEnc
options: NSDataBase64DecodingIgnoreUnknownCharacters];
str2 = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
[data release];
PASS_EQUAL(str1, str2, "Encode / Decode 64 - implicit CR LF")
[str2 release];

View file

@ -4,18 +4,19 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObject = [NSData new];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObject = AUTORELEASE([NSData new]);
test_alloc(@"NSData");
test_NSObject(@"NSData",[NSArray arrayWithObject:testObject]);
test_NSCoding([NSArray arrayWithObject:testObject]);
test_keyed_NSCoding([NSArray arrayWithObject:testObject]);
test_NSObject(@"NSData", [NSArray arrayWithObject: testObject]);
test_NSCoding([NSArray arrayWithObject: testObject]);
test_keyed_NSCoding([NSArray arrayWithObject: testObject]);
test_NSCopying(@"NSData",
@"NSMutableData",
[NSArray arrayWithObject:testObject], NO, NO);
[NSArray arrayWithObject: testObject], NO, NO);
test_NSMutableCopying(@"NSData",
@"NSMutableData",
[NSArray arrayWithObject:testObject]);
[NSArray arrayWithObject: testObject]);
[arp release]; arp = nil;
return 0;

View file

@ -6,67 +6,69 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
char *str1,*str2;
NSData *data1, *data2;
NSMutableData *mutable;
char *hold;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
char *str1, *str2;
NSData *data1, *data2;
NSMutableData *mutable;
char *hold;
str1 = "Test string for data classes";
str2 = (char *) malloc(sizeof("Test string for data classes not copied"));
strcpy(str2,"Test string for data classes not copied");
mutable = [NSMutableData dataWithLength:100];
mutable = [NSMutableData dataWithLength: 100];
hold = [mutable mutableBytes];
/* hmpf is this correct */
data1 = [NSData dataWithBytes:str1 length:(strlen(str1) * sizeof(void*))];
PASS(data1 != nil &&
[data1 isKindOfClass:[NSData class]] &&
[data1 length] == (strlen(str1) * sizeof(void*)) &&
[data1 bytes] != str1 &&
strcmp(str1,[data1 bytes]) == 0,
"+dataWithBytes:length: works");
data1 = [NSData dataWithBytes: str1 length: strlen(str1) + 1];
PASS(data1 != nil
&& [data1 isKindOfClass: [NSData class]]
&& [data1 length] == strlen(str1) + 1
&& [data1 bytes] != str1
&& strcmp(str1, [data1 bytes]) == 0,
"+dataWithBytes:length: works")
data2 = [NSData dataWithBytesNoCopy:str2 length:(strlen(str2) * sizeof(void*))];
PASS(data2 != nil && [data2 isKindOfClass:[NSData class]] &&
[data2 length] == (strlen(str2) * sizeof(void*)) &&
[data2 bytes] == str2,
"+dataWithBytesNoCopy:length: works");
data2 = [NSData dataWithBytesNoCopy: str2
length: strlen(str2) + 1];
PASS(data2 != nil && [data2 isKindOfClass: [NSData class]]
&& [data2 length] == strlen(str2) + 1
&& [data2 bytes] == str2,
"+dataWithBytesNoCopy:length: works")
data1 = [NSData dataWithBytes:nil length:0];
PASS(data1 != nil && [data1 isKindOfClass:[NSData class]] &&
[data1 length] == 0,
"+dataWithBytes:length works with 0 length");
data1 = [NSData dataWithBytes: nil length: 0];
PASS(data1 != nil && [data1 isKindOfClass: [NSData class]]
&& [data1 length] == 0,
"+dataWithBytes:length works with 0 length")
[data2 getBytes:hold range:NSMakeRange(2,6)];
PASS(strcmp(hold,"st str") == 0, "-getBytes:range works");
[data2 getBytes: hold range: NSMakeRange(2,6)];
PASS(strcmp(hold, "st str") == 0, "-getBytes:range works")
PASS_EXCEPTION([data2 getBytes:hold
range:NSMakeRange(strlen(str2)*sizeof(void*),1)];,
NSRangeException,
"getBytes:range: with bad location");
PASS_EXCEPTION([data2 getBytes: hold
range: NSMakeRange(strlen(str2) + 1, 1)];,
NSRangeException,
"getBytes:range: with bad location")
PASS_EXCEPTION([data2 getBytes:hold
range:NSMakeRange(1,(strlen(str2)*sizeof(void*)))];,
NSRangeException,
"getBytes:range: with bad length");
PASS_EXCEPTION([data2 getBytes: hold
range: NSMakeRange(1, strlen(str2) + 1)];,
NSRangeException,
"getBytes:range: with bad length")
PASS_EXCEPTION([data2 subdataWithRange:NSMakeRange((strlen(str2)*sizeof(void*)),1)];,
NSRangeException,
"-subdataWithRange: with bad location");
PASS_EXCEPTION([data2 subdataWithRange:
NSMakeRange(strlen(str2) + 1, 1)];,
NSRangeException,
"-subdataWithRange: with bad location")
PASS_EXCEPTION([data2 subdataWithRange:NSMakeRange(1,(strlen(str2)*sizeof(void*)))];,
NSRangeException,
"-subdataWithRange: with bad length");
PASS_EXCEPTION([data2 subdataWithRange:
NSMakeRange(1, strlen(str2) + 1)];,
NSRangeException,
"-subdataWithRange: with bad length")
data2 = [NSData dataWithBytesNoCopy:str1
length:(strlen(str1) * sizeof(void*))
freeWhenDone:NO];
PASS(data2 != nil && [data2 isKindOfClass:[NSData class]] &&
[data2 length] == (strlen(str1) * sizeof(void*)) &&
[data2 bytes] == str1,
"+dataWithBytesNoCopy:length:freeWhenDone: works");
data2 = [NSData dataWithBytesNoCopy: str1
length: strlen(str1) + 1
freeWhenDone: NO];
PASS(data2 != nil && [data2 isKindOfClass: [NSData class]]
&& [data2 length] == (strlen(str1) + 1)
&& [data2 bytes] == str1,
"+dataWithBytesNoCopy:length:freeWhenDone: works")
[arp release]; arp = nil;

View file

@ -7,22 +7,24 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableArray *testObjs = [NSMutableArray new];
NSDictionary *obj;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableArray *testObjs = [NSMutableArray array];
NSDictionary *obj;
test_alloc(@"NSDictionary");
obj = [NSDictionary new];
[testObjs addObject:obj];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 0,
"can create an empty dictionary");
obj = [NSDictionary dictionaryWithObject:@"Hello" forKey:@"Key"];
[testObjs addObject:obj];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 1,
"can create a dictionary with one element");
obj = [NSDictionary dictionary];
[testObjs addObject: obj];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 0,
"can create an empty dictionary")
obj = [NSDictionary dictionaryWithObject: @"Hello" forKey: @"Key"];
[testObjs addObject: obj];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 1,
"can create a dictionary with one element")
test_NSObject(@"NSDictionary", testObjs);
test_NSCoding(testObjs);
@ -36,7 +38,7 @@ int main()
#if __has_feature(objc_subscripting)
NSDictionary *dictionary = @{@123 : @123.4 ,
@"date" : @"today" };
PASS([dictionary[@123] isEqual: @123.4], "Dictionary subscripting works");
PASS([dictionary[@123] isEqual: @123.4], "Dictionary subscripting works")
# else
SKIP("No dictionary subscripting support in the compiler.")
# endif

View file

@ -4,75 +4,77 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSString *key1, *key2, *key3, *val1, *val2, *val3;
NSArray *keys1, *keys2, *keys3, *vals1, *vals2, *vals3;
NSDictionary *obj,*old;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSString *key1, *key2, *key3, *val1, *val2, *val3;
NSArray *keys1, *keys2, *keys3, *vals1, *vals2, *vals3;
NSDictionary *obj,*old;
old = nil;
key1 = @"Key1";
key2 = @"Key2";
key3 = @"Key3";
keys1 = [NSArray arrayWithObjects:key1, key2, nil];
keys2 = [NSArray arrayWithObjects:key1, key2, key3, nil];
keys1 = [NSArray arrayWithObjects: key1, key2, nil];
keys2 = [NSArray arrayWithObjects: key1, key2, key3, nil];
/* duplicate keys */
keys3 = [NSArray arrayWithObjects:key1, key2, key2, nil];
keys3 = [NSArray arrayWithObjects: key1, key2, key2, nil];
val1 = @"Kidnapped";
val2 = @"tied up";
val3 = @"taken away and helf for ransom";
vals1 = [NSArray arrayWithObjects:val1, val2, nil];
vals1 = [NSArray arrayWithObjects: val1, val2, nil];
/* duplicate values */
vals2 = [NSArray arrayWithObjects:val1, val2, val2, nil];
vals3 = [NSArray arrayWithObjects:val1, val2, val3, nil];
obj = [NSDictionary new];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 0,
"+new creates an empty dictionary");
vals2 = [NSArray arrayWithObjects: val1, val2, val2, nil];
vals3 = [NSArray arrayWithObjects: val1, val2, val3, nil];
obj = [NSDictionary dictionary];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 0,
"+new creates an empty dictionary")
obj = [NSDictionary dictionary];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 0,
"+dictionary creates an empty dictionary");
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 0,
"+dictionary creates an empty dictionary")
PASS_EXCEPTION([NSDictionary dictionaryWithObject:val1 forKey:nil];,
NSInvalidArgumentException,
"+dictionaryWithObject:forKey: with nil key");
PASS_EXCEPTION([NSDictionary dictionaryWithObject: val1 forKey: nil];,
NSInvalidArgumentException,
"+dictionaryWithObject:forKey: with nil key")
PASS_EXCEPTION([NSDictionary dictionaryWithObject:nil forKey:key1];,
NSInvalidArgumentException,
"+dictionaryWithObject:forKey: with nil value");
PASS_EXCEPTION([NSDictionary dictionaryWithObject: nil forKey: key1];,
NSInvalidArgumentException,
"+dictionaryWithObject:forKey: with nil value")
obj = [NSDictionary dictionaryWithObject:val1 forKey:key1];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 1,
"+dictionaryWithObject:forKey: builds minimal dictionary");
obj = [NSDictionary dictionaryWithObject: val1 forKey: key1];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 1,
"+dictionaryWithObject:forKey: builds minimal dictionary")
obj = [NSDictionary dictionaryWithObjects: vals1 forKeys: keys1];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 2,
"+dictionaryWithObjects:forKeys: builds a dictionary")
PASS_EXCEPTION([NSDictionary dictionaryWithObjects: vals1 forKeys: keys2];,
NSInvalidArgumentException,
"+dictionaryWithObjects:forKeys: with arrays of different sizes")
obj = [NSDictionary dictionaryWithObjects: vals2 forKeys: keys2];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 3,
"we can have multiple identical objects in a dictionary")
obj = [NSDictionary dictionaryWithObjects:vals1 forKeys:keys1];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 2,
"+dictionaryWithObjects:forKeys: builds a dictionary");
PASS_EXCEPTION([NSDictionary dictionaryWithObjects:vals1 forKeys:keys2];,
NSInvalidArgumentException,
"+dictionaryWithObjects:forKeys: with arrays of different sizes");
obj = [NSDictionary dictionaryWithObjects:vals2 forKeys:keys2];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 3,
"we can have multiple identical objects in a dictionary");
obj = [NSDictionary dictionaryWithObjects:vals3 forKeys:keys3];
PASS(obj != nil &&
[obj isKindOfClass:[NSDictionary class]] &&
[obj count] == 2,
"we can't have multiple identical keys in a dictionary");
obj = [NSDictionary dictionaryWithObjects: vals3 forKeys: keys3];
PASS(obj != nil
&& [obj isKindOfClass: [NSDictionary class]]
&& [obj count] == 2,
"we can't have multiple identical keys in a dictionary")
old = obj;
obj = [NSDictionary dictionaryWithDictionary:old];
PASS(obj != nil &&
[obj isEqual: old], "+dictionaryWithDictionary: copies dictionary");
obj = [NSDictionary dictionaryWithDictionary: old];
PASS(obj != nil
&& [obj isEqual: old], "+dictionaryWithDictionary: copies dictionary")
[arp release]; arp = nil;
return 0;

View file

@ -11,7 +11,7 @@ int main()
NSDistributedLock *lock2;
test_NSObject(@"NSDistributedLock",
[NSArray arrayWithObject: [NSDistributedLock new]]);
[NSArray arrayWithObject: AUTORELEASE([NSDistributedLock new])]);
path = [[NSFileManager defaultManager] currentDirectoryPath];
path = [path stringByAppendingPathComponent: @"MyLock"];

View file

@ -11,10 +11,10 @@ void fast_enumeration_mutation_add(id mutableCollection)
NSUInteger i = 0;
FOR_IN(id, o, mutableCollection)
if (i == [mutableCollection count]/2) {
if ([mutableCollection isKindOfClass:[NSMutableDictionary class]]) {
[mutableCollection setObject:@"boom" forKey:@"boom"];
if ([mutableCollection isKindOfClass: [NSMutableDictionary class]]) {
[mutableCollection setObject: @"boom" forKey: @"boom"];
} else {
[mutableCollection addObject:@"boom"];
[mutableCollection addObject: @"boom"];
}
}
i++;
@ -26,10 +26,10 @@ void fast_enumeration_mutation_remove(id mutableCollection)
NSUInteger i = 0;
FOR_IN(id, o, mutableCollection)
if (i == [mutableCollection count]/2) {
if ([mutableCollection isKindOfClass:[NSMutableDictionary class]]) {
[mutableCollection removeObjectForKey:o];
if ([mutableCollection isKindOfClass: [NSMutableDictionary class]]) {
[mutableCollection removeObjectForKey: o];
} else {
[mutableCollection removeObject:o];
[mutableCollection removeObject: o];
}
}
i++;
@ -38,25 +38,27 @@ void fast_enumeration_mutation_remove(id mutableCollection)
void test_fast_enumeration(id collection, NSArray *objects)
{
NSMutableArray *returnedObjects = [[NSMutableArray alloc] init];
NSMutableArray *returnedObjects = [NSMutableArray array];
FOR_IN(id, o, collection)
[returnedObjects addObject:o];
[returnedObjects addObject: o];
END_FOR_IN(collection)
if (!([collection isKindOfClass:[NSArray class]] ||
[collection isKindOfClass:[NSOrderedSet class]])) {
[returnedObjects sortUsingSelector:@selector(compare:)];
}
PASS_EQUAL(returnedObjects, objects, "fast enumeration returns all objects");
if (!([collection isKindOfClass: [NSArray class]]
|| [collection isKindOfClass: [NSOrderedSet class]]))
{
[returnedObjects sortUsingSelector: @selector(compare:)];
}
PASS_EQUAL(returnedObjects, objects, "fast enumeration returns all objects")
id mutableCollection = [collection mutableCopy];
PASS_EXCEPTION(
fast_enumeration_mutation_add(mutableCollection),
NSGenericException,
"Fast enumeration mutation add properly calls @\"NSGenericException\"");
"Fast enumeration mutation add properly calls @\"NSGenericException\"")
PASS_EXCEPTION(
fast_enumeration_mutation_remove(mutableCollection),
NSGenericException,
"Fast enumeration mutation remove properly calls @\"NSGenericException\"");
"Fast enumeration mutation remove properly calls @\"NSGenericException\"")
[mutableCollection release];
}
@ -67,26 +69,26 @@ int main()
NSMutableArray *objects = [NSMutableArray array];
int i;
for (i = 0; i < 10000; i++) {
[objects addObject:[NSString stringWithFormat:@"%.4d", i]];
[objects addObject: [NSString stringWithFormat: @"%.4d", i]];
}
START_SET("NSArray")
id array = [NSArray arrayWithArray:objects];
id array = [NSArray arrayWithArray: objects];
test_fast_enumeration(array, objects);
END_SET("NSArray")
START_SET("NSSet")
id set = [NSSet setWithArray:objects];
id set = [NSSet setWithArray: objects];
test_fast_enumeration(set, objects);
END_SET("NSSet")
START_SET("NSOrderedSet")
id orderedSet = [NSOrderedSet orderedSetWithArray:objects];
id orderedSet = [NSOrderedSet orderedSetWithArray: objects];
test_fast_enumeration(orderedSet, objects);
END_SET("NSOrderedSet")
START_SET("NSDictionary")
id dict = [NSDictionary dictionaryWithObjects:objects forKeys:objects];
id dict = [NSDictionary dictionaryWithObjects: objects forKeys: objects];
test_fast_enumeration(dict, objects);
END_SET("NSDictionary")

View file

@ -36,43 +36,43 @@ int main()
NSFileHandle *stdInFH = [NSFileHandle fileHandleWithStandardInput];
NSFileHandle *stdNullFH = [NSFileHandle fileHandleWithNullDevice];
NSFileHandle *t1FH, *t2FH;
NSString *tPath = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),[[NSProcessInfo processInfo]globallyUniqueString]];
NSData *t1Data = [tPath dataUsingEncoding:NSUTF8StringEncoding];
NSString *tPath = [NSString stringWithFormat: @"%@/%@",NSTemporaryDirectory(),[[NSProcessInfo processInfo]globallyUniqueString]];
NSData *t1Data = [tPath dataUsingEncoding: NSUTF8StringEncoding];
NSData *t2Data;
PASS([stdInFH isKindOfClass:[NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardInput");
PASS([stdInFH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardInput")
PASS([stdInFH fileDescriptor]==0,
"NSFileHandle +fileHandleWithStandardInput has 0 as fileDescriptor");
"NSFileHandle +fileHandleWithStandardInput has 0 as fileDescriptor")
PASS([stdOutFH isKindOfClass:[NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardOutput");
PASS([stdOutFH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardOutput")
PASS([stdOutFH fileDescriptor]==1,
"NSFileHandle +fileHandleWithStandardOutput has 1 as fileDescriptor");
"NSFileHandle +fileHandleWithStandardOutput has 1 as fileDescriptor")
PASS([stdErrFH isKindOfClass:[NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardError");
PASS([stdErrFH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleWithStandardError")
PASS([stdErrFH fileDescriptor]==2,
"NSFileHandle +fileHandleWithStandardError has 2 as fileDescriptor");
PASS([stdNullFH isKindOfClass:[NSFileHandle class]],
"NSFileHandle understands +fileHandleWithNullDevice");
PASS([stdNullFH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleWithNullDevice")
t1FH = [[NSFileHandle alloc] initWithFileDescriptor: 0];
PASS([t1FH isKindOfClass:[NSFileHandle class]],
"NSFileHandle understands -initWithFileDescriptor:");
t1FH = AUTORELEASE([[NSFileHandle alloc] initWithFileDescriptor: 0]);
PASS([t1FH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands -initWithFileDescriptor:")
t1FH = [NSFileHandle fileHandleForWritingAtPath: tPath];
PASS(t1FH == nil,
"NSFileHandle +fileHandleForWritingAtPath: with non-existing file return nil");
PASS(t1FH == nil, "NSFileHandle +fileHandleForWritingAtPath:"
" with non-existing file return nil")
[@"" writeToFile: tPath atomically: YES];
t1FH = [NSFileHandle fileHandleForWritingAtPath: tPath];
PASS([t1FH isKindOfClass:[NSFileHandle class]],
PASS([t1FH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleForWritingAtPath:");
t2FH = [NSFileHandle fileHandleForReadingAtPath: tPath];
PASS([t2FH isKindOfClass:[NSFileHandle class]],
PASS([t2FH isKindOfClass: [NSFileHandle class]],
"NSFileHandle understands +fileHandleForReadingAtPath:");
[t1FH writeData: t1Data];

View file

@ -56,7 +56,7 @@ int main()
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSFileManager *mgr = [NSFileManager defaultManager];
NSString *dir = @"NSFileManagerTestDir";
MyHandler *handler = [MyHandler new];
MyHandler *handler = AUTORELEASE([MyHandler new]);
NSDictionary *attr;
NSString *dirInDir;
NSString *str1;

View file

@ -4,13 +4,14 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSDictionary *dict;
NSArray *cookies;
NSURL *url;
NSHTTPCookie *cookie;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSDictionary *dict;
NSArray *cookies;
NSURL *url;
NSHTTPCookie *cookie;
TEST_FOR_CLASS(@"NSHTTPCookie", [NSHTTPCookie alloc],
cookie = AUTORELEASE([NSHTTPCookie new]);
TEST_FOR_CLASS(@"NSHTTPCookie", cookie,
"NSHTTPCookie +alloc returns an NSHTTPCookie");
dict = [NSDictionary dictionaryWithObjectsAndKeys: @"myname", @"Name",

View file

@ -33,7 +33,7 @@ int main()
tClass = NSClassFromString(@"InvokeTarget");
tar = [tClass new];
tar = AUTORELEASE([tClass new]);
/*
Test if the return value is retained. It is in the Apple OpenStep edition

View file

@ -16,7 +16,7 @@ int main()
NSInteger length;
NSString *hello = @"hello";
NSString *uppercaseHello;
NSOperationQueue *queue = [NSOperationQueue new];
NSOperationQueue *queue = AUTORELEASE([NSOperationQueue new]);
op = [[NSInvocationOperation alloc] initWithTarget: hello
selector: @selector(length)

View file

@ -103,10 +103,10 @@
@end
@implementation TestKVOChange
+ (id)changeWithKeypath:(NSString *)keypath
object:(id)object
info:(NSDictionary *)info
context:(void *)context
+ (id) changeWithKeypath: (NSString *)keypath
object: (id)object
info: (NSDictionary *)info
context: (void *)context
{
TestKVOChange *change = [[[self alloc] init] autorelease];
[change setKeypath: keypath];
@ -116,55 +116,60 @@
return change;
}
- (NSString *)keypath {
return _keypath;
- (NSString *) keypath
{
return _keypath;
}
- (void)setKeypath:(NSString *)newKeypath
- (void) setKeypath: (NSString *)newKeypath
{
if (_keypath != newKeypath)
if (_keypath != newKeypath)
{
[_keypath release];
_keypath = [newKeypath copy];
[_keypath release];
_keypath = [newKeypath copy];
}
}
- (id)object
- (id) object
{
return _object;
return _object;
}
- (void)setObject:(id)newObject
- (void) setObject: (id)newObject
{
ASSIGN(_object, newObject);
}
- (NSDictionary *)info
{
return _info;
return _info;
}
- (void)setInfo:(NSDictionary *)newInfo
- (void) setInfo: (NSDictionary *)newInfo
{
ASSIGN(_info, [newInfo copy]);
if (newInfo != _info)
{
[_info release];
_info = [newInfo copy];
}
}
- (void *)context
- (void *) context
{
return _context;
return _context;
}
- (void)setContext:(void *)newContext
- (void) setContext:(void *)newContext
{
_context = newContext;
_context = newContext;
}
- (void)dealloc
- (void) dealloc
{
[_object release];
[_keypath release];
[_info release];
[super dealloc];
[_object release];
[_keypath release];
[_info release];
[super dealloc];
}
@end
@ -216,7 +221,7 @@
[_lock lock];
NSSet *paths = [[_changedKeypaths objectForKey:keypath] copy];
[_lock unlock];
return paths;
return AUTORELEASE(paths);
}
- (void)clear
{
@ -239,6 +244,7 @@
- (void) dealloc {
[_lock release];
[_changedKeypaths release];
DEALLOC
}
@end

View file

@ -873,8 +873,11 @@ NSArrayShouldThrowWhenTryingToObserveIndexesOutOfRange()
{
START_SET("NSArrayShouldThrowWhenTryingToObserveIndexesOutOfRange");
NSArray *test = [NSArray arrayWithObjects: [Observee new], [Observee new], nil];
NSArray *o1 = AUTORELEASE([Observee new]);
NSArray *o2 = AUTORELEASE([Observee new]);
NSArray *test = [NSArray arrayWithObjects: o1, o2, nil];
TestObserver *observer = [TestObserver new];
PASS_EXCEPTION([test addObserver:observer
toObjectsAtIndexes:[NSIndexSet indexSetWithIndex:4]
forKeyPath:@"bareArray"

View file

@ -3,10 +3,15 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
test_alloc_only(@"NSKeyedArchiver");
test_NSObject(@"NSKeyedArchiver",[NSArray arrayWithObject:[[NSKeyedArchiver alloc] initForWritingWithMutableData: [NSMutableData data]]]);
test_NSObject(@"NSKeyedArchiver", [NSArray arrayWithObject:
AUTORELEASE([[NSKeyedArchiver alloc] initForWritingWithMutableData:
[NSMutableData data]])]);
test_alloc_only(@"NSKeyedUnarchiver");
test_NSObject(@"NSKeyedUnarchiver",[NSArray arrayWithObject:[[NSKeyedUnarchiver alloc] initForReadingWithData: [NSKeyedArchiver archivedDataWithRootObject: [NSData data]]]]);
test_NSObject(@"NSKeyedUnarchiver", [NSArray arrayWithObject:
AUTORELEASE([[NSKeyedUnarchiver alloc] initForReadingWithData:
[NSKeyedArchiver archivedDataWithRootObject: [NSData data]]])]);
[arp release]; arp = nil;
return 0;

View file

@ -7,18 +7,20 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id obj;
NSMutableData *data1;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id obj;
NSMutableData *data1;
obj = [NSKeyedArchiver alloc];
data1 = [NSMutableData dataWithLength: 0];
obj = [obj initForWritingWithMutableData: data1];
PASS((obj != nil && [obj isKindOfClass:[NSKeyedArchiver class]]), "-initForWritingWithMutableData seems ok");
obj = AUTORELEASE([[NSKeyedArchiver alloc]
initForWritingWithMutableData: data1]);
PASS((obj != nil && [obj isKindOfClass: [NSKeyedArchiver class]]),
"-initForWritingWithMutableData seems ok")
PASS_EXCEPTION([[NSUnarchiver alloc] initForReadingWithData:nil];,
@"NSInvalidArgumentException",
"Creating an NSUnarchiver with nil data throws an exception");
PASS_EXCEPTION(AUTORELEASE([[NSUnarchiver alloc]
initForReadingWithData: nil]);,
@"NSInvalidArgumentException",
"Creating an NSUnarchiver with nil data throws an exception")
[arp release]; arp = nil;
return 0;

View file

@ -27,8 +27,9 @@ int main()
u = [NSURL URLWithString: @"http://www.w3.org/"];
ms = [NSMutableSet set];
[ms addObject: u];
data2 = [NSMutableData new];
archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data2];
data2 = [NSMutableData data];
archiver = AUTORELEASE([[NSKeyedArchiver alloc]
initForWritingWithMutableData: data2]);
[archiver setOutputFormat: NSPropertyListXMLFormat_v1_0];
[archiver encodeObject: ms forKey: @"root"];
[archiver finishEncoding];
@ -38,28 +39,25 @@ int main()
PASS([[[ms anyObject] absoluteString] isEqual: @"http://www.w3.org/"],
"Can archive and restore a URL");
[archiver release];
[data2 release];
PASS_RUNS(val1 = [NSString stringWithCString:"Archiver.dat"];
val2 = [NSString stringWithCString:"A Goodbye"];
val3 = [NSString stringWithCString:"Testing all strings"];
val4 = [NSNumber numberWithUnsignedInt: 100];
vals1 = [[[NSArray arrayWithObject:val1]
arrayByAddingObject:val2]
arrayByAddingObject: val4];
vals2 = [vals1 arrayByAddingObject: val2];,
"We can build basic strings and arrays for tests");
PASS_RUNS(
val1 = [NSString stringWithCString:"Archiver.dat"];
val2 = [NSString stringWithCString:"A Goodbye"];
val3 = [NSString stringWithCString:"Testing all strings"];
val4 = [NSNumber numberWithUnsignedInt: 100];
vals1 = [[[NSArray arrayWithObject: val1]
arrayByAddingObject: val2]
arrayByAddingObject: val4];
vals2 = [vals1 arrayByAddingObject: val2];,
"We can build basic strings and arrays for tests")
PASS([NSKeyedArchiver archiveRootObject:vals2 toFile:val1],
PASS([NSKeyedArchiver archiveRootObject: vals2 toFile: val1],
"archiveRootObject:toFile: seems ok");
data1 = [NSKeyedArchiver archivedDataWithRootObject:vals2];
data1 = [NSKeyedArchiver archivedDataWithRootObject: vals2];
PASS((data1 != nil && [data1 length] != 0),
"archivedDataWithRootObject: seems ok");
a = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
a = [NSKeyedUnarchiver unarchiveObjectWithData: data1];
NSLog(@"From data: original array %@, decoded array %@",vals2, a);
PASS((a != nil && [a isKindOfClass:[NSArray class]] && [a isEqual:vals2]),
"unarchiveObjectWithData: seems ok");
@ -70,17 +68,18 @@ int main()
"unarchiveObjectWithFile: seems ok");
// encode
data2 = [[NSMutableData alloc] initWithCapacity: 10240];
archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data2];
data2 = [NSMutableData dataWithCapacity: 10240];
archiver = AUTORELEASE([[NSKeyedArchiver alloc]
initForWritingWithMutableData: data2]);
[archiver encodeObject: val3 forKey: @"string"];
[archiver finishEncoding];
// decode...
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData: data2];
s = [[unarchiver decodeObjectForKey: @"string"] retain];
unarchiver = AUTORELEASE([[NSKeyedUnarchiver alloc]
initForReadingWithData: data2]);
s = [unarchiver decodeObjectForKey: @"string"];
PASS((s != nil && [s isKindOfClass:[NSString class]] && [s isEqual: val3]),
"encodeObject:forKey: seems okay");
[data2 release];
NSLog(@"Original string: %@, unarchived string: %@",val3, s);

View file

@ -6,7 +6,7 @@ int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
BOOL ret;
NSLock *lock = [NSRecursiveLock new];
NSLock *lock = AUTORELEASE([NSRecursiveLock new]);
ret = [lock tryLock];
if (ret)

View file

@ -65,18 +65,20 @@ NSMutableArray *received;
int main(void)
{
[NSAutoreleasePool new];
ENTER_POOL
{
Queue *q = [Queue new];
NSMutableArray *sent = [NSMutableArray new];
received = [NSMutableArray new];
unsigned int i;
Queue *q = AUTORELEASE([Queue new]);
NSMutableArray *sent = [NSMutableArray array];
unsigned int i;
received = [NSMutableArray array];
[NSThread detachNewThreadSelector: @selector(consumeFromQueue:)
toTarget: [Consumer new]
withObject: q];
toTarget: [Consumer new]
withObject: q];
for (i = 0; i < 10000; i++)
{
id obj = [NSNumber numberWithUnsignedInt: i];
[sent addObject: obj];
if (i % 10 == 0)
{
@ -91,5 +93,6 @@ int main(void)
[NSThread sleepForTimeInterval: 2.0];
PASS([sent isEqual: received], "Condition lock");
}
LEAVE_POOL
return 0;
}

View file

@ -22,7 +22,7 @@ int main()
helpers = [helpers stringByAppendingPathComponent: @"obj"];
command = [helpers stringByAppendingPathComponent: @"doubleNSLock"];
task = [[NSTask alloc] init];
task = AUTORELEASE([[NSTask alloc] init]);
ePipe = [[NSPipe pipe] retain];
[task setLaunchPath: command];
[task setStandardError: ePipe];
@ -34,8 +34,8 @@ int main()
}
data = [hdl availableData];
NSLog(@"Data was %*.*s", [data length], [data length], [data bytes]);
string = [NSString alloc];
string = [string initWithData: data encoding: NSISOLatin1StringEncoding];
string = AUTORELEASE([[NSString alloc]
initWithData: data encoding: NSISOLatin1StringEncoding]);
PASS([string rangeOfString: @"deadlock"].length > 0,
"NSLock reported deadlock as expected");
if (NO == testPassed)
@ -46,8 +46,8 @@ int main()
[task waitUntilExit];
command = [helpers stringByAppendingPathComponent: @"doubleNSConditionLock"];
task = [[NSTask alloc] init];
ePipe = [[NSPipe pipe] retain];
task = AUTORELEASE([[NSTask alloc] init]);
ePipe = [NSPipe pipe];
[task setLaunchPath: command];
[task setStandardError: ePipe];
hdl = [ePipe fileHandleForReading];
@ -58,8 +58,8 @@ int main()
}
data = [hdl availableData];
NSLog(@"Data was %*.*s", [data length], [data length], [data bytes]);
string = [NSString alloc];
string = [string initWithData: data encoding: NSISOLatin1StringEncoding];
string = AUTORELEASE([[NSString alloc]
initWithData: data encoding: NSISOLatin1StringEncoding]);
PASS([string rangeOfString: @"deadlock"].length > 0,
"NSConditionLock reported deadlock as expected");
if (NO == testPassed)
@ -69,23 +69,23 @@ int main()
}
[task waitUntilExit];
ASSIGN(lock,[NSRecursiveLock new]);
lock = AUTORELEASE([NSRecursiveLock new]);
[lock lock];
[lock lock];
[lock unlock];
[lock unlock];
ASSIGN(lock,[NSLock new]);
lock = AUTORELEASE([NSLock new]);
PASS([lock tryLock] == YES, "NSLock can tryLock");
PASS([lock tryLock] == NO, "NSLock says NO for recursive tryLock");
[lock unlock];
ASSIGN(lock,[NSConditionLock new]);
lock = AUTORELEASE([NSConditionLock new]);
PASS([lock tryLock] == YES, "NSConditionLock can tryLock");
PASS([lock tryLock] == NO, "NSConditionLock says NO for recursive tryLock");
[lock unlock];
ASSIGN(lock,[NSRecursiveLock new]);
lock = AUTORELEASE([NSRecursiveLock new]);
PASS([lock tryLock] == YES, "NSRecursiveLock can tryLock");
PASS([lock tryLock] == YES, "NSRecursiveLock says YES for recursive tryLock");
[lock unlock];

View file

@ -3,24 +3,24 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
BOOL ret;
id lock;
NSAutoreleasePool *arp = [NSAutoreleasePool new];
BOOL ret;
id lock = nil;
lock = [NSLock new];
lock = AUTORELEASE([NSLock new]);
ret = [lock tryLock];
if (ret)
[lock unlock];
PASS(ret, "NSLock with tryLock, then unlocking");
ASSIGN(lock,[NSLock new]);
lock = AUTORELEASE([NSLock new]);
[lock tryLock];
ret = [lock tryLock];
if (ret)
[lock unlock];
PASS(ret == NO, "Recursive try lock with NSLock should return NO");
ASSIGN(lock,[NSConditionLock new]);
lock = AUTORELEASE([NSConditionLock new]);
[lock lock];
ret = [lock tryLock];
if (ret)
@ -38,34 +38,34 @@ int main()
[lock unlock];
PASS(ret == NO, "Recursive tryLockWhenCondition: with NSConditionLock (2) should return NO");
ASSIGN(lock,[NSRecursiveLock new]);
lock = AUTORELEASE([NSRecursiveLock new]);
[lock tryLock];
ret = [lock tryLock];
if (ret)
[lock unlock];
PASS(ret == YES, "Recursive try lock with NSRecursiveLock should return YES");
ASSIGN(lock,[NSLock new]);
lock = AUTORELEASE([NSLock new]);
ret = [lock lockBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 1]];
if (ret)
[lock unlock];
PASS(ret, "NSLock lockBeforeDate: works");
ASSIGN(lock,[NSLock new]);
lock = AUTORELEASE([NSLock new]);
[lock tryLock];
ret = [lock lockBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 1]];
if (ret)
[lock unlock];
PASS(ret == NO, "Recursive lockBeforeDate: with NSLock returns NO");
ASSIGN(lock,[NSConditionLock new]);
lock = AUTORELEASE([NSConditionLock new]);
[lock tryLock];
ret = [lock lockBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 1]];
if (ret)
[lock unlock];
PASS(ret == NO, "Recursive lockBeforeDate: with NSConditionLock returns NO");
ASSIGN(lock,[NSRecursiveLock new]);
lock = AUTORELEASE([NSRecursiveLock new]);
[lock tryLock];
ret = [lock lockBeforeDate: [NSDate dateWithTimeIntervalSinceNow: 1]];
if (ret)

View file

@ -6,7 +6,7 @@ int main()
{
START_SET("Unbalanced unlocking")
NSLock *lock = [NSLock new];
NSLock *lock = AUTORELEASE([NSLock new]);
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
BOOL mode = [defs boolForKey: @"GSMacOSXCompatible"];

View file

@ -198,7 +198,7 @@ typedef struct _MySmallStruct MySmallStruct;
void
test_compare_server_signature(void)
{
id objct = [MyClass new];
id objct = AUTORELEASE([MyClass new]);
id proxy = [NSConnection rootProxyForConnectionWithRegisteredName: SRV_NAME
host: nil];
if (proxy)

View file

@ -3,9 +3,10 @@
#import "ObjectTesting.h"
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSArray *arr = [NSArray arrayWithObject:[NSMutableAttributedString new]];
ENTER_POOL
NSArray *arr;
arr = [NSArray arrayWithObject: AUTORELEASE([NSMutableAttributedString new])];
test_alloc(@"NSMutableAttributedString");
test_NSObject(@"NSMutableAttributedString", arr);
test_NSCoding(arr);
@ -13,7 +14,7 @@ int main()
test_NSCopying(@"NSAttributedString",@"NSMutableAttributedString",arr,NO, NO);
test_NSMutableCopying(@"NSAttributedString",@"NSMutableAttributedString",arr);
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -63,12 +63,13 @@ NSString *NSForegroundColorAttributeName = @"NSForegroundColorAttributeName";
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
ENTER_POOL
NSMutableAttributedString *attrStr;
NSString *baseString = @"0123456789";
NSDictionary *red, *gray, *blue;
NSMutableAttributedString *s;
s = [[[NSMutableAttributedString alloc]
initWithString: @"string"] autorelease];
[s _sanity];
@ -97,8 +98,8 @@ int main()
gray = [NSDictionary dictionaryWithObject:@"Gray" forKey:@"Color"];
blue = [NSDictionary dictionaryWithObject:@"Blue" forKey:@"Color"];
attrStr = [[NSMutableAttributedString alloc] initWithString:baseString
attributes:red];
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
PASS([[attrStr string] isEqual:baseString] &&
[attrStr checkAttributes:red range:NSMakeRange(0,10)],
@ -109,8 +110,8 @@ int main()
PASS([attrStr checkAttributes:blue range:NSMakeRange(0,10)],
"-setAttributes:range: works for the whole string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(0,5)];
[attrStr _sanity];
@ -118,8 +119,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works for the first half of the string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(3,5)];
[attrStr _sanity];
@ -135,8 +136,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(8,2)],
"-setAttributes:range: works for same attributes in middle of string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(5,5)];
[attrStr _sanity];
@ -144,8 +145,8 @@ int main()
[attrStr checkAttributes:blue range:NSMakeRange(5,5)],
"-setAttributes:range: works for the last half of the string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(0,3)];
[attrStr _sanity];
@ -158,8 +159,8 @@ int main()
[attrStr checkAttributes:gray range:NSMakeRange(7,3)],
"-setAttributes:range: works in three parts of the string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(0,5)];
[attrStr _sanity];
@ -173,8 +174,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(9,1)],
"-setAttributes:range: works with overlapping");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr= AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(1,2)];
[attrStr _sanity];
@ -191,8 +192,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(9,1)],
"-setAttributes:range: works with overlapping (2)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(2,5)];
[attrStr _sanity];
@ -203,8 +204,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(7,3)],
"-setAttributes:range: works with replacing");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(1,8)];
[attrStr _sanity];
@ -221,8 +222,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(9,1)],
"-setAttributes:range: works with chinese boxes");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(1,3)];
[attrStr _sanity];
@ -233,8 +234,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works with extending at the end (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:gray range:NSMakeRange(1,3)];
[attrStr _sanity];
@ -245,8 +246,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works with extending at the end (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(2,3)];
[attrStr _sanity];
@ -257,8 +258,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works with extending at the beginning (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:gray range:NSMakeRange(2,3)];
[attrStr _sanity];
@ -270,8 +271,8 @@ int main()
"-setAttributes:range: works with extending at the beginning (same color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(1,3)];
[attrStr _sanity];
@ -283,8 +284,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(4,6)],
"-setAttributes:range: works with subset at the end (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:gray range:NSMakeRange(1,3)];
[attrStr _sanity];
@ -295,8 +296,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(4,6)],
"-setAttributes:range: works with subset at the end (same color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(2,3)];
[attrStr _sanity];
@ -308,8 +309,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works with subset at the beginning (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:gray range:NSMakeRange(2,3)];
[attrStr _sanity];
@ -320,8 +321,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(5,5)],
"-setAttributes:range: works with subset at the beginning (same color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:gray range:NSMakeRange(2,1)];
[attrStr _sanity];
@ -334,8 +335,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(6,4)],
"-setAttributes:range: works with subsets (diff color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(2,1)];
[attrStr _sanity];
@ -348,8 +349,8 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(6,4)],
"-setAttributes:range: works with subsets (same color)");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(2,1)];
[attrStr _sanity];
@ -364,8 +365,8 @@ int main()
PASS([attrStr checkAttributes:gray range:NSMakeRange(0,10)],
"-setAttributes:range: works with setting attributes for the whole string");
ASSIGN(attrStr,[[NSMutableAttributedString alloc] initWithString:baseString
attributes:red]);
attrStr = AUTORELEASE([[NSMutableAttributedString alloc]
initWithString: baseString attributes: red]);
[attrStr _sanity];
[attrStr setAttributes:blue range:NSMakeRange(0,1)];
[attrStr _sanity];
@ -377,7 +378,7 @@ int main()
[attrStr checkAttributes:red range:NSMakeRange(3,7)],
"-setAttributes:range: works with nearby attributes");
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -44,6 +44,18 @@
}
@end
@interface NSMutableAttributedString (autoreleased)
+ (NSMutableAttributedString*) stringWithString: (NSString*)s
attributes: (NSDictionary*)a;
@end
@implementation NSMutableAttributedString (autoreleased)
+ (NSMutableAttributedString*) stringWithString: (NSString*)s
attributes: (NSDictionary*)a
{
return AUTORELEASE([[self alloc] initWithString: s attributes: a]);
}
@end
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
@ -55,25 +67,25 @@ int main()
[[[NSMutableAttributedString new] autorelease] _sanity];
as = [[NSMutableAttributedString alloc] initWithString:base1 attributes:nil];
as = [NSMutableAttributedString stringWithString:base1 attributes:nil];
[as replaceCharactersInRange:NSMakeRange(2,2) withString:@""];
[as _sanity];
PASS([[as string] isEqual:@"ba-1"],
"-replaceCharactersInRange: withString: works with zero length string");
as = [[NSMutableAttributedString alloc] initWithString:base1 attributes:nil];
as = [NSMutableAttributedString stringWithString:base1 attributes:nil];
[as replaceCharactersInRange:NSMakeRange(2,2) withString:base2];
[as _sanity];
PASS([[as string] isEqual:@"babase-2-1"],
"-replaceCharactersInRange:withString: works in middle of string");
as = [[NSMutableAttributedString alloc] initWithString:base1 attributes:nil];
as = [NSMutableAttributedString stringWithString:base1 attributes:nil];
[as replaceCharactersInRange:NSMakeRange(6,0) withString:base2];
[as _sanity];
PASS([[as string] isEqual:@"base-1base-2"],
"-replaceCharactersInRange:withString: works at end of string works");
as = [[NSMutableAttributedString alloc] initWithString:base1 attributes:nil];
as = [NSMutableAttributedString stringWithString:base1 attributes:nil];
[as replaceCharactersInRange:NSMakeRange(0,0) withString:base2];
[as _sanity];
PASS([[as string] isEqual:@"base-2base-1"],
@ -82,7 +94,7 @@ int main()
attrE = [NSDictionary dictionary];
attr1 = [NSDictionary dictionaryWithObject:@"a" forKey:@"1"];
attr2 = [NSDictionary dictionaryWithObject:@"b" forKey:@"2"];
as = [[NSMutableAttributedString alloc] initWithString:base1
as = [NSMutableAttributedString stringWithString:base1
attributes:attr1];
[as setAttributes:attr2 range:NSMakeRange(2,4)];
[as replaceCharactersInRange:NSMakeRange(0,6) withString:@""];
@ -92,7 +104,7 @@ int main()
PASS([as checkAttributes:attrE range:NSMakeRange(0,4)],
"-replaceCharactersInRange:withString: keeps attributes if entire string is replaced");
as = [[NSMutableAttributedString alloc] initWithString:base1
as = [NSMutableAttributedString stringWithString:base1
attributes:attr1];
[as replaceCharactersInRange:NSMakeRange(0,6) withString:base2];
[as _sanity];
@ -107,7 +119,7 @@ int main()
BOOL removeAll,replaceAll;
NSDictionary *aBegin,*aEnd;
as = [[NSMutableAttributedString alloc] initWithString:@"aabbccdd"
as = [NSMutableAttributedString stringWithString:@"aabbccdd"
attributes:attr2];
removeAll = (start == 0 && length == 8);
[as setAttributes:attr1 range:NSMakeRange(2,2)];
@ -134,7 +146,7 @@ int main()
"attribute/(replaceCharacters... with zero length string) interaction _sanity checks %i %i",start, length);
}
as = [[NSMutableAttributedString alloc] initWithString:@"aabbccdd"
as = [NSMutableAttributedString stringWithString:@"aabbccdd"
attributes:attr2];
replaceAll = (start == 0 && length == 8);
[as setAttributes:attr1 range:NSMakeRange(2,2)];

View file

@ -5,7 +5,8 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObj = [NSMutableCharacterSet new];
id testObj = AUTORELEASE([NSMutableCharacterSet new]);
test_alloc(@"NSMutableCharacterSet");
test_NSObject(@"NSMutableCharacterSet",[NSArray arrayWithObject:testObj]);
test_NSCoding([NSArray arrayWithObject:testObj]);

View file

@ -5,7 +5,8 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
id testObject = [NSMutableData new];
id testObject = [NSMutableData data];
test_alloc(@"NSMutableData");
test_NSObject(@"NSData",[NSArray arrayWithObject:testObject]);
test_NSCoding([NSArray arrayWithObject:testObject]);

View file

@ -6,52 +6,52 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
char *str1,*str2,*tmp;
NSData *data1;
ENTER_POOL
char *str1, *str2, *tmp;
NSData *data1;
NSMutableData *mutable;
unsigned char *hold;
str1 = "Test string for data classes";
str2 = (char *) malloc(sizeof("insert"));
strcpy(str2,"insert");
str2 = (char *)malloc(sizeof("insert"));
strcpy(str2, "insert");
mutable = [NSMutableData dataWithLength:100];
mutable = [NSMutableData dataWithLength: 100];
hold = [mutable mutableBytes];
/* hmpf is this correct */
data1 = [NSData dataWithBytes:str1 length:(strlen(str1) * sizeof(void*))];
PASS(data1 != nil &&
[data1 isKindOfClass:[NSData class]] &&
[data1 length] == (strlen(str1) * sizeof(void*)) &&
[data1 bytes] != str1 &&
strcmp(str1,[data1 bytes]) == 0,
"+dataWithBytes:length: works");
data1 = [NSData dataWithBytes: str1 length: (strlen(str1) + 1)];
PASS(data1 != nil
&& [data1 isKindOfClass: [NSData class]]
&& [data1 length] == (strlen(str1) + 1)
&& [data1 bytes] != str1
&& strcmp(str1, [data1 bytes]) == 0,
"+dataWithBytes:length: works")
mutable = [NSMutableData data];
PASS(mutable != nil &&
[mutable isKindOfClass:[NSMutableData class]] &&
[mutable length] == 0,
"+data creates empty mutable data");
PASS(mutable != nil
&& [mutable isKindOfClass: [NSMutableData class]]
&& [mutable length] == 0,
"+data creates empty mutable data")
[mutable setData:data1];
PASS(mutable != nil &&
[mutable length] == (strlen(str1) * sizeof(void*)),
"-setData: works");
[mutable setData: data1];
PASS(mutable != nil
&& [mutable length] == (strlen(str1) + 1),
"-setData: works")
[mutable replaceBytesInRange:NSMakeRange(22,6) withBytes:str2];
[mutable replaceBytesInRange: NSMakeRange(22, 6) withBytes: str2];
tmp = (char *)malloc([mutable length]);
[mutable getBytes:tmp range:NSMakeRange(22,6)];
[mutable getBytes: tmp range: NSMakeRange(22, 6)];
tmp[6] = '\0';
PASS(mutable != nil &&
strcmp(tmp,str2) == 0,
"-replaceBytesInRange:withBytes suceeds");
PASS(mutable != nil
&& strcmp(tmp, str2) == 0,
"-replaceBytesInRange:withBytes suceeds")
free(tmp);
PASS_EXCEPTION([mutable replaceBytesInRange:NSMakeRange([mutable length]+1,6)
withBytes:str2];,
NSRangeException,"-replaceBytesInRange:withBytes out of range raises exception");
PASS_EXCEPTION([mutable
replaceBytesInRange: NSMakeRange([mutable length]+1, 6) withBytes: str2];,
NSRangeException,
"-replaceBytesInRange:withBytes out of range raises exception")
[arp release]; arp = nil;
free(str2);
LEAVE_POOL
return 0;
}

View file

@ -7,7 +7,7 @@ int main()
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableDictionary *testObj;
testObj = [NSMutableDictionary new];
testObj = [NSMutableDictionary dictionary];
test_NSObject(@"NSMutableDictionary", [NSArray arrayWithObject:testObj]);

View file

@ -8,7 +8,7 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
ENTER_POOL
NSString *key1, *key2, *key3, *val1, *val2, *val3;
NSArray *keys1, *keys2, *keys3, *vals1, *vals2, *vals3;
id obj;
@ -28,7 +28,7 @@ int main()
vals3 = [NSArray arrayWithObjects:val1,val2,val3,nil];
dict = [NSMutableDictionary new];
dict = [NSMutableDictionary dictionary];
PASS(dict != nil &&
[dict isKindOfClass:[NSMutableDictionary class]]
&& [dict count] == 0,
@ -207,7 +207,7 @@ int main()
[obj isEqual:dict],
"-description gives us a text property-list");
dict = [NSMutableDictionary new];
dict = [NSMutableDictionary dictionary];
[dict setObject:@"hello" forKey:@"world"];
PASS(dict != nil &&
[dict isKindOfClass:[NSMutableDictionary class]] &&
@ -218,6 +218,6 @@ int main()
PASS([[dict valueForKey:@"Lücke"] isEqualToString:@"hello"],
"unicode keys work with setValue:forKey:");
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -3,8 +3,8 @@
#include <Testing.h>
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableIndexSet *set = [[NSMutableIndexSet alloc] init];
ENTER_POOL
NSMutableIndexSet *set = AUTORELEASE([NSMutableIndexSet new]);
[set addIndex:1];
[set addIndex:2];
@ -22,6 +22,6 @@ int main()
PASS([set containsIndexesInRange:NSMakeRange(0,2)], "contains range");
[pool release];
LEAVE_POOL
return 0;
}

View file

@ -31,7 +31,7 @@
length: l
encoding: encoding
freeWhenDone: freeWhenDone];
if (s == nil) return nil;
if (s == nil) {RELEASE(self); return nil;}
l = [s length] * sizeof(unichar);
characters = malloc(l);
[s getCharacters: characters];
@ -66,22 +66,22 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
ENTER_POOL
unichar u0 = 'a';
unichar u1 = 0xfe66;
NSMutableString *testObj,*base,*ext,*want, *str1, *str2;
unichar chars[3];
test_alloc(@"NSMutableString");
testObj = [[NSMutableString alloc] initWithCString:"Hello\n"];
test_NSCoding([NSArray arrayWithObject:testObj]);
test_keyed_NSCoding([NSArray arrayWithObject:testObj]);
testObj = AUTORELEASE([[NSMutableString alloc] initWithCString:"Hello\n"]);
test_NSCoding([NSArray arrayWithObject: testObj]);
test_keyed_NSCoding([NSArray arrayWithObject: testObj]);
test_NSCopying(@"NSString",@"NSMutableString",
[NSArray arrayWithObject:testObj],NO,NO);
[NSArray arrayWithObject: testObj],NO,NO);
test_NSMutableCopying(@"NSString",@"NSMutableString",
[NSArray arrayWithObject:testObj]);
[NSArray arrayWithObject: testObj]);
base = [[NSMutableString alloc] initWithCString:"hello"];
base = [NSMutableString stringWithCString:"hello"];
ext = [@"\"\\UFE66???\"" propertyList];
want = [@"\"hello\\UFE66???\"" propertyList];
[base appendString:ext];
@ -89,11 +89,11 @@ int main()
&& [want length] == 9 && [base isEqual:want],
"We can append a unicode string to a C string");
PASS([[[NSMutableString alloc] initWithCharacters: &u0 length: 1]
PASS([AUTORELEASE([[NSMutableString alloc] initWithCharacters: &u0 length: 1])
isKindOfClass: [NSMutableString class]],
"initWithCharacters:length: creates mutable string for ascii");
PASS([[[NSMutableString alloc] initWithCharacters: &u1 length: 1]
PASS([AUTORELEASE([[NSMutableString alloc] initWithCharacters: &u1 length: 1])
isKindOfClass: [NSMutableString class]],
"initWithCharacters:length: creates mutable string for unicode");
@ -101,7 +101,7 @@ int main()
appendString: @"bar"];,
"can append to string from NSMutableString +stringWithString:");
testObj = [@"hello" mutableCopy];
testObj = AUTORELEASE([@"hello" mutableCopy]);
[testObj replaceCharactersInRange: NSMakeRange(1,1) withString: @"a"];
PASS([testObj isEqual: @"hallo"],
"replaceCharactersInRange:withString: works in middle of string");
@ -179,7 +179,6 @@ int main()
PASS_EQUAL(str, @"Text Message", "remove combining-tilde")
}
[testObj release];
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -22,10 +22,9 @@
int main()
{
NSNotification *obj;
NSMutableArray *testObjs = [[NSMutableArray alloc] init];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
ENTER_POOL
NSNotification *obj;
NSMutableArray *testObjs = [NSMutableArray array];
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
@"obj", @"key", nil];
NSNotification *o1 = [NSNotification notificationWithName: @"hello"
@ -34,18 +33,19 @@ int main()
NSNotification *o2 = [NSNotification notificationWithName: @"hello"
object: @"there"
userInfo: info];
PASS([o1 hash] == [o2 hash], "equal notification hashes")
PASS_EQUAL(o1, o2, "equal notifications")
test_alloc(@"NSNotification");
obj = [NSNotification new];
obj = AUTORELEASE([NSNotification new]);
[testObjs addObject: obj];
test_NSObject(@"NSNotification", testObjs);
test_NSCoding(testObjs);
test_keyed_NSCoding(testObjs);
test_NSCopying(@"NSNotification",@"NSNotification",testObjs,NO,NO);
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -20,18 +20,18 @@ static BOOL notifiedCurrent = NO;
int main(void)
{
ENTER_POOL
NSNotificationCenter *nc;
id t = [Toggle new];
id t = AUTORELEASE([Toggle new]);
[NSAutoreleasePool new];
nc = [NSNotificationCenter new];
nc = AUTORELEASE([NSNotificationCenter new]);
[nc addObserver: t selector: @selector(foo:) name: nil object: nil];
class_replaceMethod([Toggle class],
@selector(foo:),
class_getMethodImplementation([Toggle class], @selector(bar:)),
"v@:@");
[nc postNotificationName: @"foo" object: t];
[t release];
PASS(YES == notifiedCurrent, "implementation not cached");
LEAVE_POOL
return 0;
}

View file

@ -132,9 +132,9 @@ int main()
PASS(200 == [val1 unsignedShortValue],
"NSDecimalNumber unsignedShortValue works")
val1 = [[NSNumber alloc] initWithLongLong: LLONG_MIN];
val2 = [[NSNumber alloc] initWithUnsignedLongLong:
(unsigned long long)LLONG_MAX + 1];
val1 = AUTORELEASE([[NSNumber alloc] initWithLongLong: LLONG_MIN]);
val2 = AUTORELEASE([[NSNumber alloc] initWithUnsignedLongLong:
(unsigned long long)LLONG_MAX + 1]);
PASS([val1 compare: val2] == NSOrderedAscending,
"comparison of min signed with max unsigned works")

View file

@ -13,7 +13,7 @@ int main()
[NSNumberFormatter
setDefaultFormatterBehavior: NSNumberFormatterBehavior10_0];
TEST_FOR_CLASS(@"NSNumberFormatter",[NSNumberFormatter alloc],
TEST_FOR_CLASS(@"NSNumberFormatter", AUTORELEASE([NSNumberFormatter alloc]),
"+[NSNumberFormatter alloc] returns a NSNumberFormatter");
fmt = [[[NSNumberFormatter alloc] init] autorelease];

View file

@ -160,7 +160,7 @@ mutualinit(int sig)
*/
testHopeful = YES;
PASS(0, "+initialize mutually dependent methods work");
exit(0);
_exit(0); // Use _exit() to avoid deadlocking in atexit()
}
static void
@ -170,7 +170,7 @@ concurrency(int sig)
*/
testHopeful = YES;
PASS(0, "+initialize runs concurrently");
exit(0);
_exit(0); // Use _exit() to avoid deadlocking in atexit()
}
/**

View file

@ -48,7 +48,7 @@ int main()
![[[NSArray new] autorelease] isClass]),
"-isClass returns NO on an instance");
evilObject = [MyEvilClass new];
evilObject = AUTORELEASE([MyEvilClass new]);
[evilObject setInfo:1];
PASS(![evilObject isClass],
"-isClass returns NO on an instance (special test for broken libobjc)");

View file

@ -36,20 +36,22 @@
int main()
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
ENTER_POOL
id instance = AUTORELEASE([NicolaTest new]);
PASS([NicolaTest conformsToProtocol:@protocol(DoingNothing)],
"+conformsToProtocol returns YES on an implemented protocol");
PASS([NicolaTest conformsToProtocol:@protocol(DoingNothingCategory)],
"+conformsToProtocol returns YES on a protocol implemented in a category");
PASS(![NicolaTest conformsToProtocol:@protocol(NSCoding)],
"+conformsToProtocol returns NO on an unimplemented protocol");
PASS([[NicolaTest new] conformsToProtocol:@protocol(DoingNothing)],
PASS([instance conformsToProtocol:@protocol(DoingNothing)],
"-conformsToProtocol returns YES on an implemented protocol");
PASS([[NicolaTest new] conformsToProtocol:@protocol(DoingNothingCategory)],
PASS([instance conformsToProtocol:@protocol(DoingNothingCategory)],
"-conformsToProtocol returns YES on a protocol implemented in a category");
PASS(![[NicolaTest new] conformsToProtocol:@protocol(NSCoding)],
PASS(![instance conformsToProtocol:@protocol(NSCoding)],
"-conformsToProtocol returns NO on an unimplemented protocol");
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -12,13 +12,13 @@ static BOOL blockDidRun = NO;
int main()
{
ENTER_POOL
id obj1;
id obj2;
NSMutableArray *testObjs = [[NSMutableArray alloc] init];
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSMutableArray *testObjs = [NSMutableArray array];
test_alloc(@"NSOperation");
obj1 = [NSOperation new];
obj1 = AUTORELEASE([NSOperation new]);
PASS((obj1 != nil), "can create an operation");
[testObjs addObject: obj1];
test_NSObject(@"NSOperation", testObjs);
@ -36,7 +36,7 @@ int main()
PASS(([obj1 queuePriority] == NSOperationQueuePriorityVeryHigh),
"operation has very high priority");
obj2 = [NSOperation new];
obj2 = AUTORELEASE([NSOperation new]);
[obj2 addDependency: obj1];
PASS(([[obj2 dependencies] isEqual: testObjs]),
"operation has added dependency");
@ -53,8 +53,7 @@ int main()
"dependency removal works");
PASS(([obj2 isReady] == YES), "operation without dependency is ready");
[obj1 release];
obj1 = [NSOperation new];
obj1 = AUTORELEASE([NSOperation new]);
[testObjs replaceObjectAtIndex: 0 withObject: obj1];
[obj2 addDependency: obj1];
# if __has_feature(blocks)
@ -72,8 +71,7 @@ int main()
PASS(([obj2 isReady] == YES), "operation with finished dependency is ready");
[obj2 removeDependency: obj1];
[obj1 release];
obj1 = [NSOperation new];
obj1 = AUTORELEASE([NSOperation new]);
[testObjs replaceObjectAtIndex: 0 withObject: obj1];
[obj2 addDependency: obj1];
[obj2 cancel];
@ -92,7 +90,7 @@ int main()
test_alloc(@"NSOperationQueue");
obj1 = [NSOperationQueue new];
obj1 = AUTORELEASE([NSOperationQueue new]);
PASS((obj1 != nil), "can create an operation queue");
[testObjs removeAllObjects];
[testObjs addObject: obj1];
@ -121,11 +119,11 @@ int main()
NSInvalidArgumentException,
"NSOperationQueue cannot be given negative count");
obj2 = [NSOperation new];
obj2 = AUTORELEASE([NSOperation new]);
[obj1 addOperation: obj2];
[NSThread sleepForTimeInterval: 1.0];
PASS(([obj2 isFinished] == YES), "queue ran operation");
[arp release]; arp = nil;
LEAVE_POOL
return 0;
}

View file

@ -120,7 +120,7 @@ int main()
NSOrderedSet *testObj, *testObj2;
NSMutableOrderedSet *mutableTest1, *mutableTest2;
NSMutableArray *testObjs = [NSMutableArray new];
NSMutableArray *testObjs = [NSMutableArray array];
NSData *data = [stringData dataUsingEncoding: NSUTF8StringEncoding];
NSMutableSet *testSet;

Some files were not shown because too many files have changed in this diff Show more