File: GSTypeEncoding.c

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (730 lines) | stat: -rw-r--r-- 20,562 bytes parent folder | download | duplicates (5)
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
/*
 * Objective-C type encoding support
 *
 * Copyright (C) 2012-2013 Free Software Foundation, Inc.
 *
 * Written by Marat Ibadinov <ibadinov@me.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "GNUstepBase/GSTypeEncoding.h"

#include <stdlib.h>
#include <string.h>

#undef  MAX
#define MAX(X, Y)                     \
({                                    \
  typeof (X) __x = (X), __y = (Y);    \
  (__x > __y ? __x : __y);            \
})

/*
 * We store here aligned sizes of primitive types
 * and bit-masks of type qualifiers
 */
static const int8_t typeInfoTable[] =
{
  /* types */
  [GSObjCTypeId]                  = sizeof(id),
  [GSObjCTypeClass]               = sizeof(Class),
  [GSObjCTypeSelector]            = sizeof(SEL),
  [GSObjCTypeChar]                = sizeof(char),
  [GSObjCTypeUnsignedChar]        = sizeof(unsigned char),
  [GSObjCTypeShort]               = sizeof(short),
  [GSObjCTypeUnsignedShort]       = sizeof(unsigned short),
  [GSObjCTypeInt]                 = sizeof(int),
  [GSObjCTypeUnsignedInt]         = sizeof(unsigned int),
  [GSObjCTypeLong]                = sizeof(long),
  [GSObjCTypeUnsignedLong]        = sizeof(unsigned long),
  [GSObjCTypeLongLong]            = sizeof(long long),
  [GSObjCTypeUnsignedLongLong]    = sizeof(unsigned long long),
  [GSObjCTypeFloat]               = sizeof(float),
  [GSObjCTypeDouble]              = sizeof(double),
  [GSObjCTypeBool]                = sizeof(_Bool),
  [GSObjCTypeVoid]                = sizeof(void),
  /* here would go Pointer, but in most cases it needs special treatment */
  [GSObjCTypeCharPointer]         = sizeof(char *),
  [GSObjCTypeAtom]                = sizeof(void *),
  /* type qualifiers (negated for distinctiveness) */
  [GSObjCQualifierConst]          = -GSObjCQualifierConstMask,
  [GSObjCQualifierIn]             = -GSObjCQualifierInMask,
  [GSObjCQualifierInOut]          = -GSObjCQualifierInOutMask,
  [GSObjCQualifierOut]            = -GSObjCQualifierOutMask,
  [GSObjCQualifierByCopy]         = -GSObjCQualifierByCopyMask,
  [GSObjCQualifierByRef]          = -GSObjCQualifierByRefMask,
  [GSObjCQualifierOneWay]         = -GSObjCQualifierOneWayMask,
  [GSObjCQualifierInvisible]      = -GSObjCQualifierInvisible,
  /* ensure an appropriate table size */
  [GSObjCTypeMax]                 = 0
};

/* all substripts of typeInfoTable are of char type */
#ifdef  __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wchar-subscripts"
#endif

GS_STATIC_INLINE uint8_t
RoundToThePowerOfTwo (uint8_t value)
{
  --value;
  value |= value >> 1;
  value |= value >> 2;
  value |= value >> 4;
  return ++value;
}

GS_STATIC_INLINE const char *
GetNumericValue (const char *cursor, int *value)
{
  *value = 0;
  while (*cursor >= '0' && *cursor <= '9')
    {
      *value = 10 * (*value) + (*cursor++ - '0');
    }
  return cursor;
}

GS_STATIC_INLINE const char *
SkipName (const char *cursor)
{
  if (*cursor == '"')
    {
      for (++cursor; *cursor++ != '"';);
    }
  return cursor;
}

GS_STATIC_INLINE const char *
SkipType (const char *cursor)
{
  unsigned depth = 0;
  do {
    while (typeInfoTable[(int)*cursor] < 0)
      {
        ++cursor;
      }
    
    if (!typeInfoTable[(int)*cursor])
      {
        switch (*cursor)
          {
            case GSObjCTypeArrayBegin:
            case GSObjCTypeStructureBegin:
            case GSObjCTypeUnionBegin:
              ++depth;
              break;
            case GSObjCTypeArrayEnd:
            case GSObjCTypeStructureEnd:
            case GSObjCTypeUnionEnd:
              --depth;
              break;
            case GSObjCTypePointer:
              ++cursor;
            default:
              break;
          }
      }
    cursor = SkipName(++cursor);
  } while (depth);
  return cursor;
}

GS_STATIC_INLINE const char *
GetQualifiers (const char *cursor, uint8_t *qualifiers)
{
  *qualifiers = 0;
  while (typeInfoTable[(int)*cursor] < 0)
    {
      *qualifiers |= (uint8_t) -typeInfoTable[(int)*cursor];
      ++cursor;
    }
  return cursor;
}

typedef struct ParserStackElement
{
  const char *cursor;
  size_t      size;
  size_t      count; /* for arrays */
  char        alignment;
  char        qualifiers;
} ParserStackElement;


typedef struct ParserOutput
{
  GSObjCTypeInfo      info;
  unsigned            parentDepth;
  BOOL                suppressed;
} ParserOutput;

typedef struct ParserState
{
  ParserStackElement  *stack;
  ParserOutput        *buffer;
  unsigned            stackSize;
  unsigned            bufferSize;
  unsigned            allocated;
  unsigned            stackSpace;
  unsigned            bufferSpace;
} ParserState;

/**
 * Complex type nesting level of 4 or greater is a rare case.
 * With initial size of 3 total memory footprint of stack and
 * buffer is 224 bytes (on machines with 64-bit word).
 *
 * Nesting depth of 16 will require circa 1K of memory, 64 - approximately 4K.
 * Maybe it would be better to place an upper bound on nesting depth and simply
 * allocate space on stack once. This will certainly be a performance again.
 */
static const unsigned ParserInitialStackSize = 3;

GS_STATIC_INLINE ParserStackElement *
ParserStackTop (ParserState *state)
{
  return state->stackSize ? &state->stack[state->stackSize - 1] : NULL;
}

const char *
GSObjCParseTypeSpecification (const char *cursor,
                              GSObjCTypeParserDelegate delegate,
                              void *context,
                              unsigned options)
{
  ParserState state;
  unsigned suppressionDepth = 0;
  unsigned bitFieldSpaceAvailable = 0;
  ParserStackElement el;
  unsigned index;

  state.stackSize = state.bufferSize = 0;
  state.stackSpace = sizeof(ParserStackElement) * ParserInitialStackSize;
  state.bufferSpace = sizeof(ParserOutput) * (ParserInitialStackSize + 1);
  state.stack = malloc(state.stackSpace + state.bufferSpace);
  state.buffer = (void *)state.stack + state.stackSpace;
  state.allocated = ParserInitialStackSize;
  
  do {
    GSObjCTypeInfo info = {cursor, 0, 1, 0};
    BOOL pushStack = NO;
    BOOL popStack = NO;
    BOOL pushBuffer = YES;
    BOOL suppress = suppressionDepth != 0;
    unsigned parentDepth;

    cursor = GetQualifiers(cursor, &info.qualifiers);
    cursor = SkipName(cursor);
    parentDepth = state.stackSize;
    
    /* is it a primitive type? */
    if (typeInfoTable[(int)*cursor])
      {
        info.size = info.alignment = typeInfoTable[(int)*cursor];
        cursor = SkipName(++cursor);
      }
    else
      {
        switch (*cursor) {
          case GSObjCTypeBitField:
            {
              int totalBitCount = -bitFieldSpaceAvailable;
              int bitCount = 0;

              info.alignment = 1;
              while (totalBitCount < 8 && *cursor == GSObjCTypeBitField)
              /* can we emit token */
                {
                  cursor = GetNumericValue(++cursor, &bitCount);
                  totalBitCount += bitCount;
                  /* round bitCount to the nearest power of 2 */
                  info.alignment
                    = MAX(info.alignment, RoundToThePowerOfTwo(bitCount) / 8);
                }
              info.size = totalBitCount / 8
                + ((totalBitCount & 7 /* mod 8 */) != 0);
              if (*cursor == GSObjCTypeBitField)
                {
                  bitFieldSpaceAvailable
                    = (unsigned)info.alignment * 8 - totalBitCount;
                }
              else
                bitFieldSpaceAvailable = 0;
              break;
            }
          case GSObjCTypePointer:
            {
              info.size = info.alignment = sizeof(void *);
              cursor = SkipType(++cursor);
              break;
            }
          case GSObjCTypeComplex:
            {
              info.size = 2 * (info.alignment = typeInfoTable[(int)*++cursor]);
              ++cursor;
              break;
            }
          case GSObjCTypeArrayBegin:
            {
              int length;

              cursor = GetNumericValue(++cursor, &length);
              el = (ParserStackElement){
                cursor, 0, length - 1, 1, info.qualifiers
              };
              pushStack = YES;
              suppressionDepth += (options & GSObjCReportArrayOnceMask) != 0;
              break;
            }
          case GSObjCTypeStructureBegin:
            {
              el = (ParserStackElement){cursor, 0, 0, 1, info.qualifiers};
              /* skip typename annotation */
              while (*cursor != GSObjCTypeStructureEnd && *cursor++ != '=');
              pushStack = YES;
              break;
            }
          case GSObjCTypeUnionBegin:
            {
              el = (ParserStackElement){cursor, 0, 0, 1, info.qualifiers};
              /* skip typename annotation */
              while (*cursor != GSObjCTypeUnionEnd && *cursor++ != '=');
              ++suppressionDepth;
              pushStack = YES;
              break;
            }
          case GSObjCTypeUnionEnd:
          case GSObjCTypeArrayEnd:
          case GSObjCTypeStructureEnd:
            {
              popStack = YES;
              break;
            }
            
          default:
            abort();
        }
      }
    
    if (pushStack)
      {
        if (state.stackSize == state.allocated)
          {
            unsigned stackSpace;
            unsigned bufferSpace;
            void *data;

            state.allocated *= 2;
            stackSpace = sizeof(ParserStackElement) * state.allocated;
            bufferSpace = sizeof(ParserOutput) * (state.allocated + 1);
            data = malloc(stackSpace + bufferSpace);
            memcpy(data, state.stack, state.stackSpace);
            memcpy(data + stackSpace, state.buffer, state.bufferSpace);
            free(state.stack);
            state.stack = data;
            state.buffer = (void *)data + stackSpace;
            state.stackSpace = stackSpace;
            state.bufferSpace = bufferSpace;
          }
        state.stack[state.stackSize] = el;
        ++state.stackSize;
      }
    else
      {
        /* we can safely flush the buffer */
        for (index = 0; index < state.bufferSize; ++index)
          {
            GSObjCTypeInfo output = state.buffer[index].info;
            unsigned depth = state.buffer[index].parentDepth;

            if (depth)
              {
                ParserStackElement *parent = &state.stack[depth - 1];

                if (*parent->cursor != GSObjCTypeUnionBegin)
                  {
                    size_t alignedSize;

                    /* in array and structure we should align data according
                     * to the element that triggered flushing (it may be the
                     * next real member of the data-structure or a closing
                     * tag)
                     */
                    output.alignment = MAX(output.alignment, info.alignment);
                    alignedSize = GSObjCPadSize(output.size, output.alignment);
                    parent->size += alignedSize;
                  }
                else
                  {
                    parent->size = MAX(parent->size, output.size);
                  }
                parent->alignment = MAX(parent->alignment, output.alignment);
              }
            if (!state.buffer[index].suppressed)
              {
                delegate(context, output);
              }
          }
        state.bufferSize = 0;
      }
    
    if (popStack)
      {
        ParserStackElement *element = ParserStackTop(&state);

        switch (*cursor)
          {
            case GSObjCTypeUnionEnd:
              --suppressionDepth;       /* FALLTHROUGH */
            case GSObjCTypeArrayEnd:
              {
                if (element->count)
                  {
                    if (options & GSObjCReportArrayOnceMask)
                      {
                        /* we need to compensate "length - 1" */
                        element->size *= (element->count + 1);
                        --suppressionDepth;
                      }
                    else
                      {
                        /* decrease length and rewind */
                        --element->count;
                        cursor = element->cursor;
                        pushBuffer = NO;
                        break;
                      }
                  }
              }         /* FALLTHROUGH */
            case GSObjCTypeStructureEnd:
              {
                info.qualifiers = element->qualifiers;
                info.size = element->size;
                info.alignment = element->alignment;
                parentDepth = --state.stackSize;
                ++cursor;
                break;
              }
          }
      }
    
    if (pushBuffer)
      {
        /* outermost GSObjCTypeUnionBegin and GSObjCTypeUnionEnd
         * should be reported
         */
        state.buffer[state.bufferSize].suppressed
          = suppress && suppressionDepth != 0;
        state.buffer[state.bufferSize].parentDepth  = parentDepth;
        state.buffer[state.bufferSize].info         = info;
        ++state.bufferSize;
      }
  } while (state.stackSize);
  
  for (index = 0; index < state.bufferSize; ++index)
    {
      if (!state.buffer[index].suppressed)
        {
          delegate(context, state.buffer[index].info);
        }
    }
  
  free(state.stack);
  
  return cursor;
}

#ifdef  __clang__
#pragma GCC diagnostic pop
#endif

typedef struct InfoAccumulator
{
  size_t  size;
  char    alignment;
} InfoAccumulator;

static void
InfoAccumulatorAddInfo (InfoAccumulator *this, GSObjCTypeInfo info)
{
  /* if it's the end of structure, accumulate only padding */
  if (*info.type == GSObjCTypeStructureEnd)
      this->size += GSObjCGetPadding (info.size, info.alignment);
  else
      this->size += GSObjCPadSize (info.size, info.alignment);
  this->alignment = MAX(this->alignment, info.alignment);
}

const char *
GSGetSizeAndAlignment (const char *type, size_t *sizep, uint8_t *alignp)
{
  InfoAccumulator accumulator = {0, 0};
  type = GSObjCParseTypeSpecification (type,
    (GSObjCTypeParserDelegate)&InfoAccumulatorAddInfo,
    &accumulator,
    GSObjCReportArrayOnceMask);
  if (sizep)
    {
      *sizep = accumulator.size;
    }
  if (alignp)
    {
      *alignp = accumulator.alignment;
    }
  return type;
}


#if defined (NeXT_RUNTIME)

/* emulate GNU API */

typedef struct SizeInfoAccumulator
{
  size_t      size;
  unsigned    depth;
} SizeInfoAccumulator;

static void
SizeInfoAccumulatorAddInfo (SizeInfoAccumulator *this, GSObjCTypeInfo info)
{
  /* we wait until typespec's last element and save it's unaligned size */
  switch (*info.type)
  {
    case GSObjCTypeArrayBegin:
    case GSObjCTypeStructureBegin:
    case GSObjCTypeUnionBegin:
      ++this->depth;
      break;
    case GSObjCTypeArrayEnd:
    case GSObjCTypeStructureEnd:
    case GSObjCTypeUnionEnd:
      --this->depth;
      break;
    default:
      break;
  }
  if (!this->depth)
    {
      this->size += info.size;
    }
}

int
objc_sizeof_type (const char* type)
{
  SizeInfoAccumulator accumulator = {0, 0};
  GSObjCParseTypeSpecification (type,
    (GSObjCTypeParserDelegate)&SizeInfoAccumulatorAddInfo,
    &accumulator,
    GSObjCReportArrayOnceMask);
  return (int)accumulator.size;
}

int
objc_alignof_type (const char* type)
{
  uint8_t alignment;
  GSGetSizeAndAlignment (type, NULL, &alignment);
  return (int)alignment;
}

int
objc_aligned_size (const char* type)
{
  size_t size;
  GSGetSizeAndAlignment (type, &size, NULL);
  return (int)size;
}

int
objc_promoted_size (const char* type)
{
  size_t size;
  GSGetSizeAndAlignment (type, &size, NULL);
  return (int)GSObjCPadSize (size, sizeof(void *));
}

/* we should not instantiate this function more than once */
static const char *
GetQualifiersInst (const char *cursor, uint8_t *qualifiers)
{
  return GetQualifiers (cursor, qualifiers);
}

/* we should not instantiate this function more than once */
static const char *
SkipTypeInst (const char *cursor)
{
  return SkipType(cursor);
}

unsigned
objc_get_type_qualifiers (const char* type)
{
  uint8_t qualifiers;
  GetQualifiersInst (type, &qualifiers);
  return qualifiers;
}

const char *
objc_skip_type_qualifiers (const char* type)
{
  uint8_t qualifiers;
  return GetQualifiersInst (type, &qualifiers);
}

const char *
objc_skip_typespec (const char* type)
{
  uint8_t qualifiers;
  type = GetQualifiersInst (type, &qualifiers);
  return SkipTypeInst (type);
}

const char *
objc_skip_offset (const char* type)
{
  if (*type == '+' || *type == '-')
    {
      type++;
    }
  while (*type >= '0' && *type <= '9')
    {
      type++;
    }
  return type;
}

const char *
objc_skip_argspec (const char* type)
{
  type = SkipTypeInst (type);
  return objc_skip_offset (type);
}

static void
objc_layout_structure_append_info(struct objc_struct_layout *this,
                                  GSObjCTypeInfo info)
{
  if (this->count == this->allocated)
    {
      this->info = realloc(this->info, sizeof(GSObjCTypeInfo) * (this->allocated *= 2));
    }
  this->info[this->count] = info;
  ++this->count;
}

static void
objc_layout_structure_parser_delegate(struct objc_struct_layout *this,
                                      GSObjCTypeInfo info)
{
  unsigned initialDepth = this->depth;
  switch (*info.type)
  {
    case GSObjCTypeArrayEnd:
    case GSObjCTypeStructureEnd:
    case GSObjCTypeUnionEnd:
    {
      if (--this->depth == 1)
        {
          this->info[this->count - 1].size = info.size;
          this->info[this->count - 1].alignment = info.alignment;
        }
      break;
    }
    case GSObjCTypeArrayBegin:
    case GSObjCTypeStructureBegin:
    case GSObjCTypeUnionBegin:
      ++this->depth;
    default:
      if (initialDepth == 1)
        {
          objc_layout_structure_append_info(this, info);
        }
      break;
  }
}

void
objc_layout_structure (const char *type,
                       struct objc_struct_layout *layout)
{
  *layout = (struct objc_struct_layout)
  {
    malloc(8 * sizeof(GSObjCTypeInfo)),
    -1, 0, 8, 0, 0, 0
  };
  GSObjCParseTypeSpecification(type,
                               (GSObjCTypeParserDelegate)&objc_layout_structure_parser_delegate,
                               layout,
                               GSObjCReportArrayOnceMask);
}

BOOL
objc_layout_structure_next_member (struct objc_struct_layout *layout)
{
  return ++layout->position < layout->count;
}

void
objc_layout_structure_get_info (struct objc_struct_layout *layout,
                                unsigned int *offset,
                                unsigned int *align,
                                const char **type)
{
  GSObjCTypeInfo info = layout->info[layout->position];
  
  if (offset)
    {
      *offset = layout->offset;
    }
  if (align)
    {
      *align = info.alignment;
    }
  if (type)
    {
      *type = info.type;
    }
  
  layout->offset += GSObjCPadSize(info.size, info.alignment);
  layout->alignment = MAX(layout->alignment, info.alignment);
}

void
objc_layout_finish_structure (struct objc_struct_layout *layout,
                              unsigned int *size,
                              unsigned int *align)
{
  if (size)
    {
      *size = (unsigned int) GSObjCPadSize(layout->offset, layout->alignment);
    }
  if (align)
    {
      *align = layout->alignment;
    }
  free(layout->info);
}

#endif /* NeXT_RUNTIME */