~ubuntu-branches/ubuntu/edgy/sope/edgy

« back to all changes in this revision

Viewing changes to libFoundation/doc/libFoundation.texi

  • Committer: Bazaar Package Importer
  • Author(s): Sebastian Ley
  • Date: 2005-08-19 16:53:31 UTC
  • Revision ID: james.westby@ubuntu.com-20050819165331-hs683wz1osm708pw
Tags: upstream-4.4rc.2
ImportĀ upstreamĀ versionĀ 4.4rc.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
\input texinfo
 
2
 
 
3
@c %**start of header
 
4
@settitle libFoundation Library Manual
 
5
@setfilename libFoundation.info
 
6
@c %**end of header
 
7
 
 
8
 
 
9
@set version 0.9.0
 
10
@set update-month October 1998
 
11
 
 
12
@ifinfo
 
13
@format
 
14
START-INFO-DIR-ENTRY
 
15
* libFoundation::                      An OpenStep Foundation library.
 
16
END-INFO-DIR-ENTRY
 
17
@end format
 
18
@end ifinfo
 
19
 
 
20
@ifinfo
 
21
This file documents the features of the libFoundation library.
 
22
 
 
23
Copyright (C) 1995, 1996, 1997, 1998 Ovidiu Predescu and Mircea Oancea.
 
24
All rights reserved.
 
25
 
 
26
Permission to use, copy, modify, and distribute this software and its
 
27
documentation for ANY purpose and without fee is hereby granted,
 
28
provided that the above copyright notice appear in all copies and that
 
29
both that copyright notice and this permission notice appear in
 
30
supporting documentation. This softare may be included in any commercial
 
31
product provided that its distribution contain the libFoundation
 
32
copyright notice and this permission notice.
 
33
 
 
34
@sp 2
 
35
 
 
36
The libFoundation Library Manual may be reproduced and distributed in
 
37
whole or in part, in any medium, physical or electronic, so long as this
 
38
copyright notice remains intact and unchanged on all copies.
 
39
 
 
40
@end ifinfo
 
41
 
 
42
 
 
43
@iftex
 
44
@finalout
 
45
@c @smallbook
 
46
@end iftex
 
47
 
 
48
@titlepage
 
49
@title libFoundation Library Manual
 
50
@subtitle for libFoundation version @value{version}
 
51
@subtitle @value{update-month}
 
52
@author by Ovidiu Predescu and Mircea Oancea 
 
53
@page
 
54
 
 
55
@vskip 0pt plus 1filll
 
56
 
 
57
Copyright @copyright{} 1995, 1996, 1997, 1998 Ovidiu Predescu and Mircea
 
58
Oancea.  All rights reserved.
 
59
 
 
60
Permission to use, copy, modify, and distribute this software and its
 
61
documentation for ANY purpose and without fee is hereby granted,
 
62
provided that the above copyright notice appear in all copies and that
 
63
both that copyright notice and this permission notice appear in
 
64
supporting documentation. This softare may be included in any commercial
 
65
product provided that its distribution contain the libFoundation
 
66
copyright notice and this permission notice.
 
67
 
 
68
@sp 2
 
69
 
 
70
The libFoundation Library Manual may be reproduced and distributed in
 
71
whole or in part, in any medium, physical or electronic, so long as this
 
72
copyright notice remains intact and unchanged on all copies.
 
73
 
 
74
@end titlepage
 
75
 
 
76
@tex
 
77
\global\parindent 0pt
 
78
\global\parskip 8pt plus 2pt
 
79
@end tex
 
80
 
 
81
 
 
82
 
 
83
@ifinfo
 
84
@node    Top, Introduction, (dir), (dir)
 
85
@comment node-name,     next,           previous,       up
 
86
@top Top
 
87
@end ifinfo
 
88
 
 
89
@menu
 
90
* Introduction::                About libFoundation and this documentation.
 
91
* Coding with libFoundation::   How to write code for libFoundation.
 
92
* Exception handling::          The extended exception handling mechanism.
 
93
* Garbage collecting::          Two garbage collecting techniques.
 
94
* NSZone::                      Implementation details.
 
95
* NSInvocation::                Features of the NSInvocation class.
 
96
* NSMethodSignature::           Features of the NSMethodSignature class.
 
97
@end menu
 
98
 
 
99
 
 
100
@c =========================================================================
 
101
@node    Introduction, Coding with libFoundation, Top, Top
 
102
@comment node-name, next, previous, up
 
103
 
 
104
@chapter Introduction
 
105
 
 
106
This document describes some of the features and particularities
 
107
implemented in @emph{libFoundation}; they are also available in the
 
108
FoundationExtensions library so that users of @emph{libFoundation} can
 
109
use their code with other OpenStep Foundation implementations.
 
110
 
 
111
This documentation does not provide yet a full description of all the
 
112
classes throughout the library. However any documentation that describes
 
113
the OpenStep's Foundation library should be good enough for the classes
 
114
implemented by @emph{libFoundation}.
 
115
 
 
116
Below are some resources that provide additional information about the
 
117
OpenStep Foundation classes:
 
118
 
 
119
@itemize @bullet
 
120
 
 
121
@item
 
122
The original OpenStep specification can be found at:
 
123
 
 
124
@uref{http://www.gnustep.org/GNUOpenStep/OpenStepSpec/OpenStepSpec.html}.
 
125
 
 
126
@item
 
127
OPENSTEP/Rhapsody related documentation, you can find here a very good
 
128
documentation for Foundation:
 
129
 
 
130
@uref{http://developer.apple.com/techpubs/rhapsody/rhapsody.html}.
 
131
 
 
132
@item
 
133
The GNUstep site, @uref{http://www.gnustep.org} or the European
 
134
mirror-site,
 
135
 
 
136
@uref{http://www.nmr.embl-heidelberg.de/GNUstep}.
 
137
 
 
138
@end itemize
 
139
 
 
140
 
 
141
@c =========================================================================
 
142
@node    Coding with libFoundation, Preprocessor defines, Introduction, Top
 
143
@comment node-name, next, previous, up
 
144
@chapter Coding with libFoundation
 
145
 
 
146
There are some things one has to know when porting an OpenStep program
 
147
to work with @emph{libFoundation}. These things do not change the
 
148
general behavior of the program, they only make the program work
 
149
properly with the library.
 
150
 
 
151
@menu
 
152
* Preprocessor defines::
 
153
* Initializing your program::
 
154
* Specifying the resources directory::
 
155
* Objective-C runtime support::
 
156
@end menu
 
157
 
 
158
 
 
159
@c =========================================================================
 
160
@node    Preprocessor defines, Initializing your program, Coding with libFoundation, Coding with libFoundation
 
161
@comment node-name, next, previous, up
 
162
 
 
163
@section Preprocessor defines
 
164
 
 
165
@emph{libFoundation} defines some preprocessor values so you can check
 
166
for them if you want to conditionally pass some code to the
 
167
compiler. The following macros are defined in
 
168
@code{Foundation/NSObject.h}:
 
169
 
 
170
@example
 
171
#define LIB_FOUNDATION_LIBRARY 1
 
172
    
 
173
#define LIB_FOUNDATION_MAJOR_VERSION 0
 
174
#define LIB_FOUNDATION_MINOR_VERSION 9
 
175
#define LIB_FOUNDATION_SUBMINOR_VERSION 0
 
176
@end example
 
177
 
 
178
If you want to include a portion of code that is specific to
 
179
@emph{libFoundation} you should put it inside an @code{#ifdef}
 
180
preprocessor command:
 
181
 
 
182
@example
 
183
#ifdef LIB_FOUNDATION_LIBRARY
 
184
...
 
185
#endif
 
186
@end example
 
187
 
 
188
This way you the code inside @code{#ifdef} is compiled only in the
 
189
presence of @emph{libFoundation} and will not affect other libraries.
 
190
 
 
191
Another macro which is defined only when the Boehm's garbage collector
 
192
is used (@xref{Boehm garbage collector}) is
 
193
@code{LIB_FOUNDATION_BOEHM_GC}. You can use it to check in your code
 
194
whether the code is compiled with support for Boehm's garbage collector
 
195
or not.
 
196
 
 
197
@c =========================================================================
 
198
@node    Initializing your program, Specifying the resources directory, Preprocessor defines, Coding with libFoundation
 
199
@comment node-name, next, previous, up
 
200
 
 
201
@section Initializing your program
 
202
 
 
203
It is very important to properly initialize some @emph{libFoundation}
 
204
internal data structures when the program starts. These information
 
205
are mainly related to the @code{NSProcessInfo} class. Because not on all
 
206
platforms is possible to find out the arguments and the environment
 
207
variables passed to the program, we have chosen to explicitly delegate
 
208
this task to user. The first lines in a @emph{libFoundation} program,
 
209
before creating any other objects, should be the following:
 
210
 
 
211
@example
 
212
int main (int argc, char** argv, char** env)
 
213
@{
 
214
    /* Declarations here */
 
215
...
 
216
 
 
217
#ifdef LIB_FOUNDATION_LIBRARY
 
218
    [NSProcessInfo initializeWithArguments:argv
 
219
                   count:argc
 
220
                   environment:env];
 
221
#endif
 
222
 
 
223
    /* Objects initialization and other instructions here */
 
224
    ...
 
225
@}
 
226
@end example 
 
227
 
 
228
@c =========================================================================
 
229
@node    Specifying the resources directory, Objective-C runtime support, Initializing your program, Coding with libFoundation
 
230
@comment node-name, next, previous, up
 
231
 
 
232
@section Specifying the resources directory
 
233
 
 
234
It is common to want to try the tests before you have installed the
 
235
library in its default place. @emph{libFoundation} however requires to
 
236
have access to the resource files to function correctly. You can install
 
237
only the resources in the installation directory, but there is a more
 
238
convenient way to let the library where are its resources. You can
 
239
specify an environment variable that indicates where is the resource
 
240
directory; the name of this variable is
 
241
@code{LIB_FOUNDATION_RESOURCES_PATH} and it should indicate the
 
242
@code{Resources} directory. In a @code{sh}-like shell for example, you can do:
 
243
 
 
244
@example
 
245
LIB_FOUNDATION_RESOURCES_PATH=/home/ovidiu\
 
246
        /libFoundation-@value{version}/libFoundation/Resources
 
247
export LIB_FOUNDATION_RESOURCES_PATH
 
248
@end example
 
249
 
 
250
This environment variable is similar with the @code{PATH} variable: you
 
251
can specify more directories by separating them using @code{:}
 
252
character. Specifying resource directories this way takes precedence
 
253
over the default installation directory. You can use this to change the
 
254
resources if you want.
 
255
 
 
256
 
 
257
@c =========================================================================
 
258
@node    Objective-C runtime support, Exception handling, Specifying the resources directory, Coding with libFoundation
 
259
@comment node-name, next, previous, up
 
260
 
 
261
@section Objective-C runtime support
 
262
 
 
263
Currently there are two different Objective-C runtimes supported by
 
264
@emph{libFoundation}: the original NeXT runtime and the GNU runtime
 
265
which is modelled after it.
 
266
 
 
267
The differences between the two runtimes resides mainly in the naming of
 
268
functions. However there are differences that make the two runtimes
 
269
incompatible. The most important one is how the selectors are kept.
 
270
 
 
271
On NeXT runtime a selector is simply a unique string that represents its
 
272
name. On GNU runtime, a selector is a structure consisting from a
 
273
selector id (that is not its name) and a string describing its
 
274
types. The both approaches have advantages and disadvantages. In the
 
275
NeXT approach no matter how many times you request a selector (either
 
276
using the @code{@@selector} directive or by @code{sel_getUid()}, you get
 
277
the same selector. This is possible because the selector is simply
 
278
represented as a unique string. On the GNU runtime each time you request
 
279
a selector using the @code{@@selector} directive you get a different
 
280
selector. Moreover the obtained selector has the @code{types} member set
 
281
to @code{NULL}.
 
282
 
 
283
In the NeXT approach the encoding of the selector's types are bound to
 
284
each class that has a corresponding method. In the GNU approach the
 
285
selector's types are bound to the selector.
 
286
 
 
287
This differences have deep implication on how the @code{NSProxy} class
 
288
handle a method call in the @code{forwardInvocation:} method. On the
 
289
NeXT runtime, the proxy should make a request to the remote side to
 
290
obtain the types of the method. The types are used locally by a
 
291
@code{NSMethodSignature} object to determine an encoding. This encoding
 
292
is used to access correctly the arguments on the stack. However you have
 
293
the possibility to set a protocol to the @code{NSProxy} object at which
 
294
the remote object answer. This should be done to avoid asking the true
 
295
object about its selector types and so to increase performance.
 
296
 
 
297
On the GNU runtime this is not necessarily because in the
 
298
@code{forwardInvocation:} method the selector usually comes with types
 
299
in it. However there are cases when this is not true and the same
 
300
mechanism like in the NeXT case should be applied.
 
301
 
 
302
Because the remote machine could be different than the local one, the
 
303
@code{NSMethodSignature} class should be able to create the correct
 
304
encoding from the types received from remote. Thus the
 
305
@code{NSMethodSignature} class is dependent on the target machine.
 
306
 
 
307
This implementation of Foundation works with both runtimes. The
 
308
@code{extensions/objc-runtime.h} file defines the runtime functions to
 
309
be those from the GNU runtime. All the NeXT runtime functions are
 
310
defined in terms of GNU runtime functions.
 
311
 
 
312
In order to write portable programs for both runtimes you should never
 
313
use functions in the GNU runtime that work with the types associated
 
314
with the selector. So the @code{sel_get_type}, @code{sel_get_any_uid}
 
315
and @code{sel_get_typed_uid} cannot be used in programs. Also you should
 
316
never use functions like @code{objc_msgSend} or
 
317
@code{objc_msgSendv}. Use the @code{objc_msg_sendv} function or the
 
318
@code{NSInvocation} class instead.
 
319
 
 
320
Never use types like @code{Method} in the NeXT runtime or
 
321
@code{Method_t} in the GNU runtime. Use instead the type @code{struct
 
322
objc_method*}. This exists in both runtimes.
 
323
 
 
324
 
 
325
@c =========================================================================
 
326
@node    Exception handling, Garbage collecting, Objective-C runtime support, Top
 
327
@comment node-name, next, previous, up
 
328
 
 
329
@chapter Exception handling
 
330
 
 
331
The exception handling mechanism provides several powerful features
 
332
found in languages like C++ or Java. It extends the normal OpenStep
 
333
exception handling, while still maintaining the backward compatibility
 
334
with this. A program using the extended exception handling mechanism is
 
335
still able to work with the normal OpenStep exception handling and
 
336
viceversa.
 
337
 
 
338
The first powerful feature is that you have exceptions grouped by
 
339
classes. This means you can group exceptions in a hierarchy; not only
 
340
a tree like but even as a general graph. This feature is present in
 
341
C++ and with some restrictions in Java.
 
342
 
 
343
Another feature is that the exception handler is called as a
 
344
function. So if you are in debugger you can see the whole stack frame
 
345
from the point that generated the exception up to the exception
 
346
handler. So you are able to see what were the conditions that made the
 
347
exception to be raised.
 
348
 
 
349
The actual mechanism is based on nested functions, an extension to the
 
350
C language. This extension is currently supported by the GNU C
 
351
Compiler. The actual mechanism is written using macros, so there is no
 
352
need for special support from the compiler.
 
353
 
 
354
A code written using these macros looks like this:
 
355
 
 
356
@example
 
357
 
 
358
TRY @{
 
359
    some code that can generate an exception
 
360
@} END_TRY
 
361
CATCH(ExceptionClass1) @{
 
362
    code to handle an exception of class ExceptionClass1
 
363
@}
 
364
CATCH(ExceptionClass2) @{
 
365
    code to handle an exception of class ExceptionClass2
 
366
@}
 
367
...
 
368
OTHERWISE @{
 
369
    catch all exceptions not handled above
 
370
@}
 
371
END_CATCH
 
372
 
 
373
@end example
 
374
 
 
375
In the @code{TRY} block the code that is supposed to generate an
 
376
exception is executed. You can nest @code{TRY} blocks by entering other
 
377
blocks of code in @code{TRY} blocks. All @code{TRY} blocks form a stack
 
378
with the most recent @code{TRY} block which is executing on the top of
 
379
the stack.
 
380
 
 
381
If nothing happens during the execution of code inside a @code{TRY}
 
382
block, the program continues with the first statement after the
 
383
@code{END_CATCH} label. When this thing happens the topmost @code{TRY}
 
384
block is popped off the exception handlers stack.
 
385
 
 
386
To generate an exception you should allocate an exception object and
 
387
pass it to the @code{THROW} function. This is called raising an
 
388
exception. When an exception is raised the exception handler blocks are
 
389
searched for the one that can @emph{catch} the exception. This means to
 
390
find the first @code{CATCH} block that match the exception object
 
391
class. This matching is done by sending the exception object the
 
392
@code{exceptionIsKindOf:} message having as argument the class specified
 
393
as parameter to @code{CATCH} block. If the result of this message is
 
394
true then the @code{CATCH} block matches the exception.
 
395
 
 
396
The @code{exceptionIsKindOf:} method is implemented at the
 
397
@code{NSException} class to return the result of @code{isKindOf:}. So
 
398
implicitly the exceptions are grouped after their inheritance
 
399
hierarchy. Some specific exception classes could implement the
 
400
@code{exceptionIsKindOf:} method and simulate a graph inheritance, which
 
401
is like the multiple inheritance in C++.
 
402
 
 
403
Inside the @code{CATCH} and @code{OTHERWISE} blocks you have one hidden
 
404
parameter, the exception object, which has the name
 
405
@code{localException}. You can do the following actions inside an
 
406
exception handler:
 
407
 
 
408
 
 
409
@itemize @bullet
 
410
 
 
411
@item
 
412
you can go immediately after the @code{END_CATCH} statement if it does
 
413
not issue any of @code{RETURN} or @code{RETRY} statements
 
414
 
 
415
@item
 
416
you can reraise the exception by issuing the @code{RERAISE} if you want
 
417
to generate an exception with the same object, or you can use
 
418
@code{THROW} to generate an exception with a different object
 
419
 
 
420
@end itemize
 
421
 
 
422
 
 
423
You cannot execute a jump with the @code{goto} statement from the
 
424
@code{TRY}, @code{CATCH} or @code{OTHERWISE} blocks outside them. These
 
425
jumps are permitted only locally in the block. Also, do not return from
 
426
@code{TRY} or @code{CATCH} blocks with ordinary return statements.
 
427
 
 
428
You can jump outside the @code{TRY} block with the @code{BREAK}
 
429
statement that will go to the first statement following the
 
430
@code{END_CATCH} statement.
 
431
 
 
432
Another construction allows you to specify a block of code that will be
 
433
executed when an exception is caught by an upper exception handler. This
 
434
allows you to do some cleanup, for example to release all the resources
 
435
acquired from the system (such as memory allocation or file
 
436
descriptors). This block is introduced by the @code{CLEANUP} label.
 
437
 
 
438
Another construction is the @code{FINALLY} block. It is equivalent with
 
439
the @code{finally} block in Java. The code inside this block is called
 
440
whenever either an exception is raised and caught by an upper handler or
 
441
when the code inside a @code{TRY} block runs successfully.
 
442
 
 
443
The @code{FINALLY} construct is equivalent with the following @code{CLEANUP}
 
444
construct:
 
445
 
 
446
@example
 
447
TRY @{
 
448
    some code that can generate an exception
 
449
@} END_TRY
 
450
...
 
451
CLEANUP @{
 
452
    sequence of code
 
453
@}
 
454
END_CATCH
 
455
the same sequence of code from inside the CLEANUP block
 
456
@end example
 
457
 
 
458
If several exception handlers are nested the order in which the cleanup
 
459
and finally blocks are called is the same with the order in which the
 
460
functions containing them will normally return.
 
461
 
 
462
There are situations when you acquire some resources and you want to be
 
463
sure that they are released in case of an exception that is caught above
 
464
you in the stack frame. So you don' t need the @code{CATCH} or
 
465
@code{OTHERWISE} blocks. You could simply write:
 
466
 
 
467
@example
 
468
TRY @{
 
469
    some code that can generate an exception
 
470
@} END_TRY
 
471
CLEANUP @{
 
472
    code to release acquired resources
 
473
@}
 
474
END_CATCH
 
475
@end example
 
476
 
 
477
You could use the @code{FINALLY} construct when the resource is acquired
 
478
and also released in the same function. For example:
 
479
 
 
480
@example
 
481
acquire the resource
 
482
TRY @{
 
483
    some code that can generate an exception
 
484
@}
 
485
FINALLY @{
 
486
    code to release the resource
 
487
@}
 
488
END_CATCH
 
489
@end example
 
490
 
 
491
With these constructions the exception handling macros has the
 
492
following syntax:
 
493
 
 
494
@example
 
495
TRY @{
 
496
    some code that can generate an exception
 
497
@} END_TRY
 
498
CATCH(ExceptionClass1) @{
 
499
    code to handle an exception of class ExceptionClass1
 
500
@}
 
501
CATCH(ExceptionClass2) @{
 
502
    code to handle an exception of class ExceptionClass2
 
503
@}
 
504
...
 
505
OTHERWISE @{
 
506
    catch all exceptions not handled above
 
507
@}
 
508
CLEANUP @{
 
509
    ...
 
510
@}
 
511
FINALLY @{
 
512
    ...
 
513
@}
 
514
END_CATCH
 
515
@end example
 
516
 
 
517
@section OpenStep exceptions
 
518
 
 
519
The OpenStep exceptions are defined in the terms of the above macros.
 
520
 
 
521
@example
 
522
#define NS_DURING       TRY
 
523
 
 
524
#define NS_HANDLER \
 
525
    END_TRY \
 
526
    OTHERWISE
 
527
 
 
528
#define NS_ENDHANDLER   END_CATCH
 
529
@end example
 
530
 
 
531
In the actual implementation you can also use the @code{NS_VALRETURN}
 
532
and @code{NS_VOIDRETURN} macros inside the @code{TRY} block,
 
533
respectively inside @code{NS_DURING} block.
 
534
 
 
535
When you use @code{NS_VALRETURN} or @code{NS_VOIDRETURN} macros inside a
 
536
@code{TRY} block, be aware that before the function returns, the code
 
537
inside all @code{FINALLY} blocks associated with the @code{TRY} block
 
538
are executed first. However, because of a bug in the GNU compiler that
 
539
causes the compiler to crash when it compiles Objective-C programs with
 
540
nested functions for the NeXT runtime, this behavior is not implemented
 
541
for the programs compiled with the NeXT runtime.
 
542
 
 
543
 
 
544
@c =========================================================================
 
545
@node    Garbage collecting, Garbage collector based on reference counting, Exception handling, Top
 
546
@comment node-name, next, previous, up
 
547
 
 
548
@chapter Garbage collecting
 
549
 
 
550
Starting with version 0.9.0, @emph{libFoundation} comes with two garbage
 
551
collecting mechanisms that provide you with the ability to solve the
 
552
memory management problem.
 
553
 
 
554
The first garbage collector works with the default memory management
 
555
policy in OpenStep, the reference counting model. Reference counting is
 
556
a simple model for keeping track of objects and works good enough unless
 
557
you have cyclic data structures in your program, aka graphs of
 
558
objects. These cyclic graphs of objects cannot be collected by the
 
559
normal reference counting mechanism provided by OpenStep
 
560
Foundation. @emph{libFoundation} comes with a garbage collector based on
 
561
reference counting, that's fully integrated with the reference counting
 
562
model in OpenStep Foundation.
 
563
 
 
564
While reference counting is a simple and good technique for small to
 
565
medium programs, it's usually hard to write programs using it because,
 
566
as every human activity, is error-prone. The programmer can easily
 
567
forget to retain or release an object, thus leading to memory leaks. A
 
568
true garbage collector would solve the problem and would release the
 
569
programmer from manually keeping track of the allocated
 
570
memory. @emph{libFoundation} comes with support for Boehm's garbage
 
571
collector, a conservative collector available from
 
572
@uref{http://reality.sgi.com/boehm_mti/gc.html}.
 
573
 
 
574
There is only one source tree for the both versions of the library, the
 
575
normal OpenStep compatibility library and the support for the Boehm's
 
576
garbage collector library. To build the last type of library you just
 
577
have to type:
 
578
 
 
579
@example
 
580
  $ make gc=yes
 
581
@end example
 
582
 
 
583
This will build and install the library in a separate directory in the
 
584
GNUstep system tree. For all the GNUstep package that you want to run in
 
585
a garbage collected environment you will have to add @samp{gc=yes} as an
 
586
additional argument to make.
 
587
 
 
588
The next chapter present the garbage collector based on reference
 
589
counting. The classes and protocols presented here are only useful when
 
590
the garbage collector based on reference counting is used.
 
591
 
 
592
@menu
 
593
* Garbage collector based on reference counting::
 
594
* Boehm garbage collector::
 
595
@end menu
 
596
 
 
597
@c =========================================================================
 
598
@node    Garbage collector based on reference counting, The GarbageCollector class, Garbage collecting, Garbage collecting
 
599
@comment node-name, next, previous, up
 
600
 
 
601
@section Garbage collector based on reference counting
 
602
 
 
603
@emph{libFoundation} contains some classes that allow you to write code
 
604
without explicitly managing cyclic references between objects. Usually
 
605
you have to manage explicitly the reference counts when you have objects
 
606
that form cyclic graphs.
 
607
 
 
608
The garbage collector neither maintains explicitly all the pointers in
 
609
your program nor it collects all the memory allocated by you in the
 
610
program. Instead it collects and maintains only some special kind of
 
611
objects, that are garbage collectable.
 
612
 
 
613
The algorithm was inspired from a similar one found in the OATH C++
 
614
library written by Brian M. Kennedy's @w{@email{bmk@@csc.ti.com}}. It
 
615
works in three passes. Suppose that all the objects that are garbage
 
616
collectable are known. Also each object has an additional flag, used for
 
617
determining if the object was already visited.
 
618
 
 
619
During the first pass, all objects that are garbage collectable clears
 
620
the associated flag and receive the message
 
621
@code{-gcDecrementRefCountOfContainedObjects}. In this method the object
 
622
decrements the reference count of every garbage collectable object it
 
623
contains. After this pass all the objects that have the reference count
 
624
0 are part of cyclic graphs. Such objects have their reference count due
 
625
only to another objects from graph.
 
626
 
 
627
In the second pass we have to restore the original reference counts and
 
628
to isolate the nodes from cyclic graphs. In this pass all the objects
 
629
that have the reference count greater than 0 receive the message
 
630
@code{-gcIncrementRefCountOfContainedObjects}. In this method the object
 
631
check the flag if it's set. This flag tells if the object was visited
 
632
previously. If the flag is set, the method returns, else the flag is
 
633
set. Then the reference count of every garbage collectable object
 
634
contained is incremented and the message
 
635
@code{-gcIncrementRefCountOfContainedObjects} is sent to those objects.
 
636
 
 
637
After this pass all the objects that are reachable from `outside' have
 
638
their reference count greater than 0. All the objects that still have
 
639
their reference count equal with 0 are part of cyclic graphs and there is no
 
640
reference from `outside' to an object from these graphs.
 
641
 
 
642
In the third pass all the objects that have their reference count equal
 
643
with 0 receive the @code{-dealloc} message. In this method the objects
 
644
should send the @code{-release} message to all contained objects that
 
645
are not garbage collectable. This because the order of deallocation is
 
646
not known and you can send @code{-release} to an already deallocated
 
647
object. So if a class contains both normal objects and garbage
 
648
collectable objects, it should maintain their collectable status when
 
649
the objects are retained.
 
650
 
 
651
@menu
 
652
* The GarbageCollector class::
 
653
* The GarbageCollector protocol::
 
654
* Support classes::
 
655
@end menu
 
656
 
 
657
@c =========================================================================
 
658
@node    The GarbageCollector class, The GarbageCollector protocol, Garbage collector based on reference counting, Garbage collector based on reference counting
 
659
@comment node-name, next, previous, up
 
660
 
 
661
@subsection The @code{GarbageCollector} class
 
662
 
 
663
The class @code{GarbageCollector} implements the garbage collector. It
 
664
has the following interface:
 
665
 
 
666
@example
 
667
@@interface GarbageCollector : NSObject
 
668
 
 
669
+ (void)addObject:(id)anObject;
 
670
+ (void)objectWillBeDeallocated:(id)anObject;
 
671
 
 
672
+ (void)collectGarbages;
 
673
 
 
674
@@end
 
675
@end example
 
676
 
 
677
A new garbage collectable object has to be made know to the
 
678
@code{GarbageCollector} collector by sending it the @code{+addObject:}
 
679
message with self as argument. When the object is deallocated it should
 
680
inform the @code{GarbageCollector} class about this by sending it the
 
681
@code{+objectWillBeDeallocated:} message with self as argument.
 
682
 
 
683
The @code{+collectGarbages} should be send to the
 
684
@code{GarbageCollector} class to collect the garbages. You can send it
 
685
whenever you want. If you are using a run loop in your program you can
 
686
set a timer to be called periodically. Or you can call the garbage
 
687
collector when the program is idle.
 
688
 
 
689
In the current implementation the garbage collector is not
 
690
thread-safe, so please don't use it in multi-threaded programs, unless
 
691
you use garbage collectable objects only in one thread.
 
692
 
 
693
 
 
694
@c =========================================================================
 
695
@node    The GarbageCollector protocol, Support classes, The GarbageCollector class, Garbage collector based on reference counting
 
696
@comment node-name, next, previous, up
 
697
 
 
698
@subsection The @code{GarbageCollecting} protocol
 
699
 
 
700
To allow instances of a class to be garbage collectable, the class
 
701
should implement the following protocol:
 
702
 
 
703
@example
 
704
@@protocol GarbageCollecting
 
705
 
 
706
- gcSetNextObject:(id)anObject;
 
707
- gcSetPreviousObject:(id)anObject;
 
708
- (id)gcNextObject;
 
709
- (id)gcPreviousObject;
 
710
 
 
711
- (void)gcIncrementRefCount;
 
712
- (void)gcDecrementRefCount;
 
713
 
 
714
- (void)gcDecrementRefCountOfContainedObjects;
 
715
- (BOOL)gcIncrementRefCountOfContainedObjects;
 
716
 
 
717
- (BOOL)isGarbageCollectable;
 
718
 
 
719
@@end
 
720
@end example
 
721
 
 
722
The @code{GarbageCollector} class uses a double linked list to maintain
 
723
the objects. The @code{gcSetNextObject:}, @code{gcSetPreviousObject:},
 
724
@code{gcNextObject} and @code{gcPreviousObject} are used by the
 
725
collector to add or remove objects in its list. This could change in the
 
726
future.
 
727
 
 
728
The @code{gcIncrementRefCount} and @code{gcDecrementRefCount} methods
 
729
should increment, respectively decrement the reference count of
 
730
receiver.
 
731
 
 
732
The @code{gcDecrementRefCountOfContainedObjects} method should decrement
 
733
the reference count of all garbage collectable objects contained, by
 
734
sending them the message @w{@code{-gcDecrementRefCount}} to them.
 
735
 
 
736
The @code{gcIncrementRefCountOfContainedObjects} method should check the
 
737
flag. If this is true, the method should return @code{NO}; it this is
 
738
false the method should set it. Then it should increment the reference
 
739
count of garbage collectable objects contained by sending them the
 
740
@code{-gcIncrementRefCount} message. After this it should send the
 
741
@code{-gcIncrementRefCountOfContainedObjects} message to the same
 
742
objects. Then it should return @code{YES}.
 
743
 
 
744
The object should respond @code{YES} at the @code{-isGarbageCollectable}
 
745
message if it is garbage collectable. The NSObject class responds
 
746
@code{NO} to this message.
 
747
 
 
748
You should note the asymmetry between the
 
749
@code{gcDecrementRefCountOfContainedObjects} and
 
750
@code{gcIncrementRefCountOfContainedObjects} methods. This makes the
 
751
algorithm to work. So be careful if you're using copy/paste operations
 
752
to write them in your editor :-)!
 
753
 
 
754
 
 
755
@c =========================================================================
 
756
@node    Support classes, Boehm garbage collector, The GarbageCollector protocol, Garbage collector based on reference counting
 
757
@comment node-name, next, previous, up
 
758
 
 
759
@subsection Support classes
 
760
 
 
761
There is a class @code{GCObject} from which you could inherit your own
 
762
classes. This class implements the @code{GarbageCollecting} protocol.
 
763
 
 
764
Using this class, you could write a class whose instances hold other
 
765
objects. This class is safe to cyclic references. Here is its
 
766
implementation:
 
767
 
 
768
@example
 
769
@@interface MyGCObject : GCObject
 
770
@{
 
771
    id object;
 
772
    BOOL isGarbageCollectable;
 
773
@}
 
774
 
 
775
- (void)setObject:(id)anObject;
 
776
- (id)object;
 
777
 
 
778
@@end
 
779
 
 
780
 
 
781
@@implementation MyGCObject
 
782
 
 
783
- (void)setObject:(id)anObject
 
784
@{
 
785
    [anObject retain];
 
786
    [object release];
 
787
    object = anObject;
 
788
    isGarbageCollectable = [object isGarbageCollectable];
 
789
@}
 
790
 
 
791
- (id)object
 
792
@{
 
793
    return object;
 
794
@}
 
795
 
 
796
- (void)decrementRefCountOfContainedObjects
 
797
@{
 
798
    [object gcDecrementRefCount];
 
799
@}
 
800
 
 
801
- (BOOL)incrementRefCountOfContainedObjects
 
802
@{
 
803
    if(![super incrementRefCountOfContainedObjects])
 
804
        return NO;
 
805
    [object gcIncrementRefCount];
 
806
    [object incrementRefCountOfContainedObjects];
 
807
    return YES;
 
808
@}
 
809
 
 
810
- (void)dealloc
 
811
@{
 
812
    if(!isGarbageCollectable)
 
813
        [object release];
 
814
    [super dealloc];
 
815
@}
 
816
 
 
817
@@end
 
818
@end example
 
819
 
 
820
There are also concrete subclasses of @code{NSArray} and
 
821
@code{NSDictionary} named @code{GCArray} and @code{GCDictionary}
 
822
respectively, together with their mutable classes @code{GCMutableArray}
 
823
and @code{GCMutableDictionary}. Their instances could hold both normal
 
824
and garbage collectable objects.
 
825
 
 
826
 
 
827
 
 
828
@c =========================================================================
 
829
@node    Boehm garbage collector, Atomic memory allocation, Support classes, Garbage collecting
 
830
@comment node-name, next, previous, up
 
831
 
 
832
@section Boehm's garbage collector
 
833
 
 
834
Starting with version 0.9.0 @emph{libFoundation} comes with support for the
 
835
Boehm's garbage collector. It is available from
 
836
 
 
837
@uref{http://reality.sgi.com/boehm_mti/gc.html}
 
838
 
 
839
It is a conservative garbage collector that works by replacing the
 
840
system memory allocation routines
 
841
(@code{malloc}/@code{calloc}/@code{realloc}) with the ones that come
 
842
with the collector. The memory allocation works as before, you allocate
 
843
memory using the @code{GC_malloc()} function instead of @code{malloc()},
 
844
@code{GC_calloc()} instead of @code{calloc()} and @code{GC_realloc()}
 
845
instead of @code{realloc()}. The difference comes from the fact that
 
846
you're no longer required to call a @code{free} function. The collector
 
847
takes care of no longer reachable portions of the allocated memory by
 
848
monitoring the memory allocation of your program and trying to collect
 
849
the garbages when certain conditions are met. You can also explicitly
 
850
invoke the collection the garbages by calling the @code{GC_collect()}
 
851
function.
 
852
 
 
853
The collection can also occur in another thread on systems that support
 
854
multi-threading. You can disable the collection in the main thread by
 
855
setting the value of a variable (@code{GC_dont_gc}) and invoke the
 
856
collection in a separate thread when you wish, perhaps on a time basis
 
857
or when some other conditions are met.
 
858
 
 
859
Another feature is that the collection can be done incrementally, ie not
 
860
all the memory is collected at once. This can be done by calling the
 
861
@code{GC_collect_a_little()} function. One can use this feature in the
 
862
program's run loop of an interactive program to make sure the collection
 
863
will not make the program stop while the collection is in progress.
 
864
 
 
865
Memory allocation functions are described in @file{gc.h}.
 
866
 
 
867
@menu
 
868
* Atomic memory allocation::
 
869
* Typed memory allocation::
 
870
* Finalization::
 
871
* GC support in GNU Objective-C::
 
872
* GC support in libFoundation::
 
873
* Useful macros::
 
874
@end menu
 
875
 
 
876
@c =========================================================================
 
877
@node    Atomic memory allocation, Typed memory allocation, Boehm garbage collector, Boehm garbage collector
 
878
@comment node-name, next, previous, up
 
879
 
 
880
@subsection Atomic memory allocation
 
881
 
 
882
The Boehm's garbage collector normally assumes that all the memory
 
883
allocated potentially contains pointers. However this is not always
 
884
true. For memory zones that one knows they don't contain pointers to
 
885
other allocated memory, the @code{GC_malloc_atomic()} can be used. This
 
886
function marks the returned memory zone as not containing any
 
887
pointer. Use this function for allocating strings and memory zones that
 
888
does not contain pointers.
 
889
 
 
890
@c =========================================================================
 
891
@node    Typed memory allocation, Finalization, Atomic memory allocation, Boehm garbage collector
 
892
@comment node-name, next, previous, up
 
893
 
 
894
@subsection Typed memory allocation
 
895
 
 
896
There are many cases when the allocated memory may contain both data and
 
897
pointers. In this case the memory can be allocated using the normal
 
898
@code{GC_malloc()} function and let the collector assume that all the
 
899
contained data are pointers. This is both inefficient and error-prone
 
900
because it is possible, even with a small probability, that integers
 
901
have the same value as an existing pointer, thus keeping a reference to
 
902
a memory zone and preventing it to be deallocated.
 
903
 
 
904
Fortunately there's a better approach for this. At the time of the
 
905
allocation, it is possible to inform the collector where the pointers
 
906
are located inside it. This mechanism is called @emph{typed memory}.
 
907
 
 
908
To describe a memory zone a descriptor of it has to be constructed
 
909
first. The @code{GC_make_descriptor()} function is used for this; it
 
910
takes as arguments a bitmap describing the memory zone and the number of
 
911
meaningful bits in the bitmap. The less signifiant bit in the bitmap
 
912
corresponds to the first word in the memory zone.
 
913
 
 
914
The descriptor returned by the @code{GC_make_descriptor()} function is
 
915
then passed to the @code{GC_malloc_explicitly_typed()} or
 
916
@code{GC_calloc_explicitly_typed()}functions to allocate a memory
 
917
zone. One caveat though, the memory returned by these functions cannot
 
918
be reallocated at a later point in time.
 
919
 
 
920
The typed memory functions have their prototypes in the
 
921
@file{gc_typed.h} file.
 
922
 
 
923
@c =========================================================================
 
924
@node    Finalization, GC support in GNU Objective-C, Typed memory allocation, Boehm garbage collector
 
925
@comment node-name, next, previous, up
 
926
 
 
927
@subsection Finalization
 
928
 
 
929
The Boehm's collector provides a facility that allows a function to be
 
930
called just before a memory zone is collected. The
 
931
@code{GC_register_finalizer()} takes as arguments the function to be
 
932
called when the memory zone is being collected, the address of the
 
933
memory zone, a client data that's passed to the function when it is
 
934
called together with the address of the memory zone. There two more
 
935
arguments to this function, that are used as out arguments: the old
 
936
finalizer function and the old client data. Pass @code{NULL} to these
 
937
arguments if you're not interested in their values.
 
938
 
 
939
Be careful with what you do in the finalizer function. In general don't
 
940
assume that the finalizers are invoked in any particular order. More
 
941
important @strong{don't do any memory allocation inside the finalizer
 
942
function}. This would case the finalizer to be invoked again which is
 
943
not probably what you want (this may be a bug in the collector).
 
944
 
 
945
More explanation for the public functions can be found in both
 
946
@file{gc.h} and @file{gc_typed.h}.
 
947
 
 
948
@c =========================================================================
 
949
@node    GC support in GNU Objective-C, GC support in libFoundation, Finalization, Boehm garbage collector
 
950
@comment node-name, next, previous, up
 
951
 
 
952
@subsection Boehm's garbage collector support in the GNU Objective-C compiler and runtime
 
953
 
 
954
The GNU Objective-C runtime and compiler have been enhanced to support
 
955
the Boehm's garbage collector. To gain speed and to be able to implement
 
956
some special facilities like @strong{weak pointers} (pointers that are
 
957
invisible to the garbage collector), the GNU Objective-C runtime uses
 
958
typed memory to allocate all the instances of the classes.
 
959
 
 
960
The typed memory descriptor for each class is computed once per class,
 
961
immediately after the object has been initialized. The descriptor is
 
962
computed from the information about instance variables available in the
 
963
class. To correctly handle all the type information, the Objective-C
 
964
encoding for bitfields has been changed to include description of the
 
965
type holding the bitfield and the position of the bitfield inside the
 
966
corresponding value.
 
967
 
 
968
To mark a pointer inside an instance as a weak pointer, the function
 
969
@code{class_ivar_set_gcinvisible()} from the GNU runtime should be
 
970
used. This function takes as argument the class whose instances contain
 
971
the weak pointer, the name of the instance variable and a boolean flag
 
972
that marks or unmarks the instance variable as a weak pointer.
 
973
 
 
974
See the documentation in the GNU Objective-C compiler for a description
 
975
of the new encoding of bitfields and for an example of the
 
976
@code{class_ivar_set_gcinvisible()} function.
 
977
 
 
978
@c =========================================================================
 
979
@node    GC support in libFoundation, Useful macros, GC support in GNU Objective-C, Boehm garbage collector
 
980
@comment node-name, next, previous, up
 
981
 
 
982
@subsection Boehm's garbage collector support in @emph{libFoundation}
 
983
 
 
984
@emph{libFoundation} hides a lot of the interface with the Boehm's
 
985
garbage collector by providing the same API for the memory management
 
986
functions no matter what is the model used, the reference counting
 
987
mechanism or the Boehm's garbage collector.
 
988
 
 
989
The objects are allocated by the library using the normal
 
990
@code{NSAllocateObject()} function. In the case of Boehm's garbage
 
991
collector a typed memory object is properly allocated.
 
992
 
 
993
Internally the memory allocation for things other than objects is
 
994
performed using the @code{Malloc}, @code{Calloc}, @code{Realloc} and
 
995
@code{Free} inline functions. There are also versions that are used to
 
996
allocate atomic memory, @code{MallocAtomic} and
 
997
@code{CallocAtomic}. These pseudo-functions are not exported but one can
 
998
create similar functions for other libraries or applications.
 
999
 
 
1000
If you need to know when a given object will be finalized, you just have
 
1001
to make the class adopt the @code{GCFinalization} protocol. This
 
1002
protocol defines a single method, @code{-gcFinalize}, that is invoked by
 
1003
the garbage collector when an object is about to finalize.
 
1004
 
 
1005
In addition to finalization, the @code{GarbageCollector} class provides
 
1006
a powerful mechanism that allows objects to be registered as observers
 
1007
of other objects finalization. Here are the specific methods:
 
1008
 
 
1009
@example
 
1010
 
 
1011
@@interface GarbageCollector (BoehmGCSupport)
 
1012
 
 
1013
+ (void)registerForFinalizationObserver:(id)observer
 
1014
  selector:(SEL)selector
 
1015
  object:(id)object;
 
1016
+ (void)unregisterObserver:(id)observer
 
1017
  forObjectFinalization:(id)object;
 
1018
 
 
1019
@@end
 
1020
 
 
1021
@end example
 
1022
 
 
1023
When the @code{observer} object is registered for observing the
 
1024
finalization of @code{object}, the @code{observer}'s method whose
 
1025
selector is represented by @code{selector} is automatically called when
 
1026
@code{object} is about to finalize.
 
1027
 
 
1028
You can manually unregister an object as the observer of an object
 
1029
finalization by using the
 
1030
@code{+unregisterObserver:forObjectFinalization:} method. If you provide
 
1031
@code{nil} for the object then @code{observer} will be unregistered for
 
1032
all the objects it has been previously registered as observer.
 
1033
 
 
1034
If an object registered as observer of another objects finalizes, the
 
1035
@code{GarbageCollector} class automatically unregisters the observer for
 
1036
all the objects it was observer. You don't have to take any special
 
1037
actions to remove the observer except if it's kept in the internal
 
1038
structures of your program. In this case you should register another
 
1039
object as an observer of the original's observer finalization and remove
 
1040
it from your structures. As you can see an object can be simultaneously
 
1041
both an observed and an observer object, there's no restriction in doing
 
1042
this.
 
1043
 
 
1044
@c =========================================================================
 
1045
@node    Useful macros, NSZone, GC support in libFoundation, Boehm garbage collector
 
1046
@comment node-name, next, previous, up
 
1047
 
 
1048
@subsection Useful macros
 
1049
 
 
1050
When working with the Boehm's garbage collector, the messages used by
 
1051
the reference counting mechanism are obsolete and they simply introduce
 
1052
an unnecessary overhead. That's why instead of sending the
 
1053
@code{retain}, @code{release} and @code{autorelease} messages you'd
 
1054
better use the macros with the similar names, @code{RETAIN},
 
1055
@code{RELEASE} and @code{AUTORELEASE}. When the code is compiled with
 
1056
support for Boehm's garbage collector the correspondent messages are not
 
1057
sent at all.
 
1058
 
 
1059
In addition to the above macros, another macro should be used to make
 
1060
the code cleaner. The @code{ASSIGN} macro can be used whenever an object
 
1061
value is assigned to an object variable and the old value of the
 
1062
variable needs to be release and the new value retained. The definition
 
1063
of this macro is:
 
1064
 
 
1065
@example
 
1066
#define ASSIGN(object, value) \
 
1067
  (@{if (value) [value retain]; \
 
1068
    if (object) [object release]; \
 
1069
    object = value;@})
 
1070
@end example
 
1071
 
 
1072
When Boehm's garbage collector is used the definition of the macro is
 
1073
simply:
 
1074
 
 
1075
@example
 
1076
#define ASSIGN(object, value) \
 
1077
  object = value
 
1078
@end example
 
1079
 
 
1080
Another macro can be used whenever the code requires the creation of an
 
1081
autorelease pool. This pool is not needed when the code works in the
 
1082
presence of Boehm's garbage collector. The macro is
 
1083
@code{CREATE_AUTORELEASE_POOL} and should be used as a variable
 
1084
definition and must placed the last in the variables definition
 
1085
list. Use the @code{RELEASE} macro to release the pool.
 
1086
 
 
1087
The preprocessor define @code{LIB_FOUNDATION_BOEHM_GC} can be used to
 
1088
find out if the program is compiled with support for Boehm's garbage
 
1089
collector (@xref{Preprocessor defines} for other preprocessor
 
1090
defines). If you need to find out at runtime if the program was compiled
 
1091
with support for Boehm's collector you can access the read-only variable
 
1092
@code{_usesBoehmGC}.
 
1093
 
 
1094
@c =========================================================================
 
1095
@node    NSZone, The NSZone class, Useful macros, Top
 
1096
@comment node-name, next, previous, up
 
1097
 
 
1098
@chapter The @code{NSZone} class and memory allocation
 
1099
 
 
1100
Object allocation is performed from @emph{zones} that group related
 
1101
objects in a zone of memory. A zone is represented in
 
1102
@emph{libFoundation} by an instance of a subclass of @code{NSZone}. A
 
1103
zone is an object that not only keeps the memory zone from which the
 
1104
objects are allocated, but also encapsulates the algorithms that manage
 
1105
the memory allocation from that zone.
 
1106
 
 
1107
Traditionally, @code{NSZone} is implemented as a structure. In
 
1108
@emph{libFoundation}, @code{NSZone} is a class instead of a struct, and
 
1109
the related zone functions are static inline functions that invoke the
 
1110
corresponding methods of the zone instance. The idea behind the
 
1111
definition of the @code{NSZone} as a class and not as a struct is to
 
1112
offer the user of the library the possibility to build his own allocator
 
1113
and to let current and future allocators coexist.
 
1114
 
 
1115
Currently three zones are available: @code{NSDefaultZone},
 
1116
@code{NSAllocDebugZone} and @code{StackZone}. The first two they can be
 
1117
used only through the @code{NSZone} class and not directly. When
 
1118
@emph{libFoundation} is compiled with support for the Boehm's garbage
 
1119
collector the allocation is done using only the collector's allocation
 
1120
functions and the entire mechanism described below for the @code{NSZone}
 
1121
classes is completely unused.
 
1122
 
 
1123
When the program first starts a default zone is created
 
1124
automatically. This zone is either an instance of the
 
1125
@code{NSDefaultZone} or of the @code{NSAllocDebugZone} class, depending
 
1126
on the mode in which the program is run. If the program runs using the
 
1127
reference counting mechanism, the environment variable @code{ALLOCDEBUG}
 
1128
is checked. If the variable exists in your environment then the default
 
1129
zone will be an instance of @code{NSAllocDebugZone}. If this environment
 
1130
variable is not defined then an instance of @code{NSDefaultZone} becomes
 
1131
the default zone. If the program runs using the Boehm's garbage
 
1132
collector, no zones are used; for more information see @ref{Zones and
 
1133
garbage collection}.
 
1134
 
 
1135
You can change the default zone from which the future objects will be
 
1136
allocated using the @code{setDefaultZone:} method. To do this you have
 
1137
to create an instance of the zone you want to allocate objects from and
 
1138
call the @code{+setDefaultZone:} method of @code{NSZone} with the new
 
1139
instance. The zones are kept into a stack, the most recent zone being
 
1140
passed to @code{setDefaultZone:} being the top of the stack. When you
 
1141
release a zone and it has to be deallocated, the zone is removed from
 
1142
the stack of zones. If the zone object happens to be the top of the
 
1143
stack, the zone under it becomes the new default zone.
 
1144
 
 
1145
@menu
 
1146
* The NSZone class::
 
1147
* The NSZone functions::
 
1148
* The NSAllocDebugZone class::
 
1149
* Zones and garbage collection::
 
1150
@end menu
 
1151
 
 
1152
 
 
1153
@c =========================================================================
 
1154
@node    The NSZone class, The NSZone functions, NSZone, NSZone
 
1155
@comment node-name, next, previous, up
 
1156
 
 
1157
@section The @code{NSZone} class
 
1158
 
 
1159
@code{NSZone} is an abstract class that defines the basic behavior for
 
1160
all the memory allocators.
 
1161
 
 
1162
@itemize @bullet
 
1163
 
 
1164
@item
 
1165
@code{+(void)@strong{setDefaultZone}:(NSZone*)@emph{zone};}
 
1166
 
 
1167
@quotation
 
1168
Sets the default zone from which the subsequent memory allocation takes
 
1169
place.
 
1170
@end quotation
 
1171
 
 
1172
@item
 
1173
@code{+(NSZone*)@strong{defaultZone};}
 
1174
 
 
1175
@quotation
 
1176
Returns the default zone.
 
1177
@end quotation
 
1178
 
 
1179
@item
 
1180
@code{+(NSZone*)@strong{zoneFromPointer}:(void*)@emph{pointer};}
 
1181
 
 
1182
@quotation
 
1183
Returns the zone from which @emph{pointer} was allocated. Care should be
 
1184
taken as the zones are asked (using @code{-pointerInZone:}) in order if
 
1185
the pointer was allocated by them. See the @code{-pointerInZone:} method
 
1186
description for more information.
 
1187
@end quotation
 
1188
 
 
1189
@item
 
1190
@code{+(BOOL)@strong{checkZone};}
 
1191
 
 
1192
@quotation
 
1193
Check the memory allocated by all the zones. See the @code{-checkZone}
 
1194
method description for more information.
 
1195
@end quotation
 
1196
 
 
1197
@item
 
1198
@code{+(id)@strong{allocZoneInstance};}
 
1199
 
 
1200
@quotation
 
1201
This is the low level method used to allocate a zone instance. This is
 
1202
used because allocation of zone instances is done in a special way to
 
1203
avoid the chicken and egg problem (from which zone a zone instance is
 
1204
allocated?)
 
1205
@end quotation
 
1206
 
 
1207
@item
 
1208
@code{-(id)@strong{initForSize}:(unsigned)@emph{startSize} @strong{granularity}:(unsigned)@emph{granularity} @* @strong{canFree}:(BOOL)@emph{canFree};}
 
1209
 
 
1210
@quotation
 
1211
This is the designated initialization method. Creates a zone that can
 
1212
allocate as much as @emph{startSize} memory initially. The memory can
 
1213
grow or shrink in increments of @emph{granularity}. If @emph{canFree} is
 
1214
set to @code{YES} the memory is freed when when @code{-free:} is sent,
 
1215
otherwise the memory is never freed.
 
1216
@end quotation
 
1217
 
 
1218
@item
 
1219
@code{-(void*)@strong{malloc}:(unsigned)@emph{size};}
 
1220
 
 
1221
@quotation
 
1222
Allocate a memory zone of @emph{size} bytes and return it. Returns
 
1223
@code{NULL} if this is not possible.
 
1224
@end quotation
 
1225
 
 
1226
@item
 
1227
@code{-(void*)@strong{mallocAtomic}:(unsigned)@emph{size};}
 
1228
 
 
1229
@quotation
 
1230
Similar with @code{-malloc:} but allocate a memory zone that's not
 
1231
searched by the garbage collector for pointers.
 
1232
@end quotation
 
1233
 
 
1234
@item
 
1235
@code{-(void*)@strong{calloc}:(unsigned)@emph{numElems} @strong{byteSize}:(unsigned)@emph{byteSize};}
 
1236
 
 
1237
@quotation
 
1238
Allocate a memory zone that holds @emph{numElems} elements, each of
 
1239
@emph{byteSize}, set all the bytes in it to @code{0} and return
 
1240
it. Returns @code{NULL} if the allocation fails.
 
1241
@end quotation
 
1242
 
 
1243
@item
 
1244
@code{-(void*)@strong{callocAtomic}:(unsigned)@emph{numElems} @strong{byteSize}:(unsigned)@emph{byteSize};}
 
1245
 
 
1246
@quotation
 
1247
Similar with @code{-calloc:byteSize:} but return a memory zone that's
 
1248
not searched by the garbage collector for pointers.
 
1249
@end quotation
 
1250
 
 
1251
 
 
1252
@item
 
1253
@code{-(void*)@strong{realloc}:(void*)@emph{pointer} @strong{size}:(unsigned)@emph{size};}
 
1254
 
 
1255
@quotation
 
1256
Grow or shrink the size of the memory zone pointed to by @emph{pointer}
 
1257
to have the new size @emph{size}.
 
1258
@end quotation
 
1259
 
 
1260
@item
 
1261
@code{-(void)@strong{recycle};}
 
1262
 
 
1263
@quotation
 
1264
Frees the receiving zone after adding the still alive allocated zones to
 
1265
the default zone. Currently there are no zones in @emph{libFoundation}
 
1266
that implement this algorithm.
 
1267
@end quotation
 
1268
 
 
1269
@item
 
1270
@code{-(BOOL)@strong{pointerInZone}:(void*)@emph{pointer};}
 
1271
 
 
1272
@quotation
 
1273
Returns @code{YES} if @emph{pointer} points to a memory zone allocated
 
1274
by the receiving zone. Some zones are not able to reliably determine if
 
1275
the pointer is theirs or not. For example @code{NSDefaultZone} always
 
1276
returns true since few libc malloc implementation provide the capability
 
1277
to identify if a pointer is valid or not.
 
1278
@end quotation
 
1279
 
 
1280
@item
 
1281
@code{-(void)@strong{freePointer}:(void*)@emph{pointer};}
 
1282
 
 
1283
@quotation
 
1284
If the zone was initialized to free pointers, free the memory zone
 
1285
pointed to by @emph{pointer}. Otherwise do nothing.
 
1286
@end quotation
 
1287
 
 
1288
@item
 
1289
@code{-(void)@strong{setName}:(NSString*)@emph{name};}
 
1290
 
 
1291
@quotation
 
1292
Set the name of the receiving zone.
 
1293
@end quotation
 
1294
 
 
1295
@item
 
1296
@code{-(NSString*)@strong{name};}
 
1297
 
 
1298
@quotation
 
1299
Return the name of the receiving zone.
 
1300
@end quotation
 
1301
 
 
1302
@item
 
1303
@code{-(BOOL)@strong{checkZone};}
 
1304
 
 
1305
@quotation
 
1306
Checks the consistency of the memory allocated by the zone. Some
 
1307
classes, notably @code{NSAllocDebugZone}, when you request memory from
 
1308
them, they allocate more memory that is marked in a special way. In
 
1309
@code{-checkZone} they check if the marked zones are altered in which
 
1310
case they output an error message.
 
1311
@end quotation
 
1312
 
 
1313
@end itemize
 
1314
 
 
1315
 
 
1316
@c =========================================================================
 
1317
@node    The NSZone functions, The NSAllocDebugZone class, The NSZone class, NSZone
 
1318
@comment node-name, next, previous, up
 
1319
 
 
1320
@section The @code{NSZone} functions
 
1321
 
 
1322
The OpenStep specification defines several functions that deal with
 
1323
zones. In @emph{libFoundation} these functions are implemented as inline
 
1324
functions that send the corresponding message to the zone instance or
 
1325
directly to the @code{NSZone} class. The correspondency between them is
 
1326
straightforward so check the method description for more information.
 
1327
 
 
1328
Here are the functions used to manipulate a zone:
 
1329
 
 
1330
@itemize @bullet
 
1331
 
 
1332
@item
 
1333
@code{NSZone* @strong{NSCreateZone}(unsigned @emph{startSize}, unsigned @emph{granularity}, BOOL @emph{canFree});}
 
1334
 
 
1335
@item
 
1336
@code{NSZone* @strong{NSDefaultMallocZone}(void);}
 
1337
 
 
1338
@item
 
1339
@code{NSZone* @strong{NSZoneFromPointer}(void* @emph{pointer});}
 
1340
 
 
1341
@item
 
1342
@code{void* @strong{NSZoneMalloc}(NSZone* @emph{zone}, unsigned @emph{size});}
 
1343
 
 
1344
@item
 
1345
@code{void* @strong{NSZoneMallocAtomic}(NSZone* @emph{zone}, unsigned @emph{size});}
 
1346
 
 
1347
@item
 
1348
@code{void* @strong{NSZoneCalloc}(NSZone* @emph{zone}, unsigned @emph{numElems}, unsigned @emph{byteSize});}
 
1349
 
 
1350
@item
 
1351
@code{void* @strong{NSZoneCallocAtomic}(NSZone* @emph{zone}, unsigned @emph{numElems}, @* unsigned @emph{byteSize});}
 
1352
 
 
1353
@item
 
1354
@code{void* @strong{NSZoneRealloc}(NSZone* @emph{zone}, void* @emph{pointer}, unsigned @emph{size});}
 
1355
 
 
1356
@item
 
1357
@code{void @strong{NSZoneFree}(NSZone* @emph{zone}, void* @emph{pointer});}
 
1358
 
 
1359
@item
 
1360
@code{void @strong{NSRecycleZone}(NSZone* @emph{zone});}
 
1361
 
 
1362
@item
 
1363
@code{void @strong{NSSetZoneName}(NSZone* @emph{zone}, NSString* @emph{name});}
 
1364
 
 
1365
@item
 
1366
@code{NSString* @strong{NSZoneName}(NSZone* @emph{zone});}
 
1367
 
 
1368
@end itemize
 
1369
 
 
1370
 
 
1371
@c =========================================================================
 
1372
@node    The NSAllocDebugZone class, Zones and garbage collection, The NSZone functions, NSZone
 
1373
@comment node-name, next, previous, up
 
1374
 
 
1375
 
 
1376
@section The @code{NSAllocDebugZone} class
 
1377
 
 
1378
The @code{NSDefaultZone} uses system @code{malloc}, @code{calloc},
 
1379
@code{realloc} and @code{free} directly, without any checks.
 
1380
 
 
1381
The @code{NSAllocDebugZone} is used to help in tracking down memory
 
1382
allocation bugs. It provides the following features:
 
1383
 
 
1384
 
 
1385
@itemize @bullet
 
1386
 
 
1387
@item
 
1388
check double deallocation for pointers
 
1389
 
 
1390
@item
 
1391
check deallocation of non-existing pointers
 
1392
 
 
1393
@item
 
1394
use a block of memory past its margins
 
1395
 
 
1396
@item
 
1397
list blocks allocated since a moment (marked by a special call)
 
1398
 
 
1399
@item
 
1400
each allocated pointer has a serial number
 
1401
 
 
1402
@item
 
1403
stop when alloc-ing a pointer with a certain serial number
 
1404
 
 
1405
@item
 
1406
do @code{SYSTEM_MALLOC_CHECK} and internal checks every count operation
 
1407
 
 
1408
@item
 
1409
be able to control things from gdb
 
1410
 
 
1411
@item
 
1412
be able to control things from environment variables
 
1413
 
 
1414
@end itemize
 
1415
 
 
1416
The @code{NSAllocDebugZone} is controlled by the following environment
 
1417
variables:
 
1418
 
 
1419
@itemize @bullet
 
1420
 
 
1421
@item
 
1422
@code{ALLOCDEBUG}: must be set to something to use the alloc debug zone
 
1423
 
 
1424
@item
 
1425
@code{ALLOCDEBUG_STOP}: stop in debugger @code{SIGINT} when alloc-ing
 
1426
pointer with given serial number (this serial number is reported when
 
1427
and error with that pointer occurs). Undefined or 0 means no stop.
 
1428
 
 
1429
@item
 
1430
@code{ALLOCDEBUG_COUNT}: number of passes inside allocation/deallocation
 
1431
functions to @code{SYSTEM_MALLOC_CHECK} and internal check. Undefined or
 
1432
0 means no checks.
 
1433
 
 
1434
@item
 
1435
@code{ALLOCDEBUG_UPPER} and @code{ALLOCDEBUG_LOWER}: number of bytes to alloc at top/bottom of
 
1436
object block. These bytes are set to a given value (0x88) and checked at
 
1437
free and internal check to guard against using memory past the
 
1438
limit. Undefined or zero means no margin. Note that this size must be
 
1439
multiples of the machine address alignment (4, 8, 16 are recommended
 
1440
values).
 
1441
 
 
1442
@end itemize
 
1443
 
 
1444
The @code{NSAllocDebugZone} provides these functions to be used from the
 
1445
GNU debugger.
 
1446
 
 
1447
@itemize @bullet
 
1448
 
 
1449
@item
 
1450
@code{debuggerStopMark(unsigned mark)}: overrides @code{ALLOCDEBUG_STOP}
 
1451
 
 
1452
@item
 
1453
@code{debuggerCheckTime(unsigned count)}: overrides @code{ALLOCDEBUG_COUNT}
 
1454
 
 
1455
@item
 
1456
@code{debuggerDescription(id obj)}: performs @code{printf("%s\n", [obj description])}
 
1457
 
 
1458
@item
 
1459
@code{debuggerPerform(id obj, char* sel)}: performs @code{[obj sel]}
 
1460
 
 
1461
@item
 
1462
@code{debuggerPerformWith(id obj, char* sel, id arg)}: performs @* 
 
1463
@w{@code{[obj sel:(id)atoi(arg)]}}
 
1464
 
 
1465
@end itemize
 
1466
 
 
1467
The program instantiates two zones: one @code{NSDefaultZone} and one
 
1468
@code{NSAllocDebugZone}, and uses one or the other depending on the
 
1469
@code{ALLOCDEBUG} environment variable. If this variable exists in your
 
1470
environment then the @code{NSAllocDebugZone} instance will be
 
1471
used.
 
1472
 
 
1473
Below are some setting you might find useful when working with the
 
1474
@code{NSAllocDebugZone} class.
 
1475
 
 
1476
@example
 
1477
# must be set to something to use alloc debug zone
 
1478
ALLOCDEBUG=YES
 
1479
export ALLOCDEBUG=YES
 
1480
 
 
1481
# stop in debugger (SIGINT) when alloc-ing pointer number *
 
1482
# nil or 0 means no stop
 
1483
ALLOCDEBUG_STOP=0
 
1484
export ALLOCDEBUG_STOP
 
1485
 
 
1486
# stop in debugger (SIGINT) when alloc-ing pointer number *
 
1487
# nil or 0 means no stop
 
1488
ALLOCDEBUG_MARK=0
 
1489
export ALLOCDEBUG_MARK
 
1490
 
 
1491
# number of passes inside allocation/deallocation functions
 
1492
# to SYSTEM_MALLOC_CHECK and internal check
 
1493
# nil or 0 means no checks
 
1494
ALLOCDEBUG_COUNT=16
 
1495
export ALLOCDEBUG_COUNT
 
1496
 
 
1497
# number of bytes to alloc at top/bottom of object block
 
1498
# these bytes are set to a given value (0x88) and checked
 
1499
# at free and internal check to guard against using memory
 
1500
# past the limit.
 
1501
ALLOCDEBUG_UPPER=8
 
1502
ALLOCDEBUG_LOWER=8
 
1503
export ALLOCDEBUG_UPPER ALLOCDEBUG_LOWER
 
1504
@end example
 
1505
 
 
1506
 
 
1507
@c =========================================================================
 
1508
@node    Zones and garbage collection, NSInvocation, The NSAllocDebugZone class, NSZone
 
1509
@comment node-name, next, previous, up
 
1510
 
 
1511
@section Zones and garbage collection
 
1512
 
 
1513
The zone mechanism provides a way to group related pointers in a
 
1514
program.  For example different portions of an application which do not
 
1515
have much in common, can use different zones. This improves the memory
 
1516
localization in the virtual memory system of the operating system and
 
1517
lowers the mapping in and out of the memory pages.
 
1518
 
 
1519
In the current implementation, both garbage collectors, the Boehm's
 
1520
collector and the one based on reference counting, do not take advantage
 
1521
of this behavior. When a collection starts searching for the unused
 
1522
pointers can spread over all the existing zones.
 
1523
 
 
1524
Because of this, when @emph{libFoundation} is compiled with support for
 
1525
the Boehm's collector, the zones are completely disabled. The
 
1526
@code{NSZone} functions that perform memory allocation simply invoke the
 
1527
collector's functions.
 
1528
 
 
1529
 
 
1530
@c =========================================================================
 
1531
@node    NSInvocation, Porting NSInvocation, Zones and garbage collection, Top
 
1532
@comment node-name, next, previous, up
 
1533
 
 
1534
@chapter Features of the @code{NSInvocation} class
 
1535
 
 
1536
The ability to dynamically construct method invocations is an important
 
1537
feature in Objective-C libraries. This ability is used by various
 
1538
applications like distributed objects and various language interpreters
 
1539
to provide interface with the native methods or functions. In
 
1540
@emph{libFoundation} the @code{NSInvocation} class is designed to
 
1541
provide this important facility.
 
1542
 
 
1543
In the OpenStep specification and some OpenStep Foundation
 
1544
implementations, the @code{NSInvocation} class is only used to
 
1545
encapsulate the arguments and return value of a forwarded message and to
 
1546
allow sending a different message in the context of the forwarding. The
 
1547
normal usage of the @code{NSInvocation} is in the
 
1548
@code{-forwardInvocation:} method:
 
1549
 
 
1550
@example
 
1551
- (void)forwardInvocation:(NSInvocation*)anInvocation
 
1552
@{
 
1553
    [anInvocation setTarget:anotherObject];
 
1554
    [anInvocation setSelector:anotherSelector];
 
1555
    [anInvocation invoke];
 
1556
@}
 
1557
@end example
 
1558
 
 
1559
In this example the @code{NSInvocation} object is created automatically
 
1560
by the Foundation library, with the help of the Objective-C runtime
 
1561
library, when a message is sent to an object that does not implement
 
1562
it. The actual implementation assumes the stack frame for the arguments
 
1563
of the method already exists @footnote{On many systems this is only a
 
1564
partial picture, because the native convention calls can also use
 
1565
registers to pass arguments to a function.}. All the further changes to
 
1566
the method's arguments using the @code{NSInvocation}'s methods are
 
1567
performed on that stack frame. After the method invocation returns you
 
1568
can access the return value and possibly change it, using the
 
1569
@code{getReturnValue:} and @code{setReturnValue:} methods.
 
1570
 
 
1571
The situation is different when you build a dynamic method invocation.
 
1572
 
 
1573
@example
 
1574
    BOOL flag = YES;
 
1575
    int anInt = 1234;
 
1576
    float aFloat = 12345.0;
 
1577
    double aDouble = 98765.0;
 
1578
    id invocation = [[NSInvocation new] autorelease];
 
1579
 
 
1580
    [invocation setSelector:
 
1581
                @@selector(setFlag:intValue:floatValue:doubleValue:)];
 
1582
    [invocation setTarget:object];
 
1583
    [invocation setArgument:&flag atIndex:2];
 
1584
    [invocation setArgument:&anInt atIndex:3];
 
1585
    [invocation setArgument:&aFloat atIndex:4];
 
1586
    [invocation setArgument:&aDouble atIndex:5];
 
1587
    [invocation invoke];
 
1588
@end example
 
1589
 
 
1590
In this example the dynamic method invocation is constructed from
 
1591
scratch, by providing the object, the message selector and the arguments
 
1592
of the message. Then you can invoke the message and, after the message
 
1593
returns, you can access the return value.
 
1594
 
 
1595
It is very important to set the target and selector @emph{before}
 
1596
setting the arguments. The @code{NSInvocation} is not otherwise able to
 
1597
construct the stack and registers frame and set the arguments of the
 
1598
method invocation.
 
1599
 
 
1600
@menu
 
1601
* Porting NSInvocation::
 
1602
@end menu
 
1603
 
 
1604
 
 
1605
@c =========================================================================
 
1606
@node    Porting NSInvocation, NSMethodSignature, NSInvocation, NSInvocation
 
1607
@comment node-name, next, previous, up
 
1608
 
 
1609
 
 
1610
@section Porting @code{NSInvocation}
 
1611
 
 
1612
The @code{NSInvocation} is highly dependent on the target machine. The
 
1613
code that depends on the target machine is carefully separated from the
 
1614
independent part of the class. This code is written as macros in the
 
1615
@file{config/@emph{processor}/@emph{operating-system}}.
 
1616
 
 
1617
 
 
1618
@code{NSInvocation} is implemented using the @code{__builtin_apply} and
 
1619
@code{__builtin_return} built-in pseudo-functions that are available in
 
1620
the GNU C compiler. See the GNU C compiler documentation of these
 
1621
functions.
 
1622
 
 
1623
The following macros have to be defined for a given target
 
1624
machine. Defining them is a though process, they closely follow the
 
1625
native convention calls defined for the target in the GCC target
 
1626
dependent files. We intend to take advantage of the knowledge that's
 
1627
already in the compiler and move the @code{NSInvocation}'s code into the
 
1628
Objective-C runtime library.
 
1629
 
 
1630
@itemize @bullet
 
1631
 
 
1632
@item
 
1633
@code{FUNCTION_VALUE}
 
1634
 
 
1635
@item
 
1636
@code{FUNCTION_SET_VALUE}
 
1637
 
 
1638
@item
 
1639
@code{GET_STRUCT_VALUE_ADDRESS}
 
1640
 
 
1641
@item
 
1642
@code{SET_STRUCT_VALUE_ADDRESS}
 
1643
 
 
1644
@end itemize
 
1645
 
 
1646
In addition, if the target system does not work as expected copying the
 
1647
arguments onto and from the @code{__builtin_apply}'s frame, you can
 
1648
define in addition the @code{FRAME_SET_ARGUMENT} and
 
1649
@code{FRAME_GET_ARGUMENT} macros.
 
1650
 
 
1651
@code{FUNCTION_VALUE} should copy the return value from the result frame
 
1652
returned by the @code{__builtin_apply} pseudo-function into a memory
 
1653
zone received as argument. This macro has the following arguments:
 
1654
 
 
1655
@itemize @bullet
 
1656
 
 
1657
@item
 
1658
@code{TYPE} (@code{char*}): the Objective-C encoding of the return value
 
1659
type
 
1660
 
 
1661
@item
 
1662
@code{ARGS} (@code{void*}): the arguments frame passed to
 
1663
@code{__builtin_apply}
 
1664
 
 
1665
@item
 
1666
@code{RESULT_FRAME} (@code{void*}): the result frame returned by
 
1667
@code{__builtin_apply}
 
1668
 
 
1669
@item
 
1670
@code{RETURN_VALUE} (@code{void*}): the memory zone where the value
 
1671
should be set. This zone is already allocated.
 
1672
 
 
1673
@end itemize
 
1674
 
 
1675
 
 
1676
@code{FUNCTION_SET_VALUE} should set the return value into the result
 
1677
frame returned by the @code{__builtin_apply}. It has the following
 
1678
arguments:
 
1679
 
 
1680
@itemize @bullet
 
1681
 
 
1682
@item
 
1683
@code{TYPE} (@code{char*}): the Objective-C encoding of the return value
 
1684
type
 
1685
 
 
1686
@item
 
1687
@code{ARGS} (@code{void*}): the arguments frame passed to
 
1688
@code{__builtin_apply}
 
1689
 
 
1690
@item
 
1691
@code{RESULT_FRAME} (@code{void*}): the result frame returned by
 
1692
@code{__builtin_apply}
 
1693
 
 
1694
@item
 
1695
@code{RETURN_VALUE} (@code{void*}): the memory zone where the returned
 
1696
value should be copied from.
 
1697
 
 
1698
@end itemize
 
1699
 
 
1700
 
 
1701
@code{GET_STRUCT_VALUE_ADDRESS} is an expression that should produce the
 
1702
return value address in the case this is returned by reference or
 
1703
@code{NULL} if the return value is not returned by reference. Usually
 
1704
only the aggregates (structures and unions) are returned by
 
1705
reference. This macro has the following arguments:
 
1706
 
 
1707
@itemize @bullet
 
1708
 
 
1709
@item
 
1710
@code{ARGS} (@code{void*}): the arguments frame passed to
 
1711
@code{__builtin_apply}. Usually the address of return value is set here
 
1712
by the @code{__builtin_apply_args} pseudo-function
 
1713
 
 
1714
@item
 
1715
@code{RETTYPE} (@code{char*}): the Objective-C encoding of the return
 
1716
value type.
 
1717
 
 
1718
@end itemize
 
1719
 
 
1720
 
 
1721
@code{SET_STRUCT_VALUE_ADDRESS} should set in the arguments frame that
 
1722
will be passed to @code{__builtin_apply} the address of the return value
 
1723
if this is returned by reference. The arguments are:
 
1724
 
 
1725
@itemize @bullet
 
1726
 
 
1727
@item
 
1728
@code{ARGS} (@code{void*}): the arguments frame that will be passed to
 
1729
@code{__builtin_apply}
 
1730
 
 
1731
@item
 
1732
@code{ADDR} (@code{void*}): the address of the zone where the called
 
1733
function should set the return value. This zone is already allocated.
 
1734
 
 
1735
@item
 
1736
@code{RETTYPE} (@code{char*}): the Objective-C encoding of the return
 
1737
value type
 
1738
 
 
1739
@end itemize
 
1740
 
 
1741
 
 
1742
@code{FRAME_SET_ARGUMENT} should be used whenever the default mechanism
 
1743
of copying the argument onto the @code{__builtin_apply}'s frame is not
 
1744
working. The default mechanism is implemented in the
 
1745
@code{NSInvocation}'s @code{-setArgument:atIndex:} method. If you do not
 
1746
define this macro the default mechanism is used.
 
1747
 
 
1748
The arguments of this macro are:
 
1749
 
 
1750
@itemize @bullet
 
1751
 
 
1752
@item
 
1753
@code{FRAME_DATA} (@code{void*}): The address in the
 
1754
@code{__builtin_apply}'s frame where the argument's value has to be copied.
 
1755
 
 
1756
@code{ARGUMENT_LOCATION} (@code{void*}): The address where the argument
 
1757
to be copied is located.
 
1758
 
 
1759
@code{ARG_INFO} (@code{NSArgumentInfo}): Describes the type of the
 
1760
argument.
 
1761
 
 
1762
@end itemize
 
1763
 
 
1764
The @code{FRAME_GET_ARGUMENT} macros is similar with
 
1765
@code{FRAME_SET_ARGUMENT} but does the opposite job.
 
1766
 
 
1767
For an example of how the above macros are implemented you can take a
 
1768
look in the @file{config} directory in the @emph{libFoundation}'s
 
1769
distribution.
 
1770
 
 
1771
 
 
1772
@c =========================================================================
 
1773
@node    NSMethodSignature, Porting NSMethodSignature, Porting NSInvocation, Top
 
1774
@comment node-name, next, previous, up
 
1775
 
 
1776
@chapter Features of the @code{NSMethodSignature} class
 
1777
 
 
1778
@code{NSMethodSignature} provides information about the type signature
 
1779
of a method. The Objective-C type encoding of a method is a C string
 
1780
that contains an encoding of the return value type and type of the
 
1781
arguments including information about how to access them on the stack
 
1782
and registers frames. See the Objective-C documentation in the GCC
 
1783
runtime for more information about method type encoding.
 
1784
 
 
1785
Below is an example of how to create a @code{NSMethodSignature} instance
 
1786
for a given method of an object:
 
1787
 
 
1788
@example
 
1789
    id anObject;
 
1790
    struct objc_method* mth
 
1791
         = class_get_instance_method(self->isa, aSelector);
 
1792
    const char* types = mth->method_types;
 
1793
    id signature = [NSMethodSignature signatureWithObjCTypes:types];
 
1794
@end example
 
1795
 
 
1796
The above code is implemented by the @code{NSObject}'s
 
1797
@code{methodSignatureForSelector:} method. If you send this method to a
 
1798
class, the method searches for a class method whose selector is the same
 
1799
as the argument. If the message is sent to an instance, the method
 
1800
searches for an instance method. If you don't want to create an instance
 
1801
of a class just to find out what is the signature of an instance method,
 
1802
you can use the @code{instanceMethodForSelector:} method, that searches
 
1803
in the class for an instance method with the same selector as the
 
1804
argument.
 
1805
 
 
1806
In addition to providing information about already existing method
 
1807
encodings that are available for compiled methods, the
 
1808
@code{NSMethodSignature} class from @emph{libFoundation} allows you to
 
1809
construct method signatures for new methods, that could be created for
 
1810
example by an interpreter. Suppose one wants to create a method encoding
 
1811
that has arguments an integer and its return type is @code{void}; you
 
1812
can do like this:
 
1813
 
 
1814
@example
 
1815
    id signature = [NSMethodSignature signatureWithObjCTypes:"v@:i"];
 
1816
@end example
 
1817
 
 
1818
The @code{NSMethodSignature} class computes the full signature that
 
1819
contains the offsets of the arguments on the stack and registers
 
1820
frames. This code is dependent on the target machine so the result may
 
1821
be different between various processors and even on the same processor
 
1822
but different OSes.
 
1823
 
 
1824
@menu
 
1825
* Porting NSMethodSignature::
 
1826
@end menu
 
1827
 
 
1828
@c =========================================================================
 
1829
@node    Porting NSMethodSignature, , NSMethodSignature, NSMethodSignature
 
1830
@comment node-name, next, previous, up
 
1831
 
 
1832
@section Porting NSMethodSignature
 
1833
 
 
1834
Porting @code{NSMethodSignature} implies defining the below macros,
 
1835
similar with the way @code{NSInvocation} is ported to a new platform. As
 
1836
with the @code{NSInvocation}'s macros, this code will probably also move
 
1837
in the Objective-C runtime library, to take advantage of the compiler's
 
1838
knowledge on the target system.
 
1839
 
 
1840
@itemize @bullet
 
1841
 
 
1842
@item
 
1843
@code{CUMULATIVE_ARGS}
 
1844
 
 
1845
@item
 
1846
@code{INIT_CUMULATIVE_ARGS}
 
1847
 
 
1848
@item
 
1849
@code{FUNCTION_ARG_ENCODING}
 
1850
 
 
1851
@end itemize
 
1852
 
 
1853
The name of this macros are the same with the similar ones from the GNU
 
1854
CC compiler. However they don't correspond neither in semantics nor in
 
1855
the argument types.
 
1856
 
 
1857
@code{CUMULATIVE_ARGS} is the data type of a variable used to hold about
 
1858
arguments processed so far. On a machine where all the arguments are
 
1859
passed on stack, this type is usually @code{int}.
 
1860
 
 
1861
@code{INIT_CUMULATIVE_ARGS} should initialize the variable of type
 
1862
@code{CUMULATIVE_ARGS} described above.
 
1863
 
 
1864
@code{FUNCTION_ARG_ENCODING} determines the encoding of the next
 
1865
argument of a method. It must produce a @code{NSString} describing the
 
1866
Objective-C encoding and position of the argument in the arguments frame
 
1867
of the method.
 
1868
 
 
1869
If you want to determine how to write the encoding for a new machine you
 
1870
could use the program generated by signature-test.pl perl script in
 
1871
@emph{FoundationTestsuite}. This generates a class with a lot of
 
1872
methods. You can look at the output of the program to see how the
 
1873
compiler encodes the methods. Also take a look in the @file{objc-act.c}
 
1874
file in the compiler to see how the methods are encoded.
 
1875
 
 
1876
 
 
1877
@c =========================================================================
 
1878
 
 
1879
@contents
 
1880
 
 
1881
@bye