1 /** Interface to ObjC runtime for GNUStep
2    Copyright (C) 1995, 1997, 2000, 2002, 2003 Free Software Foundation, Inc.
3 
4    Written by:  Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
5    Date: 1995
6    Written by:  Richard Frith-Macdonald <rfm@gnu.org>
7    Date: 2002
8 
9    This file is part of the GNUstep Base Library.
10 
11    This library is free software; you can redistribute it and/or
12    modify it under the terms of the GNU Lesser General Public
13    License as published by the Free Software Foundation; either
14    version 2 of the License, or (at your option) any later version.
15 
16    This library is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19    Library General Public License for more details.
20 
21    You should have received a copy of the GNU Lesser General Public
22    License along with this library; if not, write to the Free
23    Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24    Boston, MA 02111 USA.
25 
26     AutogsdocSource: Additions/GSObjCRuntime.m
27 
28    */
29 
30 #ifndef __GSObjCRuntime_h_GNUSTEP_BASE_INCLUDE
31 #define __GSObjCRuntime_h_GNUSTEP_BASE_INCLUDE
32 
33 #import "GSVersionMacros.h"
34 #import "GSConfig.h"
35 
36 #include <stdio.h>
37 
38 #if 1 || NeXT_RUNTIME
39  #include <objc/objc.h>
40  #include <objc/objc-class.h>
41  #include <objc/objc-runtime.h>
42  #ifndef _C_ATOM
43   #define _C_ATOM '%'
44  #endif
45  #define _F_CONST    0x01
46  #define _F_IN       0x01
47  #define _F_OUT      0x02
48  #define _F_INOUT    0x03
49  #define _F_BYCOPY   0x04
50  #define _F_ONEWAY   0x08
51  #define _C_CONST    'r'
52  #define _C_IN       'n'
53  #define _C_INOUT    'N'
54  #define _C_OUT      'o'
55  #define _C_BYCOPY   'O'
56  #define _C_ONEWAY   'V'
57 #else				/* GNU Objective C Runtime */
58  #include <objc/objc.h>
59  #if defined (__GNU_LIBOBJC__)
60   #include <objc/runtime.h>
61  #else
62   #include <objc/objc-api.h>
63   #include <objc/encoding.h>
64  #endif
65 #endif
66 
67 /*
68  * Hack for older compiler versions that don't have all defines
69  * needed in  objc-api.h
70  */
71 #ifndef	_C_LNG_LNG
72 #define	_C_LNG_LNG	'q'
73 #endif
74 #ifndef	_C_ULNG_LNG
75 #define	_C_ULNG_LNG	'Q'
76 #endif
77 
78 #if	OBJC2RUNTIME
79 /* We have a real ObjC2 runtime.
80  */
81 #include <objc/runtime.h>
82 #else
83 /* We emulate an ObjC2 runtime.
84  */
85 #include <ObjectiveC2/objc/runtime.h>
86 #endif
87 
88 #ifdef __cplusplus
89 extern "C" {
90 #endif
91 
92 @class	NSArray;
93 @class	NSDictionary;
94 @class	NSObject;
95 @class	NSString;
96 @class	NSValue;
97 
98 #ifndef YES
99 #define YES		1
100 #endif
101 #ifndef NO
102 #define NO		0
103 #endif
104 #ifndef nil
105 #define nil		0
106 #endif
107 
108 #if	!defined(_C_CONST)
109 #define _C_CONST        'r'
110 #endif
111 #if	!defined(_C_IN)
112 #define _C_IN           'n'
113 #endif
114 #if	!defined(_C_INOUT)
115 #define _C_INOUT        'N'
116 #endif
117 #if	!defined(_C_OUT)
118 #define _C_OUT          'o'
119 #endif
120 #if	!defined(_C_BYCOPY)
121 #define _C_BYCOPY       'O'
122 #endif
123 #if	!defined(_C_BYREF)
124 #define _C_BYREF        'R'
125 #endif
126 #if	!defined(_C_ONEWAY)
127 #define _C_ONEWAY       'V'
128 #endif
129 #if	!defined(_C_GCINVISIBLE)
130 #define _C_GCINVISIBLE  '!'
131 #endif
132 
133 /*
134  * Functions for accessing instance variables directly -
135  * We can copy an ivar into arbitrary data,
136  * Get the type encoding for a named ivar,
137  * and copy a value into an ivar.
138  */
139 GS_EXPORT BOOL
140 GSObjCFindVariable(id obj, const char *name,
141 		   const char **type, unsigned int *size, int *offset);
142 
143 GS_EXPORT void
144 GSObjCGetVariable(id obj, int offset, unsigned int size, void *data);
145 
146 GS_EXPORT void
147 GSObjCSetVariable(id obj, int offset, unsigned int size, const void *data);
148 
149 GS_EXPORT NSArray *
150 GSObjCMethodNames(id obj, BOOL recurse);
151 
152 GS_EXPORT NSArray *
153 GSObjCVariableNames(id obj, BOOL recurse);
154 
155 /**
156  * <p>A Behavior can be seen as a "Protocol with an implementation" or a
157  * "Class without any instance variables".  A key feature of behaviors
158  * is that they give a degree of multiple inheritance.
159  * </p>
160  * <p>Behavior methods, when added to a class, override the class's
161  * superclass methods, but not the class's methods.
162  * </p>
163  * <p>Whan a behavior class is added to a receiver class, not only are the
164  * methods defined in the behavior class added, but the methods from the
165  * behavior's class hierarchy are also added (unless already present).
166  * </p>
167  * <p>It's not the case that a class adding behaviors from another class
168  * must have "no instance vars".  The receiver class just has to have the
169  * same layout as the behavior class (optionally with some additional
170  * ivars after those of the behavior class).
171  * </p>
172  * <p>This function provides Behaviors without adding any new syntax to
173  * the Objective C language.  Simply define a class with the methods you
174  * want to add, then call this function with that class as the behavior
175  * argument.
176  * </p>
177  * <p>This function should be called in the +initialize method of the receiver.
178  * </p>
179  * <p>If you add several behaviors to a class, be aware that the order of
180  * the additions is significant.
181  * </p>
182  */
183 GS_EXPORT void
184 GSObjCAddClassBehavior(Class receiver, Class behavior);
185 
186 /**
187  * <p>An Override can be seen as a "category implemented as a separate class
188  * and manually added to the receiver class under program control, rather
189  * than automatically added by the compiler/runtime.
190  * </p>
191  * <p>Override methods, when added to a receiver class, replace the class's
192  * class's methods of the same name (or are added if the class did not define
193  * methods with that name).
194  * </p>
195  * <p>It's not the case that a class adding overrides from another class
196  * must have "no instance vars".  The receiver class just has to have the
197  * same layout as the override class (optionally with some additional
198  * ivars after those of the override class).
199  * </p>
200  * <p>This function provides overrides without adding any new syntax to
201  * the Objective C language.  Simply define a class with the methods you
202  * want to add, then call this function with that class as the override
203  * argument.
204  * </p>
205  * <p>This function should usually be called in the +initialize method
206  * of the receiver.
207  * </p>
208  * <p>If you add several overrides to a class, be aware that the order of
209  * the additions is significant.
210  * </p>
211  */
212 GS_EXPORT void
213 GSObjCAddClassOverride(Class receiver, Class override);
214 
215 /** Turn on (YES), off (NO) or test (-1) behavior debugging.
216  */
217 GS_EXPORT BOOL GSObjCBehaviorDebug(int setget);
218 
219 GS_EXPORT NSValue *
220 GSObjCMakeClass(NSString *name, NSString *superName, NSDictionary *iVars);
221 
222 GS_EXPORT void
223 GSObjCAddClasses(NSArray *classes);
224 
225 /**
226  * Given a NULL terminated list of methods, add them to the class.<br />
227  * If the method already exists in a superclass, the new version overrides
228  * that one, but if the method already exists in the class itsself, the
229  * new one is quietly ignored (replace==NO) or replaced with the new
230  * version (if replace==YES).<br />
231  * To add class methods, cls should be the metaclass of the class to
232  * which the methods are being added.
233  */
234 GS_EXPORT void
235 GSObjCAddMethods(Class cls, Method *list, BOOL replace);
236 
237 /*
238  * Functions for key-value encoding ... they access values in an object
239  * either by selector or directly, but do so using NSNumber for the
240  * scalar types of data.
241  */
242 GS_EXPORT id
243 GSObjCGetVal(NSObject *self, const char *key, SEL sel,
244   const char *type, unsigned size, int offset);
245 
246 GS_EXPORT void
247 GSObjCSetVal(NSObject *self, const char *key, id val, SEL sel,
248   const char *type, unsigned size, int offset);
249 
250 /*
251  * This section includes runtime functions
252  * to query and manipulate the ObjC runtime structures.
253  * These functions take care to not use ObjC code so
254  * that they can safely be used in +(void)load implementations
255  * where applicable.
256  */
257 
258 /**
259  * Deprecated ... use objc_getClassList()
260  */
261 GS_EXPORT unsigned int
262 GSClassList(Class *buffer, unsigned int max, BOOL clearCache);
263 
264 /**
265  * GSObjCClass() is deprecated ... use object_getClass()
266  */
267 GS_EXPORT Class GSObjCClass(id obj);
268 
269 /**
270  * GSObjCSuper() is deprecated ... use class_getSuperclass()
271  */
272 GS_EXPORT Class GSObjCSuper(Class cls);
273 
274 /**
275  * GSObjCIsInstance() is deprecated ... use object_getClass()
276  * in conjunction with class_isMetaClass()
277  */
278 GS_EXPORT BOOL GSObjCIsInstance(id obj);
279 
280 /**
281  * GSObjCIsClass() is deprecated ... use object_getClass()
282  * in conjunction with class_isMetaClass()
283  */
284 GS_EXPORT BOOL GSObjCIsClass(Class cls);
285 
286 /**
287  * Test to see if class inherits from another class
288  * The argument to this function must NOT be nil.
289  */
290 GS_EXPORT BOOL GSObjCIsKindOf(Class cls, Class other);
291 
292 /**
293  * GSClassFromName() is deprecated ... use objc_lookUpClass()
294  */
295 GS_EXPORT Class GSClassFromName(const char *name);
296 
297 /**
298  * GSNameFromClass() is deprecated ... use class_getName()
299  */
300 GS_EXPORT const char *GSNameFromClass(Class cls);
301 
302 /**
303  * GSClassNameFromObject() is deprecated ... use object_getClass()
304  * in conjunction with class_getName()
305  */
306 GS_EXPORT const char *GSClassNameFromObject(id obj);
307 
308 /**
309  * GSNameFromSelector() is deprecated ... use sel_getName()
310  */
311 GS_EXPORT const char *GSNameFromSelector(SEL sel);
312 
313 /**
314  * GSSelectorFromName() is deprecated ... use sel_getUid()
315  */
316 GS_EXPORT SEL
317 GSSelectorFromName(const char *name);
318 
319 /**
320  * Return the selector for the specified name and types.<br />
321  * Returns a nul pointer if the name is nul.<br />
322  * Creates a new selector if necessary.<br />
323  * Code must NOT rely on this providing a selector with type information.
324  */
325 GS_EXPORT SEL
326 GSSelectorFromNameAndTypes(const char *name, const char *types);
327 
328 /**
329  * Return the type information from the specified selector.<br />
330  * May return a nul pointer if the selector was a nul pointer or if it
331  * was not typed (or if the runtime does not support typed selectors).<br />
332  * Code must NOT rely on this providing any type information.
333  */
334 GS_EXPORT const char *
335 GSTypesFromSelector(SEL sel);
336 
337 /**
338  * Compare only the type information ignoring qualifiers, the frame layout
339  * and register markers.  Unlike sel_types_match, this function also
340  * handles comparisons of types with and without any layout information.
341  */
342 GS_EXPORT BOOL
343 GSSelectorTypesMatch(const char *types1, const char *types2);
344 
345 /** Takes full type information and skips forward to the actual type
346  * as specified in the _C_... constants.
347  */
348 GS_EXPORT const char *
349 GSSkipTypeQualifierAndLayoutInfo(const char *types);
350 
351 /**
352  * Returns a protocol object with the corresponding name.
353  * This function searches the registered classes for any protocol
354  * with the supplied name.  If one is found, it is cached in
355  * for future requests.  If efficiency is a factor then use
356  * GSRegisterProtocol() to insert a protocol explicitly into the cache
357  * used by this function.  If no protocol is found this function returns
358  * nil.
359  */
360 GS_EXPORT Protocol *
361 GSProtocolFromName(const char *name);
362 
363 /**
364  * Registers proto in the cache used by GSProtocolFromName().
365  */
366 GS_EXPORT void
367 GSRegisterProtocol(Protocol *proto);
368 
369 /**
370  * A variant of protocol_getMethodDescription which recursively searches
371  * parent protocols if the requested selector isn't found in the given
372  * protocol.
373  *
374  * Returns a {NULL, NULL} structure if the requested selector couldn't be
375  * found.
376  */
377 GS_EXPORT struct objc_method_description
378 GSProtocolGetMethodDescriptionRecursive(Protocol *aProtocol, SEL aSel, BOOL isRequired, BOOL isInstance);
379 
380 /*
381  * Unfortunately the definition of the symbols
382  * 'Method(_t)', 'MethodList(_t)'  and 'IVar(_t)'
383  * are incompatible between the GNU and NeXT/Apple runtimes.
384  * We introduce GSMethod, GSMethodList and GSIVar to allow portability.
385  */
386 typedef Method	GSMethod;
387 typedef Ivar	GSIVar;
388 
389 /**
390  * Returns the pointer to the method structure
391  * for the selector in the specified class.
392  * Depending on searchInstanceMethods, this function searches
393  * either instance or class methods.
394  * Depending on searchSuperClassesm this function searches
395  * either the specified class only or also its superclasses.<br/>
396  * To obtain the implementation pointer IMP use returnValue->method_imp
397  * which should be safe across all runtimes.<br/>
398  * It should be safe to use this function in +load implementations.<br/>
399  * This function should currently (June 2004) be considered WIP.
400  * Please follow potential changes (Name, parameters, ...) closely until
401  * it stabilizes.
402  */
403 GS_EXPORT GSMethod
404 GSGetMethod(Class cls, SEL sel,
405 	    BOOL searchInstanceMethods,
406 	    BOOL searchSuperClasses);
407 
408 /**
409  * Deprecated .. does nothing.
410  */
411 GS_EXPORT void
412 GSFlushMethodCacheForClass (Class cls);
413 
414 /**
415  * Deprecated .. use class_getInstanceVariable()
416  */
417 GS_EXPORT GSIVar
418 GSCGetInstanceVariableDefinition(Class cls, const char *name);
419 
420 /**
421  * Deprecated .. use class_getInstanceVariable()
422  */
423 GS_EXPORT GSIVar
424 GSObjCGetInstanceVariableDefinition(Class cls, NSString *name);
425 
426 /**
427  * GSObjCVersion() is deprecated ... use class_getVersion()
428  */
429 GS_EXPORT int GSObjCVersion(Class cls);
430 
431 /**
432  * Quickly return autoreleased data storage area.
433  */
434 GS_EXPORT void *
435 GSAutoreleasedBuffer(unsigned size);
436 
437 /**
438  * <p>Prints a message to fptr using the format string provided and any
439  * additional arguments.  The format string is interpreted as by
440  * the NSString formatted initialisers, and understands the '%@' syntax
441  * for printing an object.
442  * </p>
443  * <p>The data is written to the file pointer in the default CString
444  * encoding if possible, as a UTF8 string otherwise.
445  * </p>
446  * <p>This function is recommended for printing general log messages.
447  * For debug messages use NSDebugLog() and friends.  For error logging
448  * use NSLog(), and for warnings you might consider NSWarnLog().
449  * </p>
450  */
451 GS_EXPORT BOOL
452 GSPrintf (FILE *fptr, NSString *format, ...);
453 
454 
455 
456 GS_EXPORT NSArray *
457 GSObjCAllSubclassesOfClass(Class cls);
458 
459 GS_EXPORT NSArray *
460 GSObjCDirectSubclassesOfClass(Class cls);
461 
462 /** Function to change the class of the specified instance to newClass.
463  * This handles memory debugging issues in GNUstep-base and also
464  * deals with class finalisation issues in a garbage collecting
465  * environment, so you should use this function rather than attempting
466  * to swizzle class pointers directly.
467  */
468 GS_EXPORT void
469 GSClassSwizzle(id instance, Class newClass);
470 
471 #if !defined(GS_GNUSTEP_V) || (GS_GNUSTEP_V >= GS_API_ANY && GS_GNUSTEP_V < 011500)
472 //GS_API_VERSION(GS_API_ANY,011500)
473 
474 GS_EXPORT const char *
475 GSLastErrorStr(long error_id) GS_DEPRECATED_FUNC;
476 
477 #endif
478 
479 
480 
481 #ifndef	GS_MAX_OBJECTS_FROM_STACK
482 /**
483  * The number of objects to try to get from varargs into an array on
484  * the stack ... if there are more than this, use the heap.
485  * NB. This MUST be a multiple of 2
486  */
487 #define	GS_MAX_OBJECTS_FROM_STACK	128
488 #endif
489 
490 /**
491  * <p>This is a macro designed to minimise the use of memory allocation and
492  * deallocation when you need to work with a vararg list of objects.<br />
493  * The objects are unpacked from the vararg list into two 'C' arrays and
494  * then a code fragment you specify is able to make use of them before
495  * that 'C' array is destroyed.
496  * </p>
497  * <p>The firstObject argument is the name of the formal parameter in your
498  * method or function which precedes the ', ...' denoting variable args.
499  * </p>
500  * <p>The code argument is a piece of objective-c code to be executed to
501  * make use of the objects stored in the 'C' arrays.<br />
502  * When this code is called the unsigned integer '__count' will contain the
503  * number of objects unpacked, the pointer '__objects' will point to
504  * the first object in each pair, and the pointer '__pairs' will point
505  * to an array containing the second halves of the pairs of objects
506  * whose first halves are in '__objects'.<br />
507  * This lets you pack a list of the form 'key, value, key, value, ...'
508  * into an array of keys and an array of values.
509  * </p>
510  */
511 #define GS_USEIDPAIRLIST(firstObject, code...) ({\
512   va_list	__ap; \
513   unsigned int	__max = GS_MAX_OBJECTS_FROM_STACK; \
514   unsigned int	__count = 0; \
515   id		__buf[__max]; \
516   id		*__objects = __buf; \
517   id		*__pairs = &__objects[__max/2]; \
518   id		__obj = firstObject; \
519   va_start(__ap, firstObject); \
520   while (__obj != nil && __count < __max) \
521     { \
522       if ((__count % 2) == 0) \
523 	{ \
524 	  __objects[__count/2] = __obj; \
525 	} \
526       else \
527 	{ \
528 	  __pairs[__count/2] = __obj; \
529 	} \
530       __obj = va_arg(__ap, id); \
531       if (++__count == __max) \
532 	{ \
533 	  while (__obj != nil) \
534 	    { \
535 	      __count++; \
536 	      __obj = va_arg(__ap, id); \
537 	    } \
538 	} \
539     } \
540   if ((__count % 2) == 1) \
541     { \
542       __pairs[__count/2] = nil; \
543       __count++; \
544     } \
545   va_end(__ap); \
546   if (__count > __max) \
547     { \
548       unsigned int	__tmp; \
549       __objects = (id*)malloc(__count*sizeof(id)); \
550       __pairs = &__objects[__count/2]; \
551       __objects[0] = firstObject; \
552       va_start(__ap, firstObject); \
553       for (__tmp = 1; __tmp < __count; __tmp++) \
554 	{ \
555 	  if ((__tmp % 2) == 0) \
556 	    { \
557 	      __objects[__tmp/2] = va_arg(__ap, id); \
558 	    } \
559 	  else \
560 	    { \
561 	      __pairs[__tmp/2] = va_arg(__ap, id); \
562 	    } \
563 	} \
564       va_end(__ap); \
565     } \
566   code; \
567   if (__objects != __buf) free(__objects); \
568 })
569 
570 /**
571  * <p>This is a macro designed to minimise the use of memory allocation and
572  * deallocation when you need to work with a vararg list of objects.<br />
573  * The objects are unpacked from the vararg list into a 'C' array and
574  * then a code fragment you specify is able to make use of them before
575  * that 'C' array is destroyed.
576  * </p>
577  * <p>The firstObject argument is the name of the formal parameter in your
578  * method or function which precedes the ', ...' denoting variable args.
579  * </p>
580  * <p>The code argument is a piece of objective-c code to be executed to
581  * make use of the objects stored in the 'C' array.<br />
582  * When this code is called the unsigned integer '__count' will contain the
583  * number of objects unpacked, and the pointer '__objects' will point to
584  * the unpacked objects, ie. firstObject followed by the vararg arguments
585  * up to (but not including) the first nil.
586  * </p>
587  */
588 #define GS_USEIDLIST(firstObject, code...) ({\
589   va_list	__ap; \
590   unsigned int	__max = GS_MAX_OBJECTS_FROM_STACK; \
591   unsigned int	__count = 0; \
592   id		__buf[__max]; \
593   id		*__objects = __buf; \
594   id		__obj = firstObject; \
595   va_start(__ap, firstObject); \
596   while (__obj != nil && __count < __max) \
597     { \
598       __objects[__count] = __obj; \
599       __obj = va_arg(__ap, id); \
600       if (++__count == __max) \
601 	{ \
602 	  while (__obj != nil) \
603 	    { \
604 	      __count++; \
605 	      __obj = va_arg(__ap, id); \
606 	    } \
607 	} \
608     } \
609   va_end(__ap); \
610   if (__count > __max) \
611     { \
612       unsigned int	__tmp; \
613       __objects = (id*)NSZoneMalloc(NSDefaultMallocZone(),__count*sizeof(id)); \
614       va_start(__ap, firstObject); \
615       __objects[0] = firstObject; \
616       for (__tmp = 1; __tmp < __count; __tmp++) \
617 	{ \
618 	  __objects[__tmp] = va_arg(__ap, id); \
619 	} \
620       va_end(__ap); \
621     } \
622   code; \
623   if (__objects != __buf) NSZoneFree (NSDefaultMallocZone(),__objects); \
624 })
625 
626 
627 #ifdef __cplusplus
628 }
629 #endif
630 
631 #endif /* __GSObjCRuntime_h_GNUSTEP_BASE_INCLUDE */
632