1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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
699
700
701
702
703
704
705
706
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
|
@c Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
@c 1999, 2000, 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
@c This is part of the GCC manual.
@c For copying conditions, see the file gcc.texi.
@node Objective-C
@comment node-name, next, previous, up
@chapter GNU Objective-C features
This document is meant to describe some of the GNU Objective-C
features. It is not intended to teach you Objective-C, there are
several resources on the Internet that present the language.
@menu
* Executing code before main::
* Type encoding::
* Garbage Collection::
* Constant string objects::
* compatibility_alias::
* Exceptions::
* Synchronization::
@end menu
@node Executing code before main
@section @code{+load}: Executing code before main
The GNU Objective-C runtime provides a way that allows you to execute
code before the execution of the program enters the @code{main}
function. The code is executed on a per-class and a per-category basis,
through a special class method @code{+load}.
This facility is very useful if you want to initialize global variables
which can be accessed by the program directly, without sending a message
to the class first. The usual way to initialize global variables, in the
@code{+initialize} method, might not be useful because
@code{+initialize} is only called when the first message is sent to a
class object, which in some cases could be too late.
Suppose for example you have a @code{FileStream} class that declares
@code{Stdin}, @code{Stdout} and @code{Stderr} as global variables, like
below:
@smallexample
FileStream *Stdin = nil;
FileStream *Stdout = nil;
FileStream *Stderr = nil;
@@implementation FileStream
+ (void)initialize
@{
Stdin = [[FileStream new] initWithFd:0];
Stdout = [[FileStream new] initWithFd:1];
Stderr = [[FileStream new] initWithFd:2];
@}
/* @r{Other methods here} */
@@end
@end smallexample
In this example, the initialization of @code{Stdin}, @code{Stdout} and
@code{Stderr} in @code{+initialize} occurs too late. The programmer can
send a message to one of these objects before the variables are actually
initialized, thus sending messages to the @code{nil} object. The
@code{+initialize} method which actually initializes the global
variables is not invoked until the first message is sent to the class
object. The solution would require these variables to be initialized
just before entering @code{main}.
The correct solution of the above problem is to use the @code{+load}
method instead of @code{+initialize}:
@smallexample
@@implementation FileStream
+ (void)load
@{
Stdin = [[FileStream new] initWithFd:0];
Stdout = [[FileStream new] initWithFd:1];
Stderr = [[FileStream new] initWithFd:2];
@}
/* @r{Other methods here} */
@@end
@end smallexample
The @code{+load} is a method that is not overridden by categories. If a
class and a category of it both implement @code{+load}, both methods are
invoked. This allows some additional initializations to be performed in
a category.
This mechanism is not intended to be a replacement for @code{+initialize}.
You should be aware of its limitations when you decide to use it
instead of @code{+initialize}.
@menu
* What you can and what you cannot do in +load::
@end menu
@node What you can and what you cannot do in +load
@subsection What you can and what you cannot do in @code{+load}
The @code{+load} implementation in the GNU runtime guarantees you the following
things:
@itemize @bullet
@item
you can write whatever C code you like;
@item
you can send messages to Objective-C constant strings (@code{@@"this is a
constant string"});
@item
you can allocate and send messages to objects whose class is implemented
in the same file;
@item
the @code{+load} implementation of all super classes of a class are executed before the @code{+load} of that class is executed;
@item
the @code{+load} implementation of a class is executed before the
@code{+load} implementation of any category.
@end itemize
In particular, the following things, even if they can work in a
particular case, are not guaranteed:
@itemize @bullet
@item
allocation of or sending messages to arbitrary objects;
@item
allocation of or sending messages to objects whose classes have a
category implemented in the same file;
@end itemize
You should make no assumptions about receiving @code{+load} in sibling
classes when you write @code{+load} of a class. The order in which
sibling classes receive @code{+load} is not guaranteed.
The order in which @code{+load} and @code{+initialize} are called could
be problematic if this matters. If you don't allocate objects inside
@code{+load}, it is guaranteed that @code{+load} is called before
@code{+initialize}. If you create an object inside @code{+load} the
@code{+initialize} method of object's class is invoked even if
@code{+load} was not invoked. Note if you explicitly call @code{+load}
on a class, @code{+initialize} will be called first. To avoid possible
problems try to implement only one of these methods.
The @code{+load} method is also invoked when a bundle is dynamically
loaded into your running program. This happens automatically without any
intervening operation from you. When you write bundles and you need to
write @code{+load} you can safely create and send messages to objects whose
classes already exist in the running program. The same restrictions as
above apply to classes defined in bundle.
@node Type encoding
@section Type encoding
This is an advanced section. Type encodings are used extensively by
the compiler and by the runtime, but you generally do not need to know
about them to use Objective-C.
The Objective-C compiler generates type encodings for all the types.
These type encodings are used at runtime to find out information about
selectors and methods and about objects and classes.
The types are encoded in the following way:
@c @sp 1
@multitable @columnfractions .25 .75
@item @code{_Bool}
@tab @code{B}
@item @code{char}
@tab @code{c}
@item @code{unsigned char}
@tab @code{C}
@item @code{short}
@tab @code{s}
@item @code{unsigned short}
@tab @code{S}
@item @code{int}
@tab @code{i}
@item @code{unsigned int}
@tab @code{I}
@item @code{long}
@tab @code{l}
@item @code{unsigned long}
@tab @code{L}
@item @code{long long}
@tab @code{q}
@item @code{unsigned long long}
@tab @code{Q}
@item @code{float}
@tab @code{f}
@item @code{double}
@tab @code{d}
@item @code{long double}
@tab @code{D}
@item @code{void}
@tab @code{v}
@item @code{id}
@tab @code{@@}
@item @code{Class}
@tab @code{#}
@item @code{SEL}
@tab @code{:}
@item @code{char*}
@tab @code{*}
@item @code{enum}
@tab an @code{enum} is encoded exactly as the integer type that the compiler uses for it, which depends on the enumeration
values. Often the compiler users @code{unsigned int}, which is then encoded as @code{I}.
@item unknown type
@tab @code{?}
@item Complex types
@tab @code{j} followed by the inner type. For example @code{_Complex double} is encoded as "jd".
@item bit-fields
@tab @code{b} followed by the starting position of the bit-field, the type of the bit-field and the size of the bit-field (the bit-fields encoding was changed from the NeXT's compiler encoding, see below)
@end multitable
@c @sp 1
The encoding of bit-fields has changed to allow bit-fields to be
properly handled by the runtime functions that compute sizes and
alignments of types that contain bit-fields. The previous encoding
contained only the size of the bit-field. Using only this information
it is not possible to reliably compute the size occupied by the
bit-field. This is very important in the presence of the Boehm's
garbage collector because the objects are allocated using the typed
memory facility available in this collector. The typed memory
allocation requires information about where the pointers are located
inside the object.
The position in the bit-field is the position, counting in bits, of the
bit closest to the beginning of the structure.
The non-atomic types are encoded as follows:
@c @sp 1
@multitable @columnfractions .2 .8
@item pointers
@tab @samp{^} followed by the pointed type.
@item arrays
@tab @samp{[} followed by the number of elements in the array followed by the type of the elements followed by @samp{]}
@item structures
@tab @samp{@{} followed by the name of the structure (or @samp{?} if the structure is unnamed), the @samp{=} sign, the type of the members and by @samp{@}}
@item unions
@tab @samp{(} followed by the name of the structure (or @samp{?} if the union is unnamed), the @samp{=} sign, the type of the members followed by @samp{)}
@item vectors
@tab @samp{![} followed by the vector_size (the number of bytes composing the vector) followed by a comma, followed by the alignment (in bytes) of the vector, followed by the type of the elements followed by @samp{]}
@end multitable
Here are some types and their encodings, as they are generated by the
compiler on an i386 machine:
@sp 1
@multitable @columnfractions .25 .75
@item Objective-C type
@tab Compiler encoding
@item
@smallexample
int a[10];
@end smallexample
@tab @code{[10i]}
@item
@smallexample
struct @{
int i;
float f[3];
int a:3;
int b:2;
char c;
@}
@end smallexample
@tab @code{@{?=i[3f]b128i3b131i2c@}}
@item
@smallexample
int a __attribute__ ((vector_size (16)));
@end smallexample
@tab @code{![16,16i]} (alignment would depend on the machine)
@end multitable
@sp 1
In addition to the types the compiler also encodes the type
specifiers. The table below describes the encoding of the current
Objective-C type specifiers:
@sp 1
@multitable @columnfractions .25 .75
@item Specifier
@tab Encoding
@item @code{const}
@tab @code{r}
@item @code{in}
@tab @code{n}
@item @code{inout}
@tab @code{N}
@item @code{out}
@tab @code{o}
@item @code{bycopy}
@tab @code{O}
@item @code{byref}
@tab @code{R}
@item @code{oneway}
@tab @code{V}
@end multitable
@sp 1
The type specifiers are encoded just before the type. Unlike types
however, the type specifiers are only encoded when they appear in method
argument types.
Note how @code{const} interacts with pointers:
@sp 1
@multitable @columnfractions .25 .75
@item Objective-C type
@tab Compiler encoding
@item
@smallexample
const int
@end smallexample
@tab @code{ri}
@item
@smallexample
const int*
@end smallexample
@tab @code{^ri}
@item
@smallexample
int *const
@end smallexample
@tab @code{r^i}
@end multitable
@sp 1
@code{const int*} is a pointer to a @code{const int}, and so is
encoded as @code{^ri}. @code{int* const}, instead, is a @code{const}
pointer to an @code{int}, and so is encoded as @code{r^i}.
Finally, there is a complication when encoding @code{const char *}
versus @code{char * const}. Because @code{char *} is encoded as
@code{*} and not as @code{^c}, there is no way to express the fact
that @code{r} applies to the pointer or to the pointee.
Hence, it is assumed as a convention that @code{r*} means @code{const
char *} (since it is what is most often meant), and there is no way to
encode @code{char *const}. @code{char *const} would simply be encoded
as @code{*}, and the @code{const} is lost.
@menu
* Legacy type encoding::
* @@encode::
* Method signatures::
@end menu
@node Legacy type encoding
@subsection Legacy type encoding
Unfortunately, historically GCC used to have a number of bugs in its
encoding code. The NeXT runtime expects GCC to emit type encodings in
this historical format (compatible with GCC-3.3), so when using the
NeXT runtime, GCC will introduce on purpose a number of incorrect
encodings:
@itemize @bullet
@item
the read-only qualifier of the pointee gets emitted before the '^'.
The read-only qualifier of the pointer itself gets ignored, unless it
is a typedef. Also, the 'r' is only emitted for the outermost type.
@item
32-bit longs are encoded as 'l' or 'L', but not always. For typedefs,
the compiler uses 'i' or 'I' instead if encoding a struct field or a
pointer.
@item
@code{enum}s are always encoded as 'i' (int) even if they are actually
unsigned or long.
@end itemize
In addition to that, the NeXT runtime uses a different encoding for
bitfields. It encodes them as @code{b} followed by the size, without
a bit offset or the underlying field type.
@node @@encode
@subsection @@encode
GNU Objective-C supports the @code{@@encode} syntax that allows you to
create a type encoding from a C/Objective-C type. For example,
@code{@@encode(int)} is compiled by the compiler into @code{"i"}.
@code{@@encode} does not support type qualifiers other than
@code{const}. For example, @code{@@encode(const char*)} is valid and
is compiled into @code{"r*"}, while @code{@@encode(bycopy char *)} is
invalid and will cause a compilation error.
@node Method signatures
@subsection Method signatures
This section documents the encoding of method types, which is rarely
needed to use Objective-C. You should skip it at a first reading; the
runtime provides functions that will work on methods and can walk
through the list of parameters and interpret them for you. These
functions are part of the public ``API'' and are the preferred way to
interact with method signatures from user code.
But if you need to debug a problem with method signatures and need to
know how they are implemented (ie, the ``ABI''), read on.
Methods have their ``signature'' encoded and made available to the
runtime. The ``signature'' encodes all the information required to
dynamically build invocations of the method at runtime: return type
and arguments.
The ``signature'' is a null-terminated string, composed of the following:
@itemize @bullet
@item
The return type, including type qualifiers. For example, a method
returning @code{int} would have @code{i} here.
@item
The total size (in bytes) required to pass all the parameters. This
includes the two hidden parameters (the object @code{self} and the
method selector @code{_cmd}).
@item
Each argument, with the type encoding, followed by the offset (in
bytes) of the argument in the list of parameters.
@end itemize
For example, a method with no arguments and returning @code{int} would
have the signature @code{i8@@0:4} if the size of a pointer is 4. The
signature is interpreted as follows: the @code{i} is the return type
(an @code{int}), the @code{8} is the total size of the parameters in
bytes (two pointers each of size 4), the @code{@@0} is the first
parameter (an object at byte offset @code{0}) and @code{:4} is the
second parameter (a @code{SEL} at byte offset @code{4}).
You can easily find more examples by running the ``strings'' program
on an Objective-C object file compiled by GCC. You'll see a lot of
strings that look very much like @code{i8@@0:4}. They are signatures
of Objective-C methods.
@node Garbage Collection
@section Garbage Collection
Support for garbage collection with the GNU runtime has been added by
using a powerful conservative garbage collector, known as the
Boehm-Demers-Weiser conservative garbage collector.
To enable the support for it you have to configure the compiler using
an additional argument, @w{@option{--enable-objc-gc}}. This will
build the boehm-gc library, and build an additional runtime library
which has several enhancements to support the garbage collector. The
new library has a new name, @file{libobjc_gc.a} to not conflict with
the non-garbage-collected library.
When the garbage collector is used, the objects are allocated using the
so-called typed memory allocation mechanism available in the
Boehm-Demers-Weiser collector. This mode requires precise information on
where pointers are located inside objects. This information is computed
once per class, immediately after the class has been initialized.
There is a new runtime function @code{class_ivar_set_gcinvisible()}
which can be used to declare a so-called @dfn{weak pointer}
reference. Such a pointer is basically hidden for the garbage collector;
this can be useful in certain situations, especially when you want to
keep track of the allocated objects, yet allow them to be
collected. This kind of pointers can only be members of objects, you
cannot declare a global pointer as a weak reference. Every type which is
a pointer type can be declared a weak pointer, including @code{id},
@code{Class} and @code{SEL}.
Here is an example of how to use this feature. Suppose you want to
implement a class whose instances hold a weak pointer reference; the
following class does this:
@smallexample
@@interface WeakPointer : Object
@{
const void* weakPointer;
@}
- initWithPointer:(const void*)p;
- (const void*)weakPointer;
@@end
@@implementation WeakPointer
+ (void)initialize
@{
class_ivar_set_gcinvisible (self, "weakPointer", YES);
@}
- initWithPointer:(const void*)p
@{
weakPointer = p;
return self;
@}
- (const void*)weakPointer
@{
return weakPointer;
@}
@@end
@end smallexample
Weak pointers are supported through a new type character specifier
represented by the @samp{!} character. The
@code{class_ivar_set_gcinvisible()} function adds or removes this
specifier to the string type description of the instance variable named
as argument.
@c =========================================================================
@node Constant string objects
@section Constant string objects
GNU Objective-C provides constant string objects that are generated
directly by the compiler. You declare a constant string object by
prefixing a C constant string with the character @samp{@@}:
@smallexample
id myString = @@"this is a constant string object";
@end smallexample
The constant string objects are by default instances of the
@code{NXConstantString} class which is provided by the GNU Objective-C
runtime. To get the definition of this class you must include the
@file{objc/NXConstStr.h} header file.
User defined libraries may want to implement their own constant string
class. To be able to support them, the GNU Objective-C compiler provides
a new command line options @option{-fconstant-string-class=@var{class-name}}.
The provided class should adhere to a strict structure, the same
as @code{NXConstantString}'s structure:
@smallexample
@@interface MyConstantStringClass
@{
Class isa;
char *c_string;
unsigned int len;
@}
@@end
@end smallexample
@code{NXConstantString} inherits from @code{Object}; user class
libraries may choose to inherit the customized constant string class
from a different class than @code{Object}. There is no requirement in
the methods the constant string class has to implement, but the final
ivar layout of the class must be the compatible with the given
structure.
When the compiler creates the statically allocated constant string
object, the @code{c_string} field will be filled by the compiler with
the string; the @code{length} field will be filled by the compiler with
the string length; the @code{isa} pointer will be filled with
@code{NULL} by the compiler, and it will later be fixed up automatically
at runtime by the GNU Objective-C runtime library to point to the class
which was set by the @option{-fconstant-string-class} option when the
object file is loaded (if you wonder how it works behind the scenes, the
name of the class to use, and the list of static objects to fixup, are
stored by the compiler in the object file in a place where the GNU
runtime library will find them at runtime).
As a result, when a file is compiled with the
@option{-fconstant-string-class} option, all the constant string objects
will be instances of the class specified as argument to this option. It
is possible to have multiple compilation units referring to different
constant string classes, neither the compiler nor the linker impose any
restrictions in doing this.
@c =========================================================================
@node compatibility_alias
@section compatibility_alias
The keyword @code{@@compatibility_alias} allows you to define a class name
as equivalent to another class name. For example:
@smallexample
@@compatibility_alias WOApplication GSWApplication;
@end smallexample
tells the compiler that each time it encounters @code{WOApplication} as
a class name, it should replace it with @code{GSWApplication} (that is,
@code{WOApplication} is just an alias for @code{GSWApplication}).
There are some constraints on how this can be used---
@itemize @bullet
@item @code{WOApplication} (the alias) must not be an existing class;
@item @code{GSWApplication} (the real class) must be an existing class.
@end itemize
@c =========================================================================
@node Exceptions
@section Exceptions
GNU Objective-C provides exception support built into the language, as
in the following example:
@smallexample
@@try @{
@dots{}
@@throw expr;
@dots{}
@}
@@catch (AnObjCClass *exc) @{
@dots{}
@@throw expr;
@dots{}
@@throw;
@dots{}
@}
@@catch (AnotherClass *exc) @{
@dots{}
@}
@@catch (id allOthers) @{
@dots{}
@}
@@finally @{
@dots{}
@@throw expr;
@dots{}
@}
@end smallexample
The @code{@@throw} statement may appear anywhere in an Objective-C or
Objective-C++ program; when used inside of a @code{@@catch} block, the
@code{@@throw} may appear without an argument (as shown above), in
which case the object caught by the @code{@@catch} will be rethrown.
Note that only (pointers to) Objective-C objects may be thrown and
caught using this scheme. When an object is thrown, it will be caught
by the nearest @code{@@catch} clause capable of handling objects of
that type, analogously to how @code{catch} blocks work in C++ and
Java. A @code{@@catch(id @dots{})} clause (as shown above) may also
be provided to catch any and all Objective-C exceptions not caught by
previous @code{@@catch} clauses (if any).
The @code{@@finally} clause, if present, will be executed upon exit
from the immediately preceding @code{@@try @dots{} @@catch} section.
This will happen regardless of whether any exceptions are thrown,
caught or rethrown inside the @code{@@try @dots{} @@catch} section,
analogously to the behavior of the @code{finally} clause in Java.
There are several caveats to using the new exception mechanism:
@itemize @bullet
@item
The @option{-fobjc-exceptions} command line option must be used when
compiling Objective-C files that use exceptions.
@item
With the GNU runtime, exceptions are always implemented as ``native''
exceptions and it is recommended that the @option{-fexceptions} and
@option{-shared-libgcc} options are used when linking.
@item
With the NeXT runtime, although currently designed to be binary
compatible with @code{NS_HANDLER}-style idioms provided by the
@code{NSException} class, the new exceptions can only be used on Mac
OS X 10.3 (Panther) and later systems, due to additional functionality
needed in the NeXT Objective-C runtime.
@item
As mentioned above, the new exceptions do not support handling
types other than Objective-C objects. Furthermore, when used from
Objective-C++, the Objective-C exception model does not interoperate with C++
exceptions at this time. This means you cannot @code{@@throw} an exception
from Objective-C and @code{catch} it in C++, or vice versa
(i.e., @code{throw @dots{} @@catch}).
@end itemize
@c =========================================================================
@node Synchronization
@section Synchronization
GNU Objective-C provides support for synchronized blocks:
@smallexample
@@synchronized (ObjCClass *guard) @{
@dots{}
@}
@end smallexample
Upon entering the @code{@@synchronized} block, a thread of execution
shall first check whether a lock has been placed on the corresponding
@code{guard} object by another thread. If it has, the current thread
shall wait until the other thread relinquishes its lock. Once
@code{guard} becomes available, the current thread will place its own
lock on it, execute the code contained in the @code{@@synchronized}
block, and finally relinquish the lock (thereby making @code{guard}
available to other threads).
Unlike Java, Objective-C does not allow for entire methods to be
marked @code{@@synchronized}. Note that throwing exceptions out of
@code{@@synchronized} blocks is allowed, and will cause the guarding
object to be unlocked properly.
Because of the interactions between synchronization and exception
handling, you can only use @code{@@synchronized} when compiling with
exceptions enabled, that is with the command line option
@option{-fobjc-exceptions}.
|