ObjFW  Check-in [d8c31454b4]

Overview
Comment:More style improvements.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA3-256: d8c31454b494f8dabde65fd04d227ec16c7f390e569f6387a1af07b3093c1b77
User & Date: js on 2011-04-23 00:11:41
Other Links: manifest | tags
Context
2011-04-23
01:32
Fix too big buffer in -[OFMutableString _applyTable:withSize:]. check-in: a85a9b6076 user: js tags: trunk
00:11
More style improvements. check-in: d8c31454b4 user: js tags: trunk
2011-04-22
22:46
More style improvements. check-in: c9c78d86d3 user: js tags: trunk
Changes

Modified src/OFXMLElementBuilder.h from [bdb22714af] to [922beec8cc].

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 * parsing started, this will return the complete document as an OFXMLElement
 * with all children.
 *
 * \param builder The builder which built an OFXMLElement
 * \param elem The OFXMLElement the OFXMLElementBuilder built
 */
- (void)elementBuilder: (OFXMLElementBuilder*)builder
       didBuildElement: (OFXMLElement*)elem;

#ifdef OF_HAVE_OPTIONAL_PROTOCOLS
@optional
#endif
/**
 * This callback is called when the OFXMLElementBuilder gets a close tag which
 * does not belong there.







|







36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 * parsing started, this will return the complete document as an OFXMLElement
 * with all children.
 *
 * \param builder The builder which built an OFXMLElement
 * \param elem The OFXMLElement the OFXMLElementBuilder built
 */
- (void)elementBuilder: (OFXMLElementBuilder*)builder
       didBuildElement: (OFXMLElement*)element;

#ifdef OF_HAVE_OPTIONAL_PROTOCOLS
@optional
#endif
/**
 * This callback is called when the OFXMLElementBuilder gets a close tag which
 * does not belong there.

Modified src/OFXMLElementBuilder.m from [23f4713294] to [415f6ac93d].

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
	delegate = delegate_;
}

-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attrs
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *elem;
	OFXMLAttribute **attrs_c;
	size_t i, attrs_cnt;
	IMP add_attr;

	elem = [OFXMLElement elementWithName: name
				   namespace: ns];

	attrs_c = [attrs cArray];
	attrs_cnt = [attrs count];
	add_attr = [elem methodForSelector: @selector(addAttribute:)];

	for (i = 0; i < attrs_cnt; i++) {
		if ([attrs_c[i] namespace] == nil &&
		    [[attrs_c[i] name] isEqual: @"xmlns"])
			continue;

		if ([[attrs_c[i] namespace]
		    isEqual: @"http://www.w3.org/2000/xmlns/"])
			[elem setPrefix: [attrs_c[i] name]
			   forNamespace: [attrs_c[i] stringValue]];

		add_attr(elem, @selector(addAttribute:), attrs_c[i]);
	}

	[[stack lastObject] addChild: elem];
	[stack addObject: elem];

	[pool release];
}

-  (void)parser: (OFXMLParser*)parser
  didEndElement: (OFString*)name
     withPrefix: (OFString*)prefix







|


|
|
|
|

|
|

|
|
|

|
|
|


|

|
|

|


|
|







66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
	delegate = delegate_;
}

-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attributes
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *element;
	OFXMLAttribute **cArray;
	size_t i, count;
	IMP addAttribute;

	element = [OFXMLElement elementWithName: name
				      namespace: ns];

	cArray = [attributes cArray];
	count = [attributes count];
	addAttribute = [element methodForSelector: @selector(addAttribute:)];

	for (i = 0; i < count; i++) {
		if ([cArray[i] namespace] == nil &&
		    [[cArray[i] name] isEqual: @"xmlns"])
			continue;

		if ([[cArray[i] namespace]
		    isEqual: @"http://www.w3.org/2000/xmlns/"])
			[element setPrefix: [cArray[i] name]
			      forNamespace: [cArray[i] stringValue]];

		addAttribute(element, @selector(addAttribute:), cArray[i]);
	}

	[[stack lastObject] addChild: element];
	[stack addObject: element];

	[pool release];
}

-  (void)parser: (OFXMLParser*)parser
  didEndElement: (OFString*)name
     withPrefix: (OFString*)prefix
121
122
123
124
125
126
127
128
129
130

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
		[delegate elementBuilder: self
			 didBuildElement: [stack firstObject]];

	[stack removeNObjects: 1];
}

-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)str
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];

	OFXMLElement *elem = [OFXMLElement elementWithCharacters: str];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: elem];
	else
		[[stack lastObject] addChild: elem];

	[pool release];
}

- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)cdata
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *elem = [OFXMLElement elementWithCDATA: cdata];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: elem];
	else
		[[stack lastObject] addChild: elem];

	[pool release];
}

- (void)parser: (OFXMLParser*)parser
  foundComment: (OFString*)comment
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *elem = [OFXMLElement elementWithComment: comment];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: elem];
	else
		[[stack lastObject] addChild: elem];

	[pool release];
}
@end

@implementation OFObject (OFXMLElementBuilderDelegate)
- (void)elementBuilder: (OFXMLElementBuilder*)builder







|


>
|



|

|





|


|



|

|








|



|

|







121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
		[delegate elementBuilder: self
			 didBuildElement: [stack firstObject]];

	[stack removeNObjects: 1];
}

-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)characters
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *element =
	    [OFXMLElement elementWithCharacters: characters];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: element];
	else
		[[stack lastObject] addChild: element];

	[pool release];
}

- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)CDATA
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *element = [OFXMLElement elementWithCDATA: CDATA];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: element];
	else
		[[stack lastObject] addChild: element];

	[pool release];
}

- (void)parser: (OFXMLParser*)parser
  foundComment: (OFString*)comment
{
	OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
	OFXMLElement *element = [OFXMLElement elementWithComment: comment];

	if ([stack count] == 0)
		[delegate elementBuilder: self
			 didBuildElement: element];
	else
		[[stack lastObject] addChild: element];

	[pool release];
}
@end

@implementation OFObject (OFXMLElementBuilderDelegate)
- (void)elementBuilder: (OFXMLElementBuilder*)builder

Modified src/OFXMLParser.h from [0a269ecfb6] to [542d58ae0a].

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@class OFMutableArray;
@class OFStream;

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
typedef void (^of_xml_parser_processing_instructions_block_t)(
    OFXMLParser *parser, OFString *pi);
typedef void (^of_xml_parser_element_start_block_t)(OFXMLParser *parser,
    OFString *name, OFString *prefix, OFString *ns, OFArray *attrs);
typedef void (^of_xml_parser_element_end_block_t)(OFXMLParser *parser,
    OFString *name, OFString *prefix, OFString *ns);
typedef void (^of_xml_parser_string_block_t)(OFXMLParser *parser,
    OFString *string);
typedef OFString* (^of_xml_parser_unknown_entity_block_t)(OFXMLParser *parser,
    OFString *entity);
#endif







|







23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@class OFMutableArray;
@class OFStream;

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
typedef void (^of_xml_parser_processing_instructions_block_t)(
    OFXMLParser *parser, OFString *pi);
typedef void (^of_xml_parser_element_start_block_t)(OFXMLParser *parser,
    OFString *name, OFString *prefix, OFString *ns, OFArray *attributes);
typedef void (^of_xml_parser_element_end_block_t)(OFXMLParser *parser,
    OFString *name, OFString *prefix, OFString *ns);
typedef void (^of_xml_parser_string_block_t)(OFXMLParser *parser,
    OFString *string);
typedef OFString* (^of_xml_parser_unknown_entity_block_t)(OFXMLParser *parser,
    OFString *entity);
#endif
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73
74
75
76
77
78
79
/**
 * This callback is called when the XML parser found the start of a new tag.
 *
 * \param parser The parser which found a new tag
 * \param name The name of the tag which just started
 * \param prefix The prefix of the tag which just started or nil
 * \param ns The namespace of the tag which just started or nil
 * \param attrs The attributes included in the tag which just started or nil

 */
-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attrs;

/**
 * This callback is called when the XML parser found the end of a tag.
 *
 * \param parser The parser which found the end of a tag
 * \param name The name of the tag which just ended
 * \param prefix The prefix of the tag which just ended or nil







|
>





|







59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
 * This callback is called when the XML parser found the start of a new tag.
 *
 * \param parser The parser which found a new tag
 * \param name The name of the tag which just started
 * \param prefix The prefix of the tag which just started or nil
 * \param ns The namespace of the tag which just started or nil
 * \param attributes The attributes included in the tag which just started or
 *		     nil
 */
-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attributes;

/**
 * This callback is called when the XML parser found the end of a tag.
 *
 * \param parser The parser which found the end of a tag
 * \param name The name of the tag which just ended
 * \param prefix The prefix of the tag which just ended or nil
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/**
 * This callback is called when the XML parser found characters.
 *
 * In case there are comments or CDATA, it is possible that this callback is
 * called multiple times in a row.
 *
 * \param parser The parser which found a string
 * \param string The string the XML parser found
 */
-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)string;

/**
 * This callback is called when the XML parser found CDATA.
 *
 * \param parser The parser which found a string
 * \param cdata The CDATA the XML parser found
 */
- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)cdata;

/**
 * This callback is called when the XML parser found a comment.
 *
 * \param parser The parser which found a comment
 * \param comment The comment the XML parser found
 */







|


|





|


|







88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/**
 * This callback is called when the XML parser found characters.
 *
 * In case there are comments or CDATA, it is possible that this callback is
 * called multiple times in a row.
 *
 * \param parser The parser which found a string
 * \param characters The characters the XML parser found
 */
-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)characters;

/**
 * This callback is called when the XML parser found CDATA.
 *
 * \param parser The parser which found a string
 * \param CDATA The CDATA the XML parser found
 */
- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)CDATA;

/**
 * This callback is called when the XML parser found a comment.
 *
 * \param parser The parser which found a comment
 * \param comment The comment the XML parser found
 */
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
		OF_XMLPARSER_IN_DOCTYPE,
		OF_XMLPARSER_NUM_STATES
	} state;
	OFMutableString *cache;
	OFString *name;
	OFString *prefix;
	OFMutableArray *namespaces;
	OFMutableArray *attrs;
	OFString *attrName;
	OFString *attrPrefix;
	char delim;
	OFMutableArray *previous;
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	of_xml_parser_processing_instructions_block_t
	    processingInstructionsHandler;
	of_xml_parser_element_start_block_t elementStartHandler;
	of_xml_parser_element_end_block_t elementEndHandler;
	of_xml_parser_string_block_t charactersHandler;







|
|
|
|







160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
		OF_XMLPARSER_IN_DOCTYPE,
		OF_XMLPARSER_NUM_STATES
	} state;
	OFMutableString *cache;
	OFString *name;
	OFString *prefix;
	OFMutableArray *namespaces;
	OFMutableArray *attributes;
	OFString *attributeName;
	OFString *attributePrefix;
	char delimiter;
	OFMutableArray *previous;
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	of_xml_parser_processing_instructions_block_t
	    processingInstructionsHandler;
	of_xml_parser_element_start_block_t elementStartHandler;
	of_xml_parser_element_end_block_t elementEndHandler;
	of_xml_parser_string_block_t charactersHandler;
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
 */
- (void)setUnknownEntityHandler: (of_xml_parser_unknown_entity_block_t)block;
#endif

/**
 * Parses a buffer with the specified size.
 *
 * \param buf The buffer to parse
 * \param size The size of the buffer
 */
- (void)parseBuffer: (const char*)buf
	   withSize: (size_t)size;

/**
 * Parses the specified string.
 *
 * \param str The string to parse
 */
- (void)parseString: (OFString*)str;

/**
 * Parses the specified stream.
 *
 * \param stream The stream to parse
 */
- (void)parseStream: (OFStream*)stream;







|
|

|
|




|

|







303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
 */
- (void)setUnknownEntityHandler: (of_xml_parser_unknown_entity_block_t)block;
#endif

/**
 * Parses a buffer with the specified size.
 *
 * \param buffer The buffer to parse
 * \param length The length of the buffer
 */
- (void)parseBuffer: (const char*)buffer
	 withLength: (size_t)length;

/**
 * Parses the specified string.
 *
 * \param string The string to parse
 */
- (void)parseString: (OFString*)string;

/**
 * Parses the specified stream.
 *
 * \param stream The stream to parse
 */
- (void)parseStream: (OFStream*)stream;

Modified src/OFXMLParser.m from [f51f5629f8] to [130441ad5f].

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#import "OFMalformedXMLException.h"
#import "OFUnboundNamespaceException.h"

#import "macros.h"

typedef void (*state_function)(id, SEL, const char*, size_t*, size_t*);
static SEL selectors[OF_XMLPARSER_NUM_STATES];
static state_function lookup_table[OF_XMLPARSER_NUM_STATES];

static OF_INLINE OFString*
transform_string(OFMutableString *cache,
    OFObject <OFStringXMLUnescapingDelegate> *delegate)
{
	[cache replaceOccurrencesOfString: @"\r\n"
			       withString: @"\n"];
	[cache replaceOccurrencesOfString: @"\r"
			       withString: @"\n"];
	return [cache stringByXMLUnescapingWithDelegate: delegate];
}

static OFString*
namespace_for_prefix(OFString *prefix, OFArray *namespaces)
{
	OFDictionary **carray = [namespaces cArray];
	ssize_t i;

	if (prefix == nil)
		prefix = @"";

	for (i = [namespaces count] - 1; i >= 0; i--) {
		OFString *tmp;

		if ((tmp = [carray[i] objectForKey: prefix]) != nil)
			return tmp;
	}

	return nil;
}

static OF_INLINE void
resolve_attr_namespace(OFXMLAttribute *attr, OFString *prefix, OFString *ns,
    OFArray *namespaces, Class isa)
{
	OFString *attr_ns;
	OFString *attr_prefix = attr->ns;

	if (attr_prefix == nil)
		return;

	attr_ns = namespace_for_prefix(attr_prefix, namespaces);

	if ((attr_prefix != nil && attr_ns == nil))
		@throw [OFUnboundNamespaceException newWithClass: isa

							  prefix: attr_prefix];

	[attr->ns release];
	attr->ns = [attr_ns retain];
}

@implementation OFXMLParser
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
@synthesize processingInstructionsHandler, elementStartHandler;
@synthesize elementEndHandler, charactersHandler, CDATAHandler, commentHandler;
@synthesize unknownEntityHandler;
#endif

+ (void)initialize
{
	size_t i;

	const SEL sels[] = {
		@selector(_parseOutsideTagWithBuffer:i:last:),
		@selector(_parseTagOpenedWithBuffer:i:last:),
		@selector(_parseInProcessingInstructionsWithBuffer:i:last:),
		@selector(_parseInTagNameWithBuffer:i:last:),
		@selector(_parseInCloseTagNameWithBuffer:i:last:),
		@selector(_parseInTagWithBuffer:i:last:),
		@selector(_parseInAttributeNameWithBuffer:i:last:),
		@selector(_parseExpectDelimiterWithBuffer:i:last:),
		@selector(_parseInAttributeValueWithBuffer:i:last:),
		@selector(_parseExpectCloseWithBuffer:i:last:),
		@selector(_parseExpectSpaceOrCloseWithBuffer:i:last:),
		@selector(_parseInExclamationMarkWithBuffer:i:last:),
		@selector(_parseInCDATAOpeningWithBuffer:i:last:),
		@selector(_parseInCDATA1WithBuffer:i:last:),
		@selector(_parseInCDATA2WithBuffer:i:last:),
		@selector(_parseInCommentOpeningWithBuffer:i:last:),
		@selector(_parseInComment1WithBuffer:i:last:),
		@selector(_parseInComment2WithBuffer:i:last:),
		@selector(_parseInDoctypeWithBuffer:i:last:),
	};
	memcpy(selectors, sels, sizeof(sels));

	for (i = 0; i < OF_XMLPARSER_NUM_STATES; i++) {
		if (![self instancesRespondToSelector: selectors[i]])
			@throw [OFInitializationFailedException
			    newWithClass: self];

		lookup_table[i] = (state_function)
		    [self instanceMethodForSelector: selectors[i]];
	}
}

+ parser
{
	return [[[self alloc] init] autorelease];







|















|








|







|
|

|
|

|


|

|
|
>
|

|
|













|




















|






|







34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#import "OFMalformedXMLException.h"
#import "OFUnboundNamespaceException.h"

#import "macros.h"

typedef void (*state_function)(id, SEL, const char*, size_t*, size_t*);
static SEL selectors[OF_XMLPARSER_NUM_STATES];
static state_function lookupTable[OF_XMLPARSER_NUM_STATES];

static OF_INLINE OFString*
transform_string(OFMutableString *cache,
    OFObject <OFStringXMLUnescapingDelegate> *delegate)
{
	[cache replaceOccurrencesOfString: @"\r\n"
			       withString: @"\n"];
	[cache replaceOccurrencesOfString: @"\r"
			       withString: @"\n"];
	return [cache stringByXMLUnescapingWithDelegate: delegate];
}

static OFString*
namespace_for_prefix(OFString *prefix, OFArray *namespaces)
{
	OFDictionary **cArray = [namespaces cArray];
	ssize_t i;

	if (prefix == nil)
		prefix = @"";

	for (i = [namespaces count] - 1; i >= 0; i--) {
		OFString *tmp;

		if ((tmp = [cArray[i] objectForKey: prefix]) != nil)
			return tmp;
	}

	return nil;
}

static OF_INLINE void
resolve_attribute_namespace(OFXMLAttribute *attribute, OFString *prefix,
    OFString *ns, OFArray *namespaces, Class isa)
{
	OFString *attributeNS;
	OFString *attributePrefix = attribute->ns;

	if (attributePrefix == nil)
		return;

	attributeNS = namespace_for_prefix(attributePrefix, namespaces);

	if ((attributePrefix != nil && attributeNS == nil))
		@throw [OFUnboundNamespaceException
		    newWithClass: isa
			  prefix: attributePrefix];

	[attribute->ns release];
	attribute->ns = [attributeNS retain];
}

@implementation OFXMLParser
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
@synthesize processingInstructionsHandler, elementStartHandler;
@synthesize elementEndHandler, charactersHandler, CDATAHandler, commentHandler;
@synthesize unknownEntityHandler;
#endif

+ (void)initialize
{
	size_t i;

	const SEL selectors_[] = {
		@selector(_parseOutsideTagWithBuffer:i:last:),
		@selector(_parseTagOpenedWithBuffer:i:last:),
		@selector(_parseInProcessingInstructionsWithBuffer:i:last:),
		@selector(_parseInTagNameWithBuffer:i:last:),
		@selector(_parseInCloseTagNameWithBuffer:i:last:),
		@selector(_parseInTagWithBuffer:i:last:),
		@selector(_parseInAttributeNameWithBuffer:i:last:),
		@selector(_parseExpectDelimiterWithBuffer:i:last:),
		@selector(_parseInAttributeValueWithBuffer:i:last:),
		@selector(_parseExpectCloseWithBuffer:i:last:),
		@selector(_parseExpectSpaceOrCloseWithBuffer:i:last:),
		@selector(_parseInExclamationMarkWithBuffer:i:last:),
		@selector(_parseInCDATAOpeningWithBuffer:i:last:),
		@selector(_parseInCDATA1WithBuffer:i:last:),
		@selector(_parseInCDATA2WithBuffer:i:last:),
		@selector(_parseInCommentOpeningWithBuffer:i:last:),
		@selector(_parseInComment1WithBuffer:i:last:),
		@selector(_parseInComment2WithBuffer:i:last:),
		@selector(_parseInDoctypeWithBuffer:i:last:),
	};
	memcpy(selectors, selectors_, sizeof(selectors_));

	for (i = 0; i < OF_XMLPARSER_NUM_STATES; i++) {
		if (![self instancesRespondToSelector: selectors[i]])
			@throw [OFInitializationFailedException
			    newWithClass: self];

		lookupTable[i] = (state_function)
		    [self instanceMethodForSelector: selectors[i]];
	}
}

+ parser
{
	return [[[self alloc] init] autorelease];
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
{
	[(id)delegate release];

	[cache release];
	[name release];
	[prefix release];
	[namespaces release];
	[attrs release];
	[attrName release];
	[attrPrefix release];
	[previous release];
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	[elementStartHandler release];
	[elementEndHandler release];
	[charactersHandler release];
	[CDATAHandler release];
	[commentHandler release];
	[unknownEntityHandler release];
#endif

	[super dealloc];
}

- (id <OFXMLParserDelegate>)delegate
{
	return [[(id)delegate retain] autorelease];
}

- (void)setDelegate: (id <OFXMLParserDelegate>)delegate_
{
	[(id)delegate_ retain];
	[(id)delegate release];
	delegate = delegate_;
}

- (void)parseBuffer: (const char*)buf
	   withSize: (size_t)size
{
	size_t i, last = 0;

	for (i = 0; i < size; i++) {
		size_t j = i;

		lookup_table[state](self, selectors[state], buf, &i, &last);

		/* Ensure we don't count this character twice */
		if (i != j)
			continue;

		if (buf[i] == '\r' || (buf[i] == '\n' && !lastCarriageReturn))
			lineNumber++;

		lastCarriageReturn = (buf[i] == '\r');
	}

	/* In OF_XMLPARSER_IN_TAG, there can be only spaces */
	if (size - last > 0 && state != OF_XMLPARSER_IN_TAG)
		[cache appendCStringWithoutUTF8Checking: buf + last
						 length: size - last];
}

- (void)parseString: (OFString*)str
{
	[self parseBuffer: [str cString]
		 withSize: [str cStringLength]];
}

- (void)parseStream: (OFStream*)stream
{
	char *buf = [self allocMemoryWithSize: of_pagesize];

	@try {
		while (![stream isAtEndOfStream]) {
			size_t len = [stream readNBytes: of_pagesize
					     intoBuffer: buf];

			[self parseBuffer: buf
				 withSize: len];
		}
	} @finally {
		[self freeMemory: buf];
	}
}

- (void)parseFile: (OFString*)path
{
	OFFile *file = [[OFFile alloc] initWithPath: path
					       mode: @"rb"];







|
|
|















|




<
<
|



|



|


|












|

|


|

|
|




|



|
|

|
|


|







174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
{
	[(id)delegate release];

	[cache release];
	[name release];
	[prefix release];
	[namespaces release];
	[attributes release];
	[attributeName release];
	[attributePrefix release];
	[previous release];
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	[elementStartHandler release];
	[elementEndHandler release];
	[charactersHandler release];
	[CDATAHandler release];
	[commentHandler release];
	[unknownEntityHandler release];
#endif

	[super dealloc];
}

- (id <OFXMLParserDelegate>)delegate
{
	OF_GETTER(delegate, YES)
}

- (void)setDelegate: (id <OFXMLParserDelegate>)delegate_
{


	OF_SETTER(delegate, delegate_, YES, NO)
}

- (void)parseBuffer: (const char*)buf
	 withLength: (size_t)length
{
	size_t i, last = 0;

	for (i = 0; i < length; i++) {
		size_t j = i;

		lookupTable[state](self, selectors[state], buf, &i, &last);

		/* Ensure we don't count this character twice */
		if (i != j)
			continue;

		if (buf[i] == '\r' || (buf[i] == '\n' && !lastCarriageReturn))
			lineNumber++;

		lastCarriageReturn = (buf[i] == '\r');
	}

	/* In OF_XMLPARSER_IN_TAG, there can be only spaces */
	if (length - last > 0 && state != OF_XMLPARSER_IN_TAG)
		[cache appendCStringWithoutUTF8Checking: buf + last
						 length: length - last];
}

- (void)parseString: (OFString*)string
{
	[self parseBuffer: [string cString]
	       withLength: [string cStringLength]];
}

- (void)parseStream: (OFStream*)stream
{
	char *buffer = [self allocMemoryWithSize: of_pagesize];

	@try {
		while (![stream isAtEndOfStream]) {
			size_t length = [stream readNBytes: of_pagesize
						intoBuffer: buffer];

			[self parseBuffer: buffer
			       withLength: length];
		}
	} @finally {
		[self freeMemory: buffer];
	}
}

- (void)parseFile: (OFString*)path
{
	OFFile *file = [[OFFile alloc] initWithPath: path
					       mode: @"rb"];
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
 * The following methods handle the different states of the parser. They are
 * looked up in +[initialize] and put in a lookup table to speed things up.
 * One dispatch for every character would be way too slow!
 */

/* Not in a tag */
- (void)_parseOutsideTagWithBuffer: (const char*)buf
				 i: (size_t*)i
			      last: (size_t*)last
{
	size_t len;

	if ((finishedParsing || [previous count] < 1) && buf[*i] != ' ' &&
	    buf[*i] != '\t' && buf[*i] != '\n' && buf[*i] != '\r' &&
	    buf[*i] != '<')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (buf[*i] != '<')
		return;

	if ((len = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: len];

	if ([cache cStringLength] > 0) {
		OFString *str;
		OFAutoreleasePool *pool;

		pool = [[OFAutoreleasePool alloc] init];
		str = transform_string(cache, self);

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
		if (charactersHandler != NULL)
			charactersHandler(self, str);
		else
#endif
			[delegate parser: self
			 foundCharacters: str];

		[pool release];
	}

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_TAG_OPENED;
}

/* Tag was just opened */
- (void)_parseTagOpenedWithBuffer: (const char*)buf
				i: (size_t*)i
			     last: (size_t*)last
{
	if (finishedParsing && buf[*i] != '!' && buf[*i] != '?')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	switch (buf[*i]) {
		case '?':
			*last = *i + 1;
			state = OF_XMLPARSER_IN_PROCESSING_INSTRUCTIONS;
			level = 0;
			break;
		case '/':
			*last = *i + 1;







|



|

|
|
|



|


|
|
|


|



|



|



|











|



|



|







268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/*
 * The following methods handle the different states of the parser. They are
 * looked up in +[initialize] and put in a lookup table to speed things up.
 * One dispatch for every character would be way too slow!
 */

/* Not in a tag */
- (void)_parseOutsideTagWithBuffer: (const char*)buffer
				 i: (size_t*)i
			      last: (size_t*)last
{
	size_t length;

	if ((finishedParsing || [previous count] < 1) && buffer[*i] != ' ' &&
	    buffer[*i] != '\t' && buffer[*i] != '\n' && buffer[*i] != '\r' &&
	    buffer[*i] != '<')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (buffer[*i] != '<')
		return;

	if ((length = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: length];

	if ([cache cStringLength] > 0) {
		OFString *characters;
		OFAutoreleasePool *pool;

		pool = [[OFAutoreleasePool alloc] init];
		characters = transform_string(cache, self);

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
		if (charactersHandler != NULL)
			charactersHandler(self, characters);
		else
#endif
			[delegate parser: self
			 foundCharacters: characters];

		[pool release];
	}

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_TAG_OPENED;
}

/* Tag was just opened */
- (void)_parseTagOpenedWithBuffer: (const char*)buffer
				i: (size_t*)i
			     last: (size_t*)last
{
	if (finishedParsing && buffer[*i] != '!' && buffer[*i] != '?')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	switch (buffer[*i]) {
		case '?':
			*last = *i + 1;
			state = OF_XMLPARSER_IN_PROCESSING_INSTRUCTIONS;
			level = 0;
			break;
		case '/':
			*last = *i + 1;
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
			break;
	}
}

/* <?xml […]?> */
- (BOOL)_parseXMLProcessingInstructions: (OFString*)pi
{
	const char *pi_c;
	size_t i, last, pi_len;
	int xstate = 0;
	OFString *attr = nil;
	OFString *val = nil;
	char xdelim = 0;

	if (!acceptProlog)
		return NO;

	acceptProlog = NO;

	pi = [pi substringFromIndex: 3
			    toIndex: [pi length]];
	pi = [pi stringByDeletingLeadingAndTrailingWhitespaces];

	pi_c = [pi cString];
	pi_len = [pi cStringLength];

	for (i = last = 0; i < pi_len; i++) {
		switch (xstate) {
		case 0:
			if (pi_c[i] == ' ' || pi_c[i] == '\t' ||
			    pi_c[i] == '\r' || pi_c[i] == '\n')
				continue;

			last = i;
			xstate = 1;
			i--;

			break;
		case 1:
			if (pi_c[i] != '=')
				continue;

			attr = [OFString stringWithCString: pi_c + last
						    length: i - last];
			last = i + 1;
			xstate = 2;

			break;
		case 2:
			if (pi_c[i] != '\'' && pi_c[i] != '"')
				return NO;

			xdelim = pi_c[i];
			last = i + 1;
			xstate = 3;

			break;
		case 3:
			if (pi_c[i] != xdelim)
				continue;

			val = [OFString stringWithCString: pi_c + last
						   length: i - last];

			if ([attr isEqual: @"version"])
				if (![val hasPrefix: @"1."])
					return NO;

			if ([attr isEqual: @"encoding"])
				if ([val caseInsensitiveCompare: @"utf-8"] !=
				    OF_ORDERED_SAME)
					return NO;

			last = i + 1;
			xstate = 0;

			break;
		}
	}

	if (xstate != 0)
		return NO;

	return YES;
}

/* Inside processing instructions */
- (void)_parseInProcessingInstructionsWithBuffer: (const char*)buf
					       i: (size_t*)i
					    last: (size_t*)last
{
	if (buf[*i] == '?')
		level = 1;
	else if (level == 1 && buf[*i] == '>') {
		OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
		OFMutableString *pi;
		size_t len;

		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: *i - *last];
		pi = [[cache mutableCopy] autorelease];
		len = [pi length];

		[pi deleteCharactersFromIndex: len - 1
				      toIndex: len];








|
|
|
|
|
|










|
|

|
|

|
|



|




|


|
|

|



|


|

|



|


|
|

|
|


|
|




|





|






|



|

|




|







347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
			break;
	}
}

/* <?xml […]?> */
- (BOOL)_parseXMLProcessingInstructions: (OFString*)pi
{
	const char *cString;
	size_t i, last, length;
	int piState = 0;
	OFString *attribute = nil;
	OFString *value = nil;
	char piDelimiter = 0;

	if (!acceptProlog)
		return NO;

	acceptProlog = NO;

	pi = [pi substringFromIndex: 3
			    toIndex: [pi length]];
	pi = [pi stringByDeletingLeadingAndTrailingWhitespaces];

	cString = [pi cString];
	length = [pi cStringLength];

	for (i = last = 0; i < length; i++) {
		switch (piState) {
		case 0:
			if (cString[i] == ' ' || cString[i] == '\t' ||
			    cString[i] == '\r' || cString[i] == '\n')
				continue;

			last = i;
			piState = 1;
			i--;

			break;
		case 1:
			if (cString[i] != '=')
				continue;

			attribute = [OFString stringWithCString: cString + last
							 length: i - last];
			last = i + 1;
			piState = 2;

			break;
		case 2:
			if (cString[i] != '\'' && cString[i] != '"')
				return NO;

			piDelimiter = cString[i];
			last = i + 1;
			piState = 3;

			break;
		case 3:
			if (cString[i] != piDelimiter)
				continue;

			value = [OFString stringWithCString: cString + last
						     length: i - last];

			if ([attribute isEqual: @"version"])
				if (![value hasPrefix: @"1."])
					return NO;

			if ([attribute isEqual: @"encoding"])
				if ([value caseInsensitiveCompare: @"utf-8"] !=
				    OF_ORDERED_SAME)
					return NO;

			last = i + 1;
			piState = 0;

			break;
		}
	}

	if (piState != 0)
		return NO;

	return YES;
}

/* Inside processing instructions */
- (void)_parseInProcessingInstructionsWithBuffer: (const char*)buffer
					       i: (size_t*)i
					    last: (size_t*)last
{
	if (buffer[*i] == '?')
		level = 1;
	else if (level == 1 && buffer[*i] == '>') {
		OFAutoreleasePool *pool = [[OFAutoreleasePool alloc] init];
		OFMutableString *pi;
		size_t len;

		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: *i - *last];
		pi = [[cache mutableCopy] autorelease];
		len = [pi length];

		[pi deleteCharactersFromIndex: len - 1
				      toIndex: len];

476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else
		level = 0;
}

/* Inside a tag, no name yet */
- (void)_parseInTagNameWithBuffer: (const char*)buf
				i: (size_t*)i
			     last: (size_t*)last
{
	const char *cache_c, *tmp;
	size_t len, cache_len;

	if (buf[*i] != ' ' && buf[*i] != '\t' && buf[*i] != '\n' &&
	    buf[*i] != '\r' && buf[*i] != '>' && buf[*i] != '/')
		return;

	if ((len = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: len];

	cache_c = [cache cString];
	cache_len = [cache cStringLength];

	if ((tmp = memchr(cache_c, ':', cache_len)) != NULL) {
		name = [[OFString alloc] initWithCString: tmp + 1
						  length: cache_len -
							  (tmp - cache_c) - 1];

		prefix = [[OFString alloc] initWithCString: cache_c
						    length: tmp - cache_c];
	} else {
		name = [cache copy];
		prefix = nil;
	}

	if (buf[*i] == '>' || buf[*i] == '/') {
		OFAutoreleasePool *pool;
		OFString *ns;

		ns = namespace_for_prefix(prefix, namespaces);

		if (prefix != nil && ns == nil)
			@throw







|



|
|

|
|


|
|
|

|
|

|

|
|
>
|
|





|







475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else
		level = 0;
}

/* Inside a tag, no name yet */
- (void)_parseInTagNameWithBuffer: (const char*)buffer
				i: (size_t*)i
			     last: (size_t*)last
{
	const char *cacheCString, *tmp;
	size_t length, cacheLength;

	if (buffer[*i] != ' ' && buffer[*i] != '\t' && buffer[*i] != '\n' &&
	    buffer[*i] != '\r' && buffer[*i] != '>' && buffer[*i] != '/')
		return;

	if ((length = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: length];

	cacheCString = [cache cString];
	cacheLength = [cache cStringLength];

	if ((tmp = memchr(cacheCString, ':', cacheLength)) != NULL) {
		name = [[OFString alloc] initWithCString: tmp + 1
						  length: cacheLength -
							  (tmp - cacheCString) -
							  1];
		prefix = [[OFString alloc] initWithCString: cacheCString
						    length: tmp - cacheCString];
	} else {
		name = [cache copy];
		prefix = nil;
	}

	if (buffer[*i] == '>' || buffer[*i] == '/') {
		OFAutoreleasePool *pool;
		OFString *ns;

		ns = namespace_for_prefix(prefix, namespaces);

		if (prefix != nil && ns == nil)
			@throw
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596

597
598
599
600
601
602
603
604
605
#endif
			[delegate parser: self
			 didStartElement: name
			      withPrefix: prefix
			       namespace: ns
			      attributes: nil];

		if (buf[*i] == '/') {
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
			if (elementEndHandler != NULL)
				elementEndHandler(self, name, prefix, ns);
			else
#endif
				[delegate parser: self
				   didEndElement: name
				      withPrefix: prefix
				       namespace: ns];
		} else
			[previous addObject: [[cache copy] autorelease]];

			[pool release];

			[name release];
			[prefix release];
			name = prefix = nil;

			state = (buf[*i] == '/'
			    ? OF_XMLPARSER_EXPECT_CLOSE
			    : OF_XMLPARSER_OUTSIDE_TAG);
	} else
		state = OF_XMLPARSER_IN_TAG;

	if (buf[*i] != '/') {
		OFAutoreleasePool *pool;

		pool = [[OFAutoreleasePool alloc] init];
		[namespaces addObject: [OFMutableDictionary dictionary]];
		[pool release];
	}

	[cache setToCString: ""];
	*last = *i + 1;
}

/* Inside a close tag, no name yet */
- (void)_parseInCloseTagNameWithBuffer: (const char*)buf
				     i: (size_t*)i
				  last: (size_t*)last
{
	OFAutoreleasePool *pool;
	const char *cache_c, *tmp;
	size_t len, cache_len;
	OFString *ns;

	if (buf[*i] != ' ' && buf[*i] != '\t' && buf[*i] != '\n' &&
	    buf[*i] != '\r' && buf[*i] != '>')
		return;

	if ((len = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: len];
	cache_c = [cache cString];
	cache_len = [cache cStringLength];

	if ((tmp = memchr(cache_c, ':', cache_len)) != NULL) {
		name = [[OFString alloc] initWithCString: tmp + 1
						  length: cache_len -
							  (tmp - cache_c) - 1];

		prefix = [[OFString alloc] initWithCString: cache_c
						    length: tmp - cache_c];
	} else {
		name = [cache copy];
		prefix = nil;
	}

	if (![[previous lastObject] isEqual: cache])
		@throw [OFMalformedXMLException newWithClass: isa







|


















|





|












|




|
|


|
|


|
|
|
|
|

|

|
|
>
|
|







529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#endif
			[delegate parser: self
			 didStartElement: name
			      withPrefix: prefix
			       namespace: ns
			      attributes: nil];

		if (buffer[*i] == '/') {
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
			if (elementEndHandler != NULL)
				elementEndHandler(self, name, prefix, ns);
			else
#endif
				[delegate parser: self
				   didEndElement: name
				      withPrefix: prefix
				       namespace: ns];
		} else
			[previous addObject: [[cache copy] autorelease]];

			[pool release];

			[name release];
			[prefix release];
			name = prefix = nil;

			state = (buffer[*i] == '/'
			    ? OF_XMLPARSER_EXPECT_CLOSE
			    : OF_XMLPARSER_OUTSIDE_TAG);
	} else
		state = OF_XMLPARSER_IN_TAG;

	if (buffer[*i] != '/') {
		OFAutoreleasePool *pool;

		pool = [[OFAutoreleasePool alloc] init];
		[namespaces addObject: [OFMutableDictionary dictionary]];
		[pool release];
	}

	[cache setToCString: ""];
	*last = *i + 1;
}

/* Inside a close tag, no name yet */
- (void)_parseInCloseTagNameWithBuffer: (const char*)buffer
				     i: (size_t*)i
				  last: (size_t*)last
{
	OFAutoreleasePool *pool;
	const char *cacheCString, *tmp;
	size_t length, cacheLength;
	OFString *ns;

	if (buffer[*i] != ' ' && buffer[*i] != '\t' && buffer[*i] != '\n' &&
	    buffer[*i] != '\r' && buffer[*i] != '>')
		return;

	if ((length = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: length];
	cacheCString = [cache cString];
	cacheLength = [cache cStringLength];

	if ((tmp = memchr(cacheCString, ':', cacheLength)) != NULL) {
		name = [[OFString alloc] initWithCString: tmp + 1
						  length: cacheLength -
							  (tmp - cacheCString) -
							  1];
		prefix = [[OFString alloc] initWithCString: cacheCString
						    length: tmp - cacheCString];
	} else {
		name = [cache copy];
		prefix = nil;
	}

	if (![[previous lastObject] isEqual: cache])
		@throw [OFMalformedXMLException newWithClass: isa
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675

676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

	[namespaces removeNObjects: 1];
	[name release];
	[prefix release];
	name = prefix = nil;

	*last = *i + 1;
	state = (buf[*i] == '>'
	    ? OF_XMLPARSER_OUTSIDE_TAG
	    : OF_XMLPARSER_EXPECT_SPACE_OR_CLOSE);

	if ([previous count] == 0)
		finishedParsing = YES;
}

/* Inside a tag, name found */
- (void)_parseInTagWithBuffer: (const char*)buf
			    i: (size_t*)i
			 last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFString *ns;
	OFXMLAttribute **attrs_c;
	size_t j, attrs_cnt;

	if (buf[*i] != '>' && buf[*i] != '/') {
		if (buf[*i] != ' ' && buf[*i] != '\t' && buf[*i] != '\n' &&
		    buf[*i] != '\r') {
			*last = *i;
			state = OF_XMLPARSER_IN_ATTR_NAME;
			(*i)--;
		}

		return;
	}

	attrs_c = [attrs cArray];
	attrs_cnt = [attrs count];

	ns = namespace_for_prefix(prefix, namespaces);

	if (prefix != nil && ns == nil)
		@throw [OFUnboundNamespaceException newWithClass: isa
							  prefix: prefix];

	for (j = 0; j < attrs_cnt; j++)

		resolve_attr_namespace(attrs_c[j], prefix, ns, namespaces, isa);

	pool = [[OFAutoreleasePool alloc] init];

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	if (elementStartHandler != NULL)
		elementStartHandler(self, name, prefix, ns, attrs);
	else
#endif
		[delegate parser: self
		 didStartElement: name
		      withPrefix: prefix
		       namespace: ns
		      attributes: attrs];

	if (buf[*i] == '/') {
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
		if (elementEndHandler != NULL)
			elementEndHandler(self, name, prefix, ns);
		else
#endif
			[delegate parser: self
			   didEndElement: name







|








|





|
|

|
|
|








|
|







|
>
|





|






|

|







631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700

	[namespaces removeNObjects: 1];
	[name release];
	[prefix release];
	name = prefix = nil;

	*last = *i + 1;
	state = (buffer[*i] == '>'
	    ? OF_XMLPARSER_OUTSIDE_TAG
	    : OF_XMLPARSER_EXPECT_SPACE_OR_CLOSE);

	if ([previous count] == 0)
		finishedParsing = YES;
}

/* Inside a tag, name found */
- (void)_parseInTagWithBuffer: (const char*)buffer
			    i: (size_t*)i
			 last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFString *ns;
	OFXMLAttribute **attributesCArray;
	size_t j, attributesCount;

	if (buffer[*i] != '>' && buffer[*i] != '/') {
		if (buffer[*i] != ' ' && buffer[*i] != '\t' &&
		    buffer[*i] != '\n' && buffer[*i] != '\r') {
			*last = *i;
			state = OF_XMLPARSER_IN_ATTR_NAME;
			(*i)--;
		}

		return;
	}

	attributesCArray = [attributes cArray];
	attributesCount = [attributes count];

	ns = namespace_for_prefix(prefix, namespaces);

	if (prefix != nil && ns == nil)
		@throw [OFUnboundNamespaceException newWithClass: isa
							  prefix: prefix];

	for (j = 0; j < attributesCount; j++)
		resolve_attribute_namespace(attributesCArray[j], prefix, ns,
		    namespaces, isa);

	pool = [[OFAutoreleasePool alloc] init];

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	if (elementStartHandler != NULL)
		elementStartHandler(self, name, prefix, ns, attributes);
	else
#endif
		[delegate parser: self
		 didStartElement: name
		      withPrefix: prefix
		       namespace: ns
		      attributes: attributes];

	if (buffer[*i] == '/') {
#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
		if (elementEndHandler != NULL)
			elementEndHandler(self, name, prefix, ns);
		else
#endif
			[delegate parser: self
			   didEndElement: name
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743

744
745
746
747
748

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808

809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
	} else
		[previous addObject: name];

	[pool release];

	[name release];
	[prefix release];
	[attrs release];
	name = prefix = nil;
	attrs = nil;

	*last = *i + 1;
	state = (buf[*i] == '/'
	    ? OF_XMLPARSER_EXPECT_CLOSE
	    : OF_XMLPARSER_OUTSIDE_TAG);
}

/* Looking for attribute name */
- (void)_parseInAttributeNameWithBuffer: (const char*)buf
				      i: (size_t*)i
				   last: (size_t*)last
{
	const char *cache_c, *tmp;
	size_t len, cache_len;

	if (buf[*i] != '=')
		return;

	if ((len = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: len];

	[cache deleteLeadingAndTrailingWhitespaces];
	cache_c = [cache cString];
	cache_len = [cache cStringLength];

	if ((tmp = memchr(cache_c, ':', cache_len)) != NULL) {

		attrName = [[OFString alloc] initWithCString: tmp + 1
						      length: cache_len -
							      (tmp - cache_c) -
							      1];
		attrPrefix = [[OFString alloc] initWithCString: cache_c

							length: tmp - cache_c];
	} else {
		attrName = [cache copy];
		attrPrefix = nil;
	}

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_EXPECT_DELIM;
}

/* Expecting delimiter */
- (void)_parseExpectDelimiterWithBuffer: (const char*)buf
				      i: (size_t*)i
				   last: (size_t*)last
{
	*last = *i + 1;

	if (buf[*i] == ' ' || buf[*i] == '\t' || buf[*i] == '\n' ||
	    buf[*i] == '\r')
		return;

	if (buf[*i] != '\'' && buf[*i] != '"')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	delim = buf[*i];
	state = OF_XMLPARSER_IN_ATTR_VALUE;
}

/* Looking for attribute value */
- (void)_parseInAttributeValueWithBuffer: (const char*)buf
				       i: (size_t*)i
				    last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFString *attr_val;
	size_t len;

	if (buf[*i] != delim)
		return;

	if ((len = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buf + *last
						 length: len];

	pool = [[OFAutoreleasePool alloc] init];
	attr_val = transform_string(cache, self);

	if (attrPrefix == nil && [attrName isEqual: @"xmlns"])
		[[namespaces lastObject] setObject: attr_val
					    forKey: @""];
	if ([attrPrefix isEqual: @"xmlns"])
		[[namespaces lastObject] setObject: attr_val
					    forKey: attrName];

	if (attrs == nil)
		attrs = [[OFMutableArray alloc] init];


	[attrs addObject: [OFXMLAttribute attributeWithName: attrName
						  namespace: attrPrefix
						stringValue: attr_val]];

	[pool release];

	[cache setToCString: ""];
	[attrName release];
	[attrPrefix release];
	attrName = attrPrefix = nil;

	*last = *i + 1;
	state = OF_XMLPARSER_IN_TAG;
}

/* Expecting closing '>' */
- (void)_parseExpectCloseWithBuffer: (const char*)buf
				  i: (size_t*)i
			       last: (size_t*)last
{
	if (buf[*i] == '>') {
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];
}

/* Expecting closing '>' or space */
- (void)_parseExpectSpaceOrCloseWithBuffer: (const char*)buf
					 i: (size_t*)i
				      last: (size_t*)last
{
	if (buf[*i] == '>') {
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else if (buf[*i] != ' ' && buf[*i] != '\t' && buf[*i] != '\n' &&
	    buf[*i] != '\r')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];
}

/* In <! */
- (void)_parseInExclamationMarkWithBuffer: (const char*)buf
					i: (size_t*)i
				     last: (size_t*)last
{
	if (finishedParsing && buf[*i] != '-')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (buf[*i] == '-')
		state = OF_XMLPARSER_IN_COMMENT_OPENING;
	else if (buf[*i] == '[') {
		state = OF_XMLPARSER_IN_CDATA_OPENING;
		level = 0;
	} else if (buf[*i] == 'D') {
		state = OF_XMLPARSER_IN_DOCTYPE;
		level = 0;
	} else
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	*last = *i + 1;
}

/* CDATA */
- (void)_parseInCDATAOpeningWithBuffer: (const char*)buf
				     i: (size_t*)i
				  last: (size_t*)last
{
	if (buf[*i] != "CDATA["[level])
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (++level == 6) {
		state = OF_XMLPARSER_IN_CDATA_1;
		level = 0;
	}

	*last = *i + 1;
}

- (void)_parseInCDATA1WithBuffer: (const char*)buf
			       i: (size_t*)i
			    last: (size_t*)last
{
	if (buf[*i] == ']')
		level++;
	else
		level = 0;

	if (level == 2)
		state = OF_XMLPARSER_IN_CDATA_2;
}

- (void)_parseInCDATA2WithBuffer: (const char*)buf
			       i: (size_t*)i
			    last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFMutableString *cdata;
	size_t len;

	if (buf[*i] != '>') {
		state = OF_XMLPARSER_IN_CDATA_1;
		level = (buf[*i] == ']' ? 1 : 0);

		return;
	}

	pool = [[OFAutoreleasePool alloc] init];

	[cache appendCStringWithoutUTF8Checking: buf + *last
					 length: *i - *last];
	cdata = [[cache mutableCopy] autorelease];
	len = [cdata length];

	[cdata deleteCharactersFromIndex: len - 2
				 toIndex: len];

	/*
	 * Class swizzle the string to be immutable. We pass it as OFString*, so
	 * it can't be modified anyway. But not swizzling it would create a
	 * real copy each time -[copy] is called.
	 */
	cdata->isa = [OFString class];

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	if (CDATAHandler != NULL)
		CDATAHandler(self, cdata);
	else
#endif
		[delegate parser: self
		      foundCDATA: cdata];

	[pool release];

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_OUTSIDE_TAG;
}

/* Comment */
- (void)_parseInCommentOpeningWithBuffer: (const char*)buf
				       i: (size_t*)i
				    last: (size_t*)last
{
	if (buf[*i] != '-')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	*last = *i + 1;
	state = OF_XMLPARSER_IN_COMMENT_1;
	level = 0;
}

- (void)_parseInComment1WithBuffer: (const char*)buf
				 i: (size_t*)i
			      last: (size_t*)last
{
	if (buf[*i] == '-')
		level++;
	else
		level = 0;

	if (level == 2)
		state = OF_XMLPARSER_IN_COMMENT_2;
}

- (void)_parseInComment2WithBuffer: (const char*)buf
				 i: (size_t*)i
			      last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFMutableString *comment;
	size_t len;

	if (buf[*i] != '>')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	pool = [[OFAutoreleasePool alloc] init];

	[cache appendCStringWithoutUTF8Checking: buf + *last
					 length: *i - *last];
	comment = [[cache mutableCopy] autorelease];
	len = [comment length];

	[comment deleteCharactersFromIndex: len - 2
				   toIndex: len];

	/*
	 * Class swizzle the string to be immutable. We pass it as OFString*, so
	 * it can't be modified anyway. But not swizzling it would create a
	 * real copy each time -[copy] is called.
	 */
	comment->isa = [OFString class];







|

|


|





|



|
|

|


|
|
|


|
|

|
>
|
|
<
<
|
>
|

|
|









|





|
|


|



|




|




|
|

|


|
|
|


|

|
|

|
|
|

|
|

>
|
|
|




|
|
|






|



|








|



|


|
|





|



|



|

|


|










|



|











|



|








|




|
|

|

|






|

|
|

|
|






|



|



|










|



|








|



|








|





|

|





|


|

|
|







709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748


749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
	} else
		[previous addObject: name];

	[pool release];

	[name release];
	[prefix release];
	[attributes release];
	name = prefix = nil;
	attributes = nil;

	*last = *i + 1;
	state = (buffer[*i] == '/'
	    ? OF_XMLPARSER_EXPECT_CLOSE
	    : OF_XMLPARSER_OUTSIDE_TAG);
}

/* Looking for attribute name */
- (void)_parseInAttributeNameWithBuffer: (const char*)buffer
				      i: (size_t*)i
				   last: (size_t*)last
{
	const char *cacheCString, *tmp;
	size_t length, cacheLength;

	if (buffer[*i] != '=')
		return;

	if ((length = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: length];

	[cache deleteLeadingAndTrailingWhitespaces];
	cacheCString = [cache cString];
	cacheLength = [cache cStringLength];

	if ((tmp = memchr(cacheCString, ':', cacheLength)) != NULL) {
		attributeName = [[OFString alloc]
		    initWithCString: tmp + 1
			     length: cacheLength - (tmp - cacheCString) - 1];


		attributePrefix = [[OFString alloc]
		    initWithCString: cacheCString
			     length: tmp - cacheCString];
	} else {
		attributeName = [cache copy];
		attributePrefix = nil;
	}

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_EXPECT_DELIM;
}

/* Expecting delimiter */
- (void)_parseExpectDelimiterWithBuffer: (const char*)buffer
				      i: (size_t*)i
				   last: (size_t*)last
{
	*last = *i + 1;

	if (buffer[*i] == ' ' || buffer[*i] == '\t' || buffer[*i] == '\n' ||
	    buffer[*i] == '\r')
		return;

	if (buffer[*i] != '\'' && buffer[*i] != '"')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	delimiter = buffer[*i];
	state = OF_XMLPARSER_IN_ATTR_VALUE;
}

/* Looking for attribute value */
- (void)_parseInAttributeValueWithBuffer: (const char*)buffer
				       i: (size_t*)i
				    last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFString *attributeValue;
	size_t length;

	if (buffer[*i] != delimiter)
		return;

	if ((length = *i - *last) > 0)
		[cache appendCStringWithoutUTF8Checking: buffer + *last
						 length: length];

	pool = [[OFAutoreleasePool alloc] init];
	attributeValue = transform_string(cache, self);

	if (attributePrefix == nil && [attributeName isEqual: @"xmlns"])
		[[namespaces lastObject] setObject: attributeValue
					    forKey: @""];
	if ([attributePrefix isEqual: @"xmlns"])
		[[namespaces lastObject] setObject: attributeValue
					    forKey: attributeName];

	if (attributes == nil)
		attributes = [[OFMutableArray alloc] init];

	[attributes addObject:
	    [OFXMLAttribute attributeWithName: attributeName
				    namespace: attributePrefix
				  stringValue: attributeValue]];

	[pool release];

	[cache setToCString: ""];
	[attributeName release];
	[attributePrefix release];
	attributeName = attributePrefix = nil;

	*last = *i + 1;
	state = OF_XMLPARSER_IN_TAG;
}

/* Expecting closing '>' */
- (void)_parseExpectCloseWithBuffer: (const char*)buffer
				  i: (size_t*)i
			       last: (size_t*)last
{
	if (buffer[*i] == '>') {
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];
}

/* Expecting closing '>' or space */
- (void)_parseExpectSpaceOrCloseWithBuffer: (const char*)buffer
					 i: (size_t*)i
				      last: (size_t*)last
{
	if (buffer[*i] == '>') {
		*last = *i + 1;
		state = OF_XMLPARSER_OUTSIDE_TAG;
	} else if (buffer[*i] != ' ' && buffer[*i] != '\t' &&
	    buffer[*i] != '\n' && buffer[*i] != '\r')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];
}

/* In <! */
- (void)_parseInExclamationMarkWithBuffer: (const char*)buffer
					i: (size_t*)i
				     last: (size_t*)last
{
	if (finishedParsing && buffer[*i] != '-')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (buffer[*i] == '-')
		state = OF_XMLPARSER_IN_COMMENT_OPENING;
	else if (buffer[*i] == '[') {
		state = OF_XMLPARSER_IN_CDATA_OPENING;
		level = 0;
	} else if (buffer[*i] == 'D') {
		state = OF_XMLPARSER_IN_DOCTYPE;
		level = 0;
	} else
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	*last = *i + 1;
}

/* CDATA */
- (void)_parseInCDATAOpeningWithBuffer: (const char*)buffer
				     i: (size_t*)i
				  last: (size_t*)last
{
	if (buffer[*i] != "CDATA["[level])
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (++level == 6) {
		state = OF_XMLPARSER_IN_CDATA_1;
		level = 0;
	}

	*last = *i + 1;
}

- (void)_parseInCDATA1WithBuffer: (const char*)buffer
			       i: (size_t*)i
			    last: (size_t*)last
{
	if (buffer[*i] == ']')
		level++;
	else
		level = 0;

	if (level == 2)
		state = OF_XMLPARSER_IN_CDATA_2;
}

- (void)_parseInCDATA2WithBuffer: (const char*)buffer
			       i: (size_t*)i
			    last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFMutableString *CDATA;
	size_t length;

	if (buffer[*i] != '>') {
		state = OF_XMLPARSER_IN_CDATA_1;
		level = (buffer[*i] == ']' ? 1 : 0);

		return;
	}

	pool = [[OFAutoreleasePool alloc] init];

	[cache appendCStringWithoutUTF8Checking: buffer + *last
					 length: *i - *last];
	CDATA = [[cache mutableCopy] autorelease];
	length = [CDATA length];

	[CDATA deleteCharactersFromIndex: length - 2
				 toIndex: length];

	/*
	 * Class swizzle the string to be immutable. We pass it as OFString*, so
	 * it can't be modified anyway. But not swizzling it would create a
	 * real copy each time -[copy] is called.
	 */
	CDATA->isa = [OFString class];

#if defined(OF_HAVE_PROPERTIES) && defined(OF_HAVE_BLOCKS)
	if (CDATAHandler != NULL)
		CDATAHandler(self, CDATA);
	else
#endif
		[delegate parser: self
		      foundCDATA: CDATA];

	[pool release];

	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_OUTSIDE_TAG;
}

/* Comment */
- (void)_parseInCommentOpeningWithBuffer: (const char*)buffer
				       i: (size_t*)i
				    last: (size_t*)last
{
	if (buffer[*i] != '-')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	*last = *i + 1;
	state = OF_XMLPARSER_IN_COMMENT_1;
	level = 0;
}

- (void)_parseInComment1WithBuffer: (const char*)buffer
				 i: (size_t*)i
			      last: (size_t*)last
{
	if (buffer[*i] == '-')
		level++;
	else
		level = 0;

	if (level == 2)
		state = OF_XMLPARSER_IN_COMMENT_2;
}

- (void)_parseInComment2WithBuffer: (const char*)buffer
				 i: (size_t*)i
			      last: (size_t*)last
{
	OFAutoreleasePool *pool;
	OFMutableString *comment;
	size_t length;

	if (buffer[*i] != '>')
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	pool = [[OFAutoreleasePool alloc] init];

	[cache appendCStringWithoutUTF8Checking: buffer + *last
					 length: *i - *last];
	comment = [[cache mutableCopy] autorelease];
	length = [comment length];

	[comment deleteCharactersFromIndex: length - 2
				   toIndex: length];

	/*
	 * Class swizzle the string to be immutable. We pass it as OFString*, so
	 * it can't be modified anyway. But not swizzling it would create a
	 * real copy each time -[copy] is called.
	 */
	comment->isa = [OFString class];
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_OUTSIDE_TAG;
}

/* In <!DOCTYPE ...> */
- (void)_parseInDoctypeWithBuffer: (const char*)buf
				i: (size_t*)i
			     last: (size_t*)last
{
	if ((level < 6 && buf[*i] != "OCTYPE"[level]) ||
	    (level == 6 && buf[*i] != ' ' && buf[*i] != '\t' &&
	    buf[*i] != '\n' && buf[*i] != '\r'))
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (level < 7 || buf[*i] == '<')
		level++;

	if (buf[*i] == '>') {
		if (level == 7)
			state = OF_XMLPARSER_OUTSIDE_TAG;
		else
			level--;
	}

	*last = *i + 1;







|



|
|
|



|


|







1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
	[cache setToCString: ""];

	*last = *i + 1;
	state = OF_XMLPARSER_OUTSIDE_TAG;
}

/* In <!DOCTYPE ...> */
- (void)_parseInDoctypeWithBuffer: (const char*)buffer
				i: (size_t*)i
			     last: (size_t*)last
{
	if ((level < 6 && buffer[*i] != "OCTYPE"[level]) ||
	    (level == 6 && buffer[*i] != ' ' && buffer[*i] != '\t' &&
	    buffer[*i] != '\n' && buffer[*i] != '\r'))
		@throw [OFMalformedXMLException newWithClass: isa
						      parser: self];

	if (level < 7 || buffer[*i] == '<')
		level++;

	if (buffer[*i] == '>') {
		if (level == 7)
			state = OF_XMLPARSER_OUTSIDE_TAG;
		else
			level--;
	}

	*last = *i + 1;
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
{
}

-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attrs
{
}

-  (void)parser: (OFXMLParser*)parser
  didEndElement: (OFString*)name
     withPrefix: (OFString*)prefix
      namespace: (OFString*)ns
{
}

-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)string
{
}

- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)cdata
{
}

- (void)parser: (OFXMLParser*)parser
  foundComment: (OFString*)comment
{
}







|











|




|







1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
{
}

-    (void)parser: (OFXMLParser*)parser
  didStartElement: (OFString*)name
       withPrefix: (OFString*)prefix
	namespace: (OFString*)ns
       attributes: (OFArray*)attributes
{
}

-  (void)parser: (OFXMLParser*)parser
  didEndElement: (OFString*)name
     withPrefix: (OFString*)prefix
      namespace: (OFString*)ns
{
}

-    (void)parser: (OFXMLParser*)parser
  foundCharacters: (OFString*)characters
{
}

- (void)parser: (OFXMLParser*)parser
    foundCDATA: (OFString*)CDATA
{
}

- (void)parser: (OFXMLParser*)parser
  foundComment: (OFString*)comment
{
}

Modified src/asprintf.m from [871d5b824d] to [970a47cdfd].

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

int
vasprintf(char **strp, const char *fmt, va_list args)
{
	int size;

	if ((size = vsnprintf(NULL, 0, fmt, args)) < 0)
		return size;
	if ((*strp = malloc((size_t)size + 1)) == NULL)
		return -1;

	return vsnprintf(*strp, (size_t)size + 1, fmt, args);
}

int
asprintf(char **strp, const char *fmt, ...)
{
	int ret;
	va_list args;

	va_start(args, fmt);
	ret = vasprintf(strp, fmt, args);
	va_end(args);

	return ret;
}







|

|

|
|
|


|



|


|

|
|




17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "config.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

int
vasprintf(char **cString, const char *format, va_list arguments)
{
	int length;

	if ((length = vsnprintf(NULL, 0, format, arguments)) < 0)
		return length;
	if ((*cString = malloc((size_t)length + 1)) == NULL)
		return -1;

	return vsnprintf(*cString, (size_t)length + 1, format, arguments);
}

int
asprintf(char **cString, const char *format, ...)
{
	int ret;
	va_list arguments;

	va_start(arguments, format);
	ret = vasprintf(cString, format, arguments);
	va_end(args);

	return ret;
}

Modified src/base64.h from [a2c286eeff] to [1452cf6869].

25
26
27
28
29
30
31
32
33
34
35
36
@class OFString;
@class OFDataArray;

#ifdef __cplusplus
extern "C" {
#endif
extern const char of_base64_table[64];
extern OFString *of_base64_encode(const char *buf, size_t len);
extern BOOL of_base64_decode(OFDataArray *data, const char *str, size_t len);
#ifdef __cplusplus
}
#endif







|
|



25
26
27
28
29
30
31
32
33
34
35
36
@class OFString;
@class OFDataArray;

#ifdef __cplusplus
extern "C" {
#endif
extern const char of_base64_table[64];
extern OFString *of_base64_encode(const char*, size_t);
extern BOOL of_base64_decode(OFDataArray*, const char*, size_t);
#ifdef __cplusplus
}
#endif

Modified src/base64.m from [769602ecfc] to [5331624491].

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
	 3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
	20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30,
	31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
	48, 49, 50, 51, -1, -1, -1, -1, -1
};

OFString*
of_base64_encode(const char *data, size_t len)
{
	OFMutableString *ret = [OFMutableString string];
	uint8_t *buf = (uint8_t*)data;
	size_t i;
	uint8_t rest;
	char tb[4];
	uint32_t sb;

	rest = len % 3;

	for (i = 0; i < len - rest; i += 3) {
		sb = (buf[i] << 16) | (buf[i + 1] << 8) | buf[i + 2];

		tb[0] = of_base64_encode_table[(sb & 0xFC0000) >> 18];
		tb[1] = of_base64_encode_table[(sb & 0x03F000) >> 12];
		tb[2] = of_base64_encode_table[(sb & 0x000FC0) >> 6];
		tb[3] = of_base64_encode_table[sb & 0x00003F];

		[ret appendCStringWithoutUTF8Checking: tb
					       length: 4];
	}

	switch (rest) {
	case 1:
		tb[0] = of_base64_encode_table[buf[i] >> 2];
		tb[1] = of_base64_encode_table[(buf[i] & 3) << 4];
		tb[2] = tb[3] = '=';

		[ret appendCStringWithoutUTF8Checking: tb
					       length: 4];

		break;
	case 2:
		sb = (buf[i] << 16) | (buf[i + 1] << 8);

		tb[0] = of_base64_encode_table[(sb & 0xFC0000) >> 18];
		tb[1] = of_base64_encode_table[(sb & 0x03F000) >> 12];
		tb[2] = of_base64_encode_table[(sb & 0x000FC0) >> 6];
		tb[3] = '=';

		[ret appendCStringWithoutUTF8Checking: tb







|


|





|

|
|












|
|







|







36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
	 3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
	20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30,
	31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
	48, 49, 50, 51, -1, -1, -1, -1, -1
};

OFString*
of_base64_encode(const char *data, size_t length)
{
	OFMutableString *ret = [OFMutableString string];
	uint8_t *buffer = (uint8_t*)data;
	size_t i;
	uint8_t rest;
	char tb[4];
	uint32_t sb;

	rest = length % 3;

	for (i = 0; i < length - rest; i += 3) {
		sb = (buffer[i] << 16) | (buffer[i + 1] << 8) | buffer[i + 2];

		tb[0] = of_base64_encode_table[(sb & 0xFC0000) >> 18];
		tb[1] = of_base64_encode_table[(sb & 0x03F000) >> 12];
		tb[2] = of_base64_encode_table[(sb & 0x000FC0) >> 6];
		tb[3] = of_base64_encode_table[sb & 0x00003F];

		[ret appendCStringWithoutUTF8Checking: tb
					       length: 4];
	}

	switch (rest) {
	case 1:
		tb[0] = of_base64_encode_table[buffer[i] >> 2];
		tb[1] = of_base64_encode_table[(buffer[i] & 3) << 4];
		tb[2] = tb[3] = '=';

		[ret appendCStringWithoutUTF8Checking: tb
					       length: 4];

		break;
	case 2:
		sb = (buffer[i] << 16) | (buffer[i + 1] << 8);

		tb[0] = of_base64_encode_table[(sb & 0xFC0000) >> 18];
		tb[1] = of_base64_encode_table[(sb & 0x03F000) >> 12];
		tb[2] = of_base64_encode_table[(sb & 0x000FC0) >> 6];
		tb[3] = '=';

		[ret appendCStringWithoutUTF8Checking: tb
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
	 * would create a real copy each time -[copy] is called.
	 */
	ret->isa = [OFString class];
	return ret;
}

BOOL
of_base64_decode(OFDataArray *data, const char *str, size_t len)
{
	const uint8_t *buf = (const uint8_t*)str;
	size_t i;

	if ((len & 3) != 0)
		return NO;

	for (i = 0; i < len; i += 4) {
		uint32_t sb = 0;
		uint8_t cnt = 3;
		char db[3];
		char tmp;

		if (buf[i] > 0x7F || buf[i + 1] > 0x7F ||
		    buf[i + 2] > 0x7F || buf[i + 3] > 0x7F)
			return NO;

		if (buf[i] == '=' || buf[i + 1] == '=' ||
		    (buf[i + 2] == '=' && buf[i + 3] != '='))
			return NO;

		if (buf[i + 2] == '=')
			cnt--;
		if (buf[i + 3] == '=')
			cnt--;

		if ((tmp = of_base64_decode_table[buf[i]]) == -1)
			return NO;

		sb |= tmp << 18;

		if ((tmp = of_base64_decode_table[buf[i + 1]]) == -1)
			return NO;

		sb |= tmp << 12;

		if ((tmp = of_base64_decode_table[buf[i + 2]]) == -1)
			return NO;

		sb |= tmp << 6;

		if ((tmp = of_base64_decode_table[buf[i + 3]]) == -1)
			return NO;

		sb |= tmp;

		db[0] = (sb & 0xFF0000) >> 16;
		db[1] = (sb & 0x00FF00) >> 8;
		db[2] = sb & 0x0000FF;

		[data addNItems: cnt
		     fromCArray: db];
	}

	return YES;
}







|

|







|



|
|


|
|


|
|
|
|

|




|




|




|








|





93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
	 * would create a real copy each time -[copy] is called.
	 */
	ret->isa = [OFString class];
	return ret;
}

BOOL
of_base64_decode(OFDataArray *data, const char *cString, size_t len)
{
	const uint8_t *buffer = (const uint8_t*)cString;
	size_t i;

	if ((len & 3) != 0)
		return NO;

	for (i = 0; i < len; i += 4) {
		uint32_t sb = 0;
		uint8_t count = 3;
		char db[3];
		char tmp;

		if (buffer[i] > 0x7F || buffer[i + 1] > 0x7F ||
		    buffer[i + 2] > 0x7F || buffer[i + 3] > 0x7F)
			return NO;

		if (buffer[i] == '=' || buffer[i + 1] == '=' ||
		    (buffer[i + 2] == '=' && buffer[i + 3] != '='))
			return NO;

		if (buffer[i + 2] == '=')
			count--;
		if (buffer[i + 3] == '=')
			count--;

		if ((tmp = of_base64_decode_table[buffer[i]]) == -1)
			return NO;

		sb |= tmp << 18;

		if ((tmp = of_base64_decode_table[buffer[i + 1]]) == -1)
			return NO;

		sb |= tmp << 12;

		if ((tmp = of_base64_decode_table[buffer[i + 2]]) == -1)
			return NO;

		sb |= tmp << 6;

		if ((tmp = of_base64_decode_table[buffer[i + 3]]) == -1)
			return NO;

		sb |= tmp;

		db[0] = (sb & 0xFF0000) >> 16;
		db[1] = (sb & 0x00FF00) >> 8;
		db[2] = sb & 0x0000FF;

		[data addNItems: count
		     fromCArray: db];
	}

	return YES;
}

Modified src/foundation-compat.m from [233f316a15] to [f8a972ec13].

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
}

static void __attribute__((constructor))
init(void)
{
	Class NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
	Class NSObject = objc_getClass("NSObject");
	Method alloc_method;
	Method addObject_method;
	Method autorelease_method;

	if (NSAutoreleasePool == Nil || NSObject == Nil)
		return;

	alloc_method = class_getClassMethod(NSAutoreleasePool,
	    @selector(alloc));
	addObject_method = class_getClassMethod(NSAutoreleasePool,
	    @selector(addObject:));
	autorelease_method = class_getInstanceMethod(NSObject,
	    @selector(autorelease));

	if (alloc_method == NULL || addObject_method == NULL ||
	    autorelease_method == NULL)
		return;

	class_replaceMethod(NSAutoreleasePool->isa, @selector(alloc),
	    (IMP)alloc, method_getTypeEncoding(alloc_method));
	class_replaceMethod(NSAutoreleasePool->isa, @selector(addObject:),
	    (IMP)addObject, method_getTypeEncoding(addObject_method));
	class_replaceMethod(NSObject, @selector(autorelease),
	    (IMP)autorelease, method_getTypeEncoding(autorelease_method));
}







|
|
|




|

|

|


|
|



|

|

|

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
}

static void __attribute__((constructor))
init(void)
{
	Class NSAutoreleasePool = objc_getClass("NSAutoreleasePool");
	Class NSObject = objc_getClass("NSObject");
	Method allocMethod;
	Method addObjectMethod;
	Method autoreleaseMethod;

	if (NSAutoreleasePool == Nil || NSObject == Nil)
		return;

	allocMethod = class_getClassMethod(NSAutoreleasePool,
	    @selector(alloc));
	addObjectMethod = class_getClassMethod(NSAutoreleasePool,
	    @selector(addObject:));
	autoreleaseMethod = class_getInstanceMethod(NSObject,
	    @selector(autorelease));

	if (allocMethod == NULL || addObjectMethod == NULL ||
	    autoreleaseMethod == NULL)
		return;

	class_replaceMethod(NSAutoreleasePool->isa, @selector(alloc),
	    (IMP)alloc, method_getTypeEncoding(allocMethod));
	class_replaceMethod(NSAutoreleasePool->isa, @selector(addObject:),
	    (IMP)addObject, method_getTypeEncoding(addObjectMethod));
	class_replaceMethod(NSObject, @selector(autorelease),
	    (IMP)autorelease, method_getTypeEncoding(autoreleaseMethod));
}

Modified src/macros.h from [ab000dd8bb] to [eef3962225].

198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#else
# define of_bswap16(i) of_bswap16_const(i)
# define of_bswap32(i) of_bswap32_const(i)
# define of_bswap64(i) of_bswap64_const(i)
#endif

static OF_INLINE void
of_bswap32_vec(uint32_t *buf, size_t len)
{
	while (len--) {
		*buf = of_bswap32(*buf);
		buf++;
	}
}

#ifdef OF_BIG_ENDIAN
# define of_bswap16_if_be(i) of_bswap16(i)
# define of_bswap32_if_be(i) of_bswap32(i)
# define of_bswap64_if_be(i) of_bswap64(i)







|

|
|
|







198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#else
# define of_bswap16(i) of_bswap16_const(i)
# define of_bswap32(i) of_bswap32_const(i)
# define of_bswap64(i) of_bswap64_const(i)
#endif

static OF_INLINE void
of_bswap32_vec(uint32_t *buffer, size_t length)
{
	while (length--) {
		*buffer = of_bswap32(*buffer);
		buffer++;
	}
}

#ifdef OF_BIG_ENDIAN
# define of_bswap16_if_be(i) of_bswap16(i)
# define of_bswap32_if_be(i) of_bswap32(i)
# define of_bswap64_if_be(i) of_bswap64(i)
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# define of_bswap64_if_be(i) (i)
# define of_bswap16_if_le(i) of_bswap16(i)
# define of_bswap32_if_le(i) of_bswap32(i)
# define of_bswap64_if_le(i) of_bswap64(i)
# define of_bswap32_vec_if_be(buf, len)
#endif

#define OF_ROL(val, bits)						\
	(((val) << ((bits) % (sizeof(val) * 8))) |			\
	(val) >> (sizeof(val) * 8 - ((bits) % (sizeof(val) * 8))))

#define OF_HASH_INIT(hash) hash = 0
#define OF_HASH_ADD(hash, byte)		\
	{				\
		hash += (uint8_t)byte;	\
		hash += (hash << 10);	\
		hash ^= (hash >> 6);	\







|
|
|







224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# define of_bswap64_if_be(i) (i)
# define of_bswap16_if_le(i) of_bswap16(i)
# define of_bswap32_if_le(i) of_bswap32(i)
# define of_bswap64_if_le(i) of_bswap64(i)
# define of_bswap32_vec_if_be(buf, len)
#endif

#define OF_ROL(value, bits)						\
	(((value) << ((bits) % (sizeof(value) * 8))) |			\
	(value) >> (sizeof(value) * 8 - ((bits) % (sizeof(value) * 8))))

#define OF_HASH_INIT(hash) hash = 0
#define OF_HASH_ADD(hash, byte)		\
	{				\
		hash += (uint8_t)byte;	\
		hash += (hash << 10);	\
		hash ^= (hash >> 6);	\

Modified src/objc_sync.m from [4d687d4a25] to [9a5af0a0dd].

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# import <objfw-rt.h>
#else
# import <objc/objc.h>
#endif

#import "threading.h"

struct locks_s {
	id		 obj;
	size_t		 count;
	size_t		 recursion;
	of_thread_t	 thread;
	of_mutex_t	 mutex;
};

static of_mutex_t mutex;
static struct locks_s *locks = NULL;
static ssize_t num_locks = 0;

#define SYNC_ERR(f)							\
	{								\
		fprintf(stderr, "WARNING: %s failed in line %d!\n"	\
		    "WARNING: This might result in a race "		\
		    "condition!\n", f, __LINE__);			\
		return 1;						\
	}

BOOL
objc_sync_init(void)
{
	return of_mutex_new(&mutex);
}

int
objc_sync_enter(id obj)
{
	ssize_t i;

	if (obj == nil)
		return 0;

	if (!of_mutex_lock(&mutex))
		SYNC_ERR("of_mutex_lock(&mutex)");

	for (i = num_locks - 1; i >= 0; i--) {
		if (locks[i].obj == obj) {
			if (of_thread_is_current(locks[i].thread))
				locks[i].recursion++;
			else {
				/* Make sure objc_sync_exit doesn't free it */
				locks[i].count++;

				/* Unlock so objc_sync_exit can return */







|
|







|
|
















|









|
|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# import <objfw-rt.h>
#else
# import <objc/objc.h>
#endif

#import "threading.h"

struct lock_s {
	id		 object;
	size_t		 count;
	size_t		 recursion;
	of_thread_t	 thread;
	of_mutex_t	 mutex;
};

static of_mutex_t mutex;
static struct lock_s *locks = NULL;
static ssize_t numLocks = 0;

#define SYNC_ERR(f)							\
	{								\
		fprintf(stderr, "WARNING: %s failed in line %d!\n"	\
		    "WARNING: This might result in a race "		\
		    "condition!\n", f, __LINE__);			\
		return 1;						\
	}

BOOL
objc_sync_init(void)
{
	return of_mutex_new(&mutex);
}

int
objc_sync_enter(id object)
{
	ssize_t i;

	if (obj == nil)
		return 0;

	if (!of_mutex_lock(&mutex))
		SYNC_ERR("of_mutex_lock(&mutex)");

	for (i = numLocks - 1; i >= 0; i--) {
		if (locks[i].object == object) {
			if (of_thread_is_current(locks[i].thread))
				locks[i].recursion++;
			else {
				/* Make sure objc_sync_exit doesn't free it */
				locks[i].count++;

				/* Unlock so objc_sync_exit can return */
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
				SYNC_ERR("of_mutex_unlock(&mutex)");

			return 0;
		}
	}

	if (locks == NULL) {
		if ((locks = malloc(sizeof(struct locks_s))) == NULL) {
			of_mutex_unlock(&mutex);
			SYNC_ERR("malloc(...)");
		}
	} else {
		struct locks_s *new_locks;

		if ((new_locks = realloc(locks, (num_locks + 1) *
		    sizeof(struct locks_s))) == NULL) {
			of_mutex_unlock(&mutex);
			SYNC_ERR("realloc(...)");
		}

		locks = new_locks;
	}

	locks[num_locks].obj = obj;
	locks[num_locks].count = 1;
	locks[num_locks].recursion = 0;
	locks[num_locks].thread = of_thread_current();

	if (!of_mutex_new(&locks[num_locks].mutex)) {
		of_mutex_unlock(&mutex);
		SYNC_ERR("of_mutex_new(&locks[num_locks].mutex");
	}

	if (!of_mutex_lock(&locks[num_locks].mutex)) {
		of_mutex_unlock(&mutex);
		SYNC_ERR("of_mutex_lock(&locks[num_locks].mutex");
	}

	num_locks++;

	if (!of_mutex_unlock(&mutex))
		SYNC_ERR("of_mutex_unlock(&mutex)");

	return 0;
}

int
objc_sync_exit(id obj)
{
	ssize_t i;

	if (obj == nil)
		return 0;

	if (!of_mutex_lock(&mutex))
		SYNC_ERR("of_mutex_lock(&mutex)");

	for (i = num_locks - 1; i >= 0; i--) {
		if (locks[i].obj == obj) {
			if (locks[i].recursion > 0 &&
			    of_thread_is_current(locks[i].thread)) {
				locks[i].recursion--;

				if (!of_mutex_unlock(&mutex))
					SYNC_ERR("of_mutex_unlock(&mutex)");

				return 0;
			}

			if (!of_mutex_unlock(&locks[i].mutex)) {
				of_mutex_unlock(&mutex);
				SYNC_ERR("of_mutex_unlock(&locks[i].mutex)");
			}

			locks[i].count--;

			if (locks[i].count == 0) {
				struct locks_s *new_locks = NULL;

				if (!of_mutex_free(&locks[i].mutex)) {
					of_mutex_unlock(&mutex);
					SYNC_ERR(
					    "of_mutex_free(&locks[i].mutex");
				}

				num_locks--;
				locks[i] = locks[num_locks];

				if (num_locks == 0) {
					free(locks);
					new_locks = NULL;
				} else if ((new_locks = realloc(locks,
				    num_locks * sizeof(struct locks_s))) ==
				    NULL) {
					of_mutex_unlock(&mutex);
					SYNC_ERR("realloc(...)");
				}

				locks = new_locks;
			}







|




|

|
|







|
|
|
|

|

|


|

|


|








|



|





|
|


















|







|
|

|



|







96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
				SYNC_ERR("of_mutex_unlock(&mutex)");

			return 0;
		}
	}

	if (locks == NULL) {
		if ((locks = malloc(sizeof(struct lock_s))) == NULL) {
			of_mutex_unlock(&mutex);
			SYNC_ERR("malloc(...)");
		}
	} else {
		struct lock_s *new_locks;

		if ((new_locks = realloc(locks, (numLocks + 1) *
		    sizeof(struct lock_s))) == NULL) {
			of_mutex_unlock(&mutex);
			SYNC_ERR("realloc(...)");
		}

		locks = new_locks;
	}

	locks[numLocks].object = object;
	locks[numLocks].count = 1;
	locks[numLocks].recursion = 0;
	locks[numLocks].thread = of_thread_current();

	if (!of_mutex_new(&locks[numLocks].mutex)) {
		of_mutex_unlock(&mutex);
		SYNC_ERR("of_mutex_new(&locks[numLocks].mutex");
	}

	if (!of_mutex_lock(&locks[numLocks].mutex)) {
		of_mutex_unlock(&mutex);
		SYNC_ERR("of_mutex_lock(&locks[numLocks].mutex");
	}

	numLocks++;

	if (!of_mutex_unlock(&mutex))
		SYNC_ERR("of_mutex_unlock(&mutex)");

	return 0;
}

int
objc_sync_exit(id object)
{
	ssize_t i;

	if (object == nil)
		return 0;

	if (!of_mutex_lock(&mutex))
		SYNC_ERR("of_mutex_lock(&mutex)");

	for (i = numLocks - 1; i >= 0; i--) {
		if (locks[i].object == object) {
			if (locks[i].recursion > 0 &&
			    of_thread_is_current(locks[i].thread)) {
				locks[i].recursion--;

				if (!of_mutex_unlock(&mutex))
					SYNC_ERR("of_mutex_unlock(&mutex)");

				return 0;
			}

			if (!of_mutex_unlock(&locks[i].mutex)) {
				of_mutex_unlock(&mutex);
				SYNC_ERR("of_mutex_unlock(&locks[i].mutex)");
			}

			locks[i].count--;

			if (locks[i].count == 0) {
				struct lock_s *new_locks = NULL;

				if (!of_mutex_free(&locks[i].mutex)) {
					of_mutex_unlock(&mutex);
					SYNC_ERR(
					    "of_mutex_free(&locks[i].mutex");
				}

				numLocks--;
				locks[i] = locks[numLocks];

				if (numLocks == 0) {
					free(locks);
					new_locks = NULL;
				} else if ((new_locks = realloc(locks,
				    numLocks * sizeof(struct lock_s))) ==
				    NULL) {
					of_mutex_unlock(&mutex);
					SYNC_ERR("realloc(...)");
				}

				locks = new_locks;
			}

Modified src/of_asprintf.m from [983a2f4cc6] to [e2f58222ca].

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393

394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501

502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#include <stdbool.h>
#include <wchar.h>

#import "OFString.h"
#import "OFAutoreleasePool.h"
#import "asprintf.h"

#define MAX_SUBFMT_LEN 64

struct context {
	const char *fmt;
	size_t fmt_len;
	char subfmt[MAX_SUBFMT_LEN + 1];
	size_t subfmt_len;
	va_list args;
	char *buf;
	size_t buf_len;
	size_t i, last;
	enum {
		STATE_STRING,
		STATE_FORMAT_FLAGS,
		STATE_FORMAT_FIELD_WIDTH,
		STATE_FORMAT_LENGTH_MODIFIER,
		STATE_FORMAT_CONVERSION_SPECIFIER
	} state;
	enum {
		LENGTH_MODIFIER_NONE,
		LENGTH_MODIFIER_HH,
		LENGTH_MODIFIER_H,
		LENGTH_MODIFIER_L,
		LENGTH_MODIFIER_LL,
		LENGTH_MODIFIER_J,
		LENGTH_MODIFIER_Z,
		LENGTH_MODIFIER_T,
		LENGTH_MODIFIER_CAPITAL_L
	} len_mod;
};

static bool
append_str(struct context *ctx, const char *astr, size_t astr_len)
{
	char *nbuf;

	if (astr_len == 0)
		return true;

	if ((nbuf = realloc(ctx->buf, ctx->buf_len + astr_len + 1)) == NULL)

		return false;

	memcpy(nbuf + ctx->buf_len, astr, astr_len);

	ctx->buf = nbuf;
	ctx->buf_len += astr_len;

	return true;
}

static bool
append_subfmt(struct context *ctx, const char *asubfmt, size_t asubfmt_len)
{
	if (ctx->subfmt_len + asubfmt_len > MAX_SUBFMT_LEN)
		return false;

	memcpy(ctx->subfmt + ctx->subfmt_len, asubfmt, asubfmt_len);
	ctx->subfmt_len += asubfmt_len;
	ctx->subfmt[ctx->subfmt_len] = 0;

	return true;
}

static bool
state_string(struct context *ctx)
{
	if (ctx->fmt[ctx->i] == '%') {
		if (ctx->i > 0)
			if (!append_str(ctx, ctx->fmt + ctx->last,
			    ctx->i - ctx->last))
				return false;

		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		ctx->last = ctx->i + 1;
		ctx->state = STATE_FORMAT_FLAGS;
	}

	return true;
}

static bool
state_format_flags(struct context *ctx)
{
	switch (ctx->fmt[ctx->i]) {
	case '-':
	case '+':
	case ' ':
	case '#':
	case '0':
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		break;
	default:
		ctx->state = STATE_FORMAT_FIELD_WIDTH;
		ctx->i--;

		break;
	}

	return true;
}

static bool
state_format_field_width(struct context *ctx)
{
	if ((ctx->fmt[ctx->i] >= '0' && ctx->fmt[ctx->i] <= '9') ||
	    ctx->fmt[ctx->i] == '*' || ctx->fmt[ctx->i] == '.') {
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;
	} else {
		ctx->state = STATE_FORMAT_LENGTH_MODIFIER;
		ctx->i--;
	}

	return true;
}

static bool
state_format_length_modifier(struct context *ctx)
{
	/* Only one allowed */
	switch (ctx->fmt[ctx->i]) {
	case 'h': /* and also hh */

		if (ctx->fmt_len > ctx->i + 1 && ctx->fmt[ctx->i + 1] == 'h') {
			if (!append_subfmt(ctx, ctx->fmt + ctx->i, 2))
				return false;

			ctx->i++;
			ctx->len_mod = LENGTH_MODIFIER_HH;
		} else {
			if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
				return false;

			ctx->len_mod = LENGTH_MODIFIER_H;
		}

		break;
	case 'l': /* and also ll */

		if (ctx->fmt_len > ctx->i + 1 && ctx->fmt[ctx->i + 1] == 'l') {
			if (!append_subfmt(ctx, ctx->fmt + ctx->i, 2))
				return false;

			ctx->i++;
			ctx->len_mod = LENGTH_MODIFIER_LL;
		} else {
			if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
				return false;

			ctx->len_mod = LENGTH_MODIFIER_L;
		}

		break;
	case 'j':
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		ctx->len_mod = LENGTH_MODIFIER_J;

		break;
	case 'z':
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		ctx->len_mod = LENGTH_MODIFIER_Z;

		break;
	case 't':
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		ctx->len_mod = LENGTH_MODIFIER_T;

		break;
	case 'L':
		if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
			return false;

		ctx->len_mod = LENGTH_MODIFIER_CAPITAL_L;

		break;
	default:
		ctx->i--;

		break;
	}

	ctx->state = STATE_FORMAT_CONVERSION_SPECIFIER;
	return true;
}

static bool
state_format_conversion_specifier(struct context *ctx)
{
	char *tmp = NULL;
	int tmp_len = 0;

	if (!append_subfmt(ctx, ctx->fmt + ctx->i, 1))
		return false;

	switch (ctx->fmt[ctx->i]) {
	case '@':;
		OFAutoreleasePool *pool;

		ctx->subfmt[ctx->subfmt_len - 1] = 's';

		@try {
			pool = [[OFAutoreleasePool alloc] init];
		} @catch (id e) {
			[e release];
			return false;
		}

		@try {
			id obj;

			if ((obj = va_arg(ctx->args, id)) != nil)
				tmp_len = asprintf(&tmp, ctx->subfmt,
				    [[obj description] cString]);
			else
				tmp_len = asprintf(&tmp, ctx->subfmt, "(nil)");

		} @catch (id e) {
			free(ctx->buf);
			@throw e;
		} @finally {
			[pool release];
		}

		break;
	case 'd':
	case 'i':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_HH:
		case LENGTH_MODIFIER_H:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, int));
			break;
		case LENGTH_MODIFIER_L:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, long));
			break;
		case LENGTH_MODIFIER_LL:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, long long));
			break;
		case LENGTH_MODIFIER_J:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, intmax_t));
			break;
		case LENGTH_MODIFIER_Z:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, ssize_t));
			break;
		case LENGTH_MODIFIER_T:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, ptrdiff_t));
			break;
		default:
			return false;
		}

		break;
	case 'o':
	case 'u':
	case 'x':
	case 'X':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_HH:
		case LENGTH_MODIFIER_H:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, unsigned int));
			break;
		case LENGTH_MODIFIER_L:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, unsigned long));
			break;
		case LENGTH_MODIFIER_LL:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, unsigned long long));
			break;
		case LENGTH_MODIFIER_J:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, uintmax_t));
			break;
		case LENGTH_MODIFIER_Z:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, size_t));
			break;
		case LENGTH_MODIFIER_T:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, ptrdiff_t));
			break;
		default:
			return false;
		}

		break;
	case 'f':
	case 'F':
	case 'e':
	case 'E':
	case 'g':
	case 'G':
	case 'a':
	case 'A':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_L:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, double));
			break;
		case LENGTH_MODIFIER_CAPITAL_L:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, long double));
			break;
		default:
			return false;
		}

		break;
	case 'c':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, int));
			break;
		case LENGTH_MODIFIER_L:
#if WINT_MAX >= INT_MAX
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, wint_t));
#else
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, int));
#endif
			break;
		default:
			return false;
		}

		break;
	case 's':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, const char*));
			break;
		case LENGTH_MODIFIER_L:
			tmp_len = asprintf(&tmp, ctx->subfmt,
			    va_arg(ctx->args, const wchar_t*));
			break;
		default:
			return false;
		}

		break;
	case 'p':
		if (ctx->len_mod != LENGTH_MODIFIER_NONE)
			return false;

		tmp_len = asprintf(&tmp, ctx->subfmt, va_arg(ctx->args, void*));


		break;
	case 'n':
		switch (ctx->len_mod) {
		case LENGTH_MODIFIER_NONE:
			*va_arg(ctx->args, int*) = (int)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_HH:
			*va_arg(ctx->args, signed char*) =
			    (signed char)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_H:
			*va_arg(ctx->args, short*) = (short)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_L:
			*va_arg(ctx->args, long*) = (long)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_LL:
			*va_arg(ctx->args, long long*) =
			    (long long)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_J:

			*va_arg(ctx->args, intmax_t*) = (intmax_t)ctx->buf_len;
			break;
		case LENGTH_MODIFIER_Z:
			*va_arg(ctx->args, size_t*) = ctx->buf_len;
			break;
		case LENGTH_MODIFIER_T:
			*va_arg(ctx->args, ptrdiff_t*) =
			    (ptrdiff_t)ctx->buf_len;
			break;
		default:
			return false;
		}

		break;
	case '%':
		if (ctx->len_mod != LENGTH_MODIFIER_NONE)
			return false;

		if (!append_str(ctx, "%", 1))
			return false;

		break;
	default:
		return false;
	}

	if (tmp_len == -1)
		return false;

	if (tmp != NULL) {
		if (!append_str(ctx, tmp, tmp_len)) {
			free(tmp);
			return false;
		}

		free(tmp);
	}

	memset(ctx->subfmt, 0, MAX_SUBFMT_LEN);
	ctx->subfmt_len = 0;
	ctx->len_mod = LENGTH_MODIFIER_NONE;

	ctx->last = ctx->i + 1;
	ctx->state = STATE_STRING;

	return true;
}

static bool (*states[])(struct context*) = {
	state_string,
	state_format_flags,
	state_format_field_width,
	state_format_length_modifier,
	state_format_conversion_specifier
};

int
of_vasprintf(char **ret, const char *fmt, va_list args)
{
	struct context ctx;

	ctx.fmt = fmt;
	ctx.fmt_len = strlen(fmt);
	memset(ctx.subfmt, 0, MAX_SUBFMT_LEN + 1);
	ctx.subfmt_len = 0;
	va_copy(ctx.args, args);
	ctx.buf_len = 0;
	ctx.last = 0;
	ctx.state = STATE_STRING;
	ctx.len_mod = LENGTH_MODIFIER_NONE;

	if ((ctx.buf = malloc(1)) == NULL)
		return -1;

	for (ctx.i = 0; ctx.i < ctx.fmt_len; ctx.i++) {
		if (!states[ctx.state](&ctx)) {
			free(ctx.buf);
			return -1;
		}
	}

	if (ctx.state != STATE_STRING) {
		free(ctx.buf);
		return -1;
	}


	if (!append_str(&ctx, ctx.fmt + ctx.last, ctx.fmt_len - ctx.last)) {
		free(ctx.buf);
		return -1;
	}

	ctx.buf[ctx.buf_len] = 0;

	*ret = ctx.buf;
	return (ctx.buf_len <= INT_MAX ? (int)ctx.buf_len : INT_MAX);
}

int
of_asprintf(char **ret, const char *fmt, ...)
{
	va_list args;
	int r;

	va_start(args, fmt);
	r = of_vasprintf(ret, fmt, args);
	va_end(args);

	return r;
}







|


|
|
|
|
|
|
|


















|



|

|

|


|
>


|

|
|





|

|


|
|
|





|

|

|



|










|

|





|














|

|
|
|










|


|

>
|
|



|

|


|




>
|
|



|

|


|




|


|



|


|



|


|



|


|













|


|

|


|



|









|

|
|
|

|
>

|








|



|
|


|
|


|
|


|
|


|
|


|
|










|



|
|


|
|


|
|


|
|


|
|


|
|














|


|
|


|
|







|

|
|



|
|

|
|








|

|
|


|
|







|


|
>



|

|


|
|


|


|


|
|


>
|


|


|
|







|


|







|



|







|
|
|








|
|
|
|
|



|



|
|
|
|
|
|


|

|


|

|





|



>
|
|



|

|
|



|

|
|

|
|
|

|

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#include <stdbool.h>
#include <wchar.h>

#import "OFString.h"
#import "OFAutoreleasePool.h"
#import "asprintf.h"

#define MAX_SUBFORMAT_LEN 64

struct context {
	const char *format;
	size_t formatLen;
	char subformat[MAX_SUBFORMAT_LEN + 1];
	size_t subformatLen;
	va_list arguments;
	char *buffer;
	size_t bufferLen;
	size_t i, last;
	enum {
		STATE_STRING,
		STATE_FORMAT_FLAGS,
		STATE_FORMAT_FIELD_WIDTH,
		STATE_FORMAT_LENGTH_MODIFIER,
		STATE_FORMAT_CONVERSION_SPECIFIER
	} state;
	enum {
		LENGTH_MODIFIER_NONE,
		LENGTH_MODIFIER_HH,
		LENGTH_MODIFIER_H,
		LENGTH_MODIFIER_L,
		LENGTH_MODIFIER_LL,
		LENGTH_MODIFIER_J,
		LENGTH_MODIFIER_Z,
		LENGTH_MODIFIER_T,
		LENGTH_MODIFIER_CAPITAL_L
	} lengthModifier;
};

static bool
appendString(struct context *ctx, const char *append, size_t appendLen)
{
	char *nBuf;

	if (appendLen == 0)
		return true;

	if ((nBuf = realloc(ctx->buffer,
	    ctx->bufferLen + appendLen + 1)) == NULL)
		return false;

	memcpy(nBuf + ctx->bufferLen, append, appendLen);

	ctx->buffer = nBuf;
	ctx->bufferLen += appendLen;

	return true;
}

static bool
appendSubformat(struct context *ctx, const char *subformat, size_t subformatLen)
{
	if (ctx->subformatLen + subformatLen > MAX_SUBFORMAT_LEN)
		return false;

	memcpy(ctx->subformat + ctx->subformatLen, subformat, subformatLen);
	ctx->subformatLen += subformatLen;
	ctx->subformat[ctx->subformatLen] = 0;

	return true;
}

static bool
stringState(struct context *ctx)
{
	if (ctx->format[ctx->i] == '%') {
		if (ctx->i > 0)
			if (!appendString(ctx, ctx->format + ctx->last,
			    ctx->i - ctx->last))
				return false;

		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		ctx->last = ctx->i + 1;
		ctx->state = STATE_FORMAT_FLAGS;
	}

	return true;
}

static bool
formatFlagsState(struct context *ctx)
{
	switch (ctx->format[ctx->i]) {
	case '-':
	case '+':
	case ' ':
	case '#':
	case '0':
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		break;
	default:
		ctx->state = STATE_FORMAT_FIELD_WIDTH;
		ctx->i--;

		break;
	}

	return true;
}

static bool
formatFieldWidthState(struct context *ctx)
{
	if ((ctx->format[ctx->i] >= '0' && ctx->format[ctx->i] <= '9') ||
	    ctx->format[ctx->i] == '*' || ctx->format[ctx->i] == '.') {
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;
	} else {
		ctx->state = STATE_FORMAT_LENGTH_MODIFIER;
		ctx->i--;
	}

	return true;
}

static bool
formatLengthModifierState(struct context *ctx)
{
	/* Only one allowed */
	switch (ctx->format[ctx->i]) {
	case 'h': /* and also hh */
		if (ctx->formatLen > ctx->i + 1 &&
		    ctx->format[ctx->i + 1] == 'h') {
			if (!appendSubformat(ctx, ctx->format + ctx->i, 2))
				return false;

			ctx->i++;
			ctx->lengthModifier = LENGTH_MODIFIER_HH;
		} else {
			if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
				return false;

			ctx->lengthModifier = LENGTH_MODIFIER_H;
		}

		break;
	case 'l': /* and also ll */
		if (ctx->formatLen > ctx->i + 1 &&
		    ctx->format[ctx->i + 1] == 'l') {
			if (!appendSubformat(ctx, ctx->format + ctx->i, 2))
				return false;

			ctx->i++;
			ctx->lengthModifier = LENGTH_MODIFIER_LL;
		} else {
			if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
				return false;

			ctx->lengthModifier = LENGTH_MODIFIER_L;
		}

		break;
	case 'j':
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		ctx->lengthModifier = LENGTH_MODIFIER_J;

		break;
	case 'z':
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		ctx->lengthModifier = LENGTH_MODIFIER_Z;

		break;
	case 't':
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		ctx->lengthModifier = LENGTH_MODIFIER_T;

		break;
	case 'L':
		if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
			return false;

		ctx->lengthModifier = LENGTH_MODIFIER_CAPITAL_L;

		break;
	default:
		ctx->i--;

		break;
	}

	ctx->state = STATE_FORMAT_CONVERSION_SPECIFIER;
	return true;
}

static bool
formatConversionSpecifierState(struct context *ctx)
{
	char *tmp = NULL;
	int tmpLen = 0;

	if (!appendSubformat(ctx, ctx->format + ctx->i, 1))
		return false;

	switch (ctx->format[ctx->i]) {
	case '@':;
		OFAutoreleasePool *pool;

		ctx->subformat[ctx->subformatLen - 1] = 's';

		@try {
			pool = [[OFAutoreleasePool alloc] init];
		} @catch (id e) {
			[e release];
			return false;
		}

		@try {
			id object;

			if ((object = va_arg(ctx->arguments, id)) != nil)
				tmpLen = asprintf(&tmp, ctx->subformat,
				    [[object description] cString]);
			else
				tmpLen = asprintf(&tmp, ctx->subformat,
				    "(nil)");
		} @catch (id e) {
			free(ctx->buffer);
			@throw e;
		} @finally {
			[pool release];
		}

		break;
	case 'd':
	case 'i':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_HH:
		case LENGTH_MODIFIER_H:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, int));
			break;
		case LENGTH_MODIFIER_L:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, long));
			break;
		case LENGTH_MODIFIER_LL:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, long long));
			break;
		case LENGTH_MODIFIER_J:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, intmax_t));
			break;
		case LENGTH_MODIFIER_Z:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, ssize_t));
			break;
		case LENGTH_MODIFIER_T:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, ptrdiff_t));
			break;
		default:
			return false;
		}

		break;
	case 'o':
	case 'u':
	case 'x':
	case 'X':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_HH:
		case LENGTH_MODIFIER_H:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, unsigned int));
			break;
		case LENGTH_MODIFIER_L:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, unsigned long));
			break;
		case LENGTH_MODIFIER_LL:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, unsigned long long));
			break;
		case LENGTH_MODIFIER_J:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, uintmax_t));
			break;
		case LENGTH_MODIFIER_Z:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, size_t));
			break;
		case LENGTH_MODIFIER_T:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, ptrdiff_t));
			break;
		default:
			return false;
		}

		break;
	case 'f':
	case 'F':
	case 'e':
	case 'E':
	case 'g':
	case 'G':
	case 'a':
	case 'A':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
		case LENGTH_MODIFIER_L:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, double));
			break;
		case LENGTH_MODIFIER_CAPITAL_L:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, long double));
			break;
		default:
			return false;
		}

		break;
	case 'c':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, int));
			break;
		case LENGTH_MODIFIER_L:
#if WINT_MAX >= INT_MAX
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, wint_t));
#else
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, int));
#endif
			break;
		default:
			return false;
		}

		break;
	case 's':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, const char*));
			break;
		case LENGTH_MODIFIER_L:
			tmpLen = asprintf(&tmp, ctx->subformat,
			    va_arg(ctx->arguments, const wchar_t*));
			break;
		default:
			return false;
		}

		break;
	case 'p':
		if (ctx->lengthModifier != LENGTH_MODIFIER_NONE)
			return false;

		tmpLen = asprintf(&tmp, ctx->subformat,
		    va_arg(ctx->arguments, void*));

		break;
	case 'n':
		switch (ctx->lengthModifier) {
		case LENGTH_MODIFIER_NONE:
			*va_arg(ctx->arguments, int*) = (int)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_HH:
			*va_arg(ctx->arguments, signed char*) =
			    (signed char)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_H:
			*va_arg(ctx->arguments, short*) = (short)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_L:
			*va_arg(ctx->arguments, long*) = (long)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_LL:
			*va_arg(ctx->arguments, long long*) =
			    (long long)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_J:
			*va_arg(ctx->arguments, intmax_t*) =
			    (intmax_t)ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_Z:
			*va_arg(ctx->arguments, size_t*) = ctx->bufferLen;
			break;
		case LENGTH_MODIFIER_T:
			*va_arg(ctx->arguments, ptrdiff_t*) =
			    (ptrdiff_t)ctx->bufferLen;
			break;
		default:
			return false;
		}

		break;
	case '%':
		if (ctx->lengthModifier != LENGTH_MODIFIER_NONE)
			return false;

		if (!appendString(ctx, "%", 1))
			return false;

		break;
	default:
		return false;
	}

	if (tmpLen == -1)
		return false;

	if (tmp != NULL) {
		if (!appendString(ctx, tmp, tmpLen)) {
			free(tmp);
			return false;
		}

		free(tmp);
	}

	memset(ctx->subformat, 0, MAX_SUBFORMAT_LEN);
	ctx->subformatLen = 0;
	ctx->lengthModifier = LENGTH_MODIFIER_NONE;

	ctx->last = ctx->i + 1;
	ctx->state = STATE_STRING;

	return true;
}

static bool (*states[])(struct context*) = {
	stringState,
	formatFlagsState,
	formatFieldWidthState,
	formatLengthModifierState,
	formatConversionSpecifierState
};

int
of_vasprintf(char **cString, const char *format, va_list arguments)
{
	struct context ctx;

	ctx.format = format;
	ctx.formatLen = strlen(format);
	memset(ctx.subformat, 0, MAX_SUBFORMAT_LEN + 1);
	ctx.subformatLen = 0;
	va_copy(ctx.arguments, arguments);
	ctx.bufferLen = 0;
	ctx.last = 0;
	ctx.state = STATE_STRING;
	ctx.lengthModifier = LENGTH_MODIFIER_NONE;

	if ((ctx.buffer = malloc(1)) == NULL)
		return -1;

	for (ctx.i = 0; ctx.i < ctx.formatLen; ctx.i++) {
		if (!states[ctx.state](&ctx)) {
			free(ctx.buffer);
			return -1;
		}
	}

	if (ctx.state != STATE_STRING) {
		free(ctx.buffer);
		return -1;
	}

	if (!appendString(&ctx, ctx.format + ctx.last,
	    ctx.formatLen - ctx.last)) {
		free(ctx.buffer);
		return -1;
	}

	ctx.buffer[ctx.bufferLen] = 0;

	*cString = ctx.buffer;
	return (ctx.bufferLen <= INT_MAX ? (int)ctx.bufferLen : -1);
}

int
of_asprintf(char **cString, const char *format, ...)
{
	va_list arguments;
	int ret;

	va_start(arguments, format);
	ret = of_vasprintf(cString, format, arguments);
	va_end(arguments);

	return ret;
}

Modified src/threading.h from [c1d87def31] to [ffa37b7f10].

282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

	return (id)ret;
}

static OF_INLINE BOOL
of_tlskey_set(of_tlskey_t key, id obj)
{
	void *p = (obj != nil ? (void*)obj : NULL);

#if defined(OF_HAVE_PTHREADS)
	return !pthread_setspecific(key, p);
#elif defined(_WIN32)
	return TlsSetValue(key, p);
#endif
}

static OF_INLINE BOOL
of_tlskey_free(of_tlskey_t key)
{
#if defined(OF_HAVE_PTHREADS)
	return !pthread_key_delete(key);
#elif defined(_WIN32)
	return TlsFree(key);
#endif
}

static OF_INLINE BOOL
of_spinlock_new(of_spinlock_t *s)
{
#if defined(OF_ATOMIC_OPS)
	*s = 0;
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_init(s, 0);
#else
	return of_mutex_new(s);
#endif
}

static OF_INLINE BOOL
of_spinlock_trylock(of_spinlock_t *s)
{
#if defined(OF_ATOMIC_OPS)
	return of_atomic_cmpswap_int(s, 0, 1);
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_trylock(s);
#else
	return of_mutex_trylock(s);
#endif
}

static OF_INLINE BOOL
of_spinlock_lock(of_spinlock_t *s)
{
#if defined(OF_ATOMIC_OPS)
# if defined(OF_HAVE_SCHED_YIELD) || defined(_WIN32)
	int i;

	for (i = 0; i < OF_SPINCOUNT; i++)
		if (of_spinlock_trylock(s))
			return YES;

	while (!of_spinlock_trylock(s))
#  ifndef _WIN32
		sched_yield();
#  else
		Sleep(0);
#  endif
# else
	while (!of_spinlock_trylock(s));
# endif

	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_lock(s);
#else
	return of_mutex_lock(s);
#endif
}

static OF_INLINE BOOL
of_spinlock_unlock(of_spinlock_t *s)
{
#if defined(OF_ATOMIC_OPS)
	*s = 0;
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_unlock(s);
#else
	return of_mutex_unlock(s);
#endif
}

static OF_INLINE BOOL
of_spinlock_free(of_spinlock_t *s)
{
#if defined(OF_ATOMIC_OPS)
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_destroy(s);
#else
	return of_mutex_free(s);
#endif
}







|


|

|














|


|


|

|




|


|

|

|




|






|


|






|




|

|




|


|


|

|




|




|

|


282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

	return (id)ret;
}

static OF_INLINE BOOL
of_tlskey_set(of_tlskey_t key, id obj)
{
	void *ptr = (obj != nil ? (void*)obj : NULL);

#if defined(OF_HAVE_PTHREADS)
	return !pthread_setspecific(key, ptr);
#elif defined(_WIN32)
	return TlsSetValue(key, ptr);
#endif
}

static OF_INLINE BOOL
of_tlskey_free(of_tlskey_t key)
{
#if defined(OF_HAVE_PTHREADS)
	return !pthread_key_delete(key);
#elif defined(_WIN32)
	return TlsFree(key);
#endif
}

static OF_INLINE BOOL
of_spinlock_new(of_spinlock_t *spinlock)
{
#if defined(OF_ATOMIC_OPS)
	*spinlock = 0;
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_init(spinlock, 0);
#else
	return of_mutex_new(spinlock);
#endif
}

static OF_INLINE BOOL
of_spinlock_trylock(of_spinlock_t *spinlock)
{
#if defined(OF_ATOMIC_OPS)
	return of_atomic_cmpswap_int(spinlock, 0, 1);
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_trylock(spinlock);
#else
	return of_mutex_trylock(spinlock);
#endif
}

static OF_INLINE BOOL
of_spinlock_lock(of_spinlock_t *spinlock)
{
#if defined(OF_ATOMIC_OPS)
# if defined(OF_HAVE_SCHED_YIELD) || defined(_WIN32)
	int i;

	for (i = 0; i < OF_SPINCOUNT; i++)
		if (of_spinlock_trylock(spinlock))
			return YES;

	while (!of_spinlock_trylock(spinlock))
#  ifndef _WIN32
		sched_yield();
#  else
		Sleep(0);
#  endif
# else
	while (!of_spinlock_trylock(spinlock));
# endif

	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_lock(spinlock);
#else
	return of_mutex_lock(spinlock);
#endif
}

static OF_INLINE BOOL
of_spinlock_unlock(of_spinlock_t *spinlock)
{
#if defined(OF_ATOMIC_OPS)
	*spinlock = 0;
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_unlock(spinlock);
#else
	return of_mutex_unlock(spinlock);
#endif
}

static OF_INLINE BOOL
of_spinlock_free(of_spinlock_t *spinlock)
{
#if defined(OF_ATOMIC_OPS)
	return YES;
#elif defined(OF_HAVE_PTHREAD_SPINLOCKS)
	return !pthread_spin_destroy(spinlock);
#else
	return of_mutex_free(spinlock);
#endif
}

Modified tests/OFXMLParserTests.m from [1a865f21e8] to [1737f2bda6].

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366

	for (j = 0; j < len; j+= 2) {
		if ([parser finishedParsing])
			abort();

		if (j + 2 > len)
			[parser parseBuffer: str + j
				   withSize: 1];
		else
			[parser parseBuffer: str + j
				   withSize: 2];
	}

	TEST(@"Checking if everything was parsed",
	    i == 32 && [parser lineNumber] == 18)

	TEST(@"-[finishedParsing]", [parser finishedParsing])








|


|







349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366

	for (j = 0; j < len; j+= 2) {
		if ([parser finishedParsing])
			abort();

		if (j + 2 > len)
			[parser parseBuffer: str + j
				 withLength: 1];
		else
			[parser parseBuffer: str + j
				 withLength: 2];
	}

	TEST(@"Checking if everything was parsed",
	    i == 32 && [parser lineNumber] == 18)

	TEST(@"-[finishedParsing]", [parser finishedParsing])