• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Protocol Buffers - Google's data interchange format
2// Copyright 2008 Google Inc.  All rights reserved.
3// https://developers.google.com/protocol-buffers/
4//
5// Redistribution and use in source and binary forms, with or without
6// modification, are permitted provided that the following conditions are
7// met:
8//
9//     * Redistributions of source code must retain the above copyright
10// notice, this list of conditions and the following disclaimer.
11//     * Redistributions in binary form must reproduce the above
12// copyright notice, this list of conditions and the following disclaimer
13// in the documentation and/or other materials provided with the
14// distribution.
15//     * Neither the name of Google Inc. nor the names of its
16// contributors may be used to endorse or promote products derived from
17// this software without specific prior written permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31#import "GPBCodedInputStream_PackagePrivate.h"
32
33#import "GPBDictionary_PackagePrivate.h"
34#import "GPBMessage_PackagePrivate.h"
35#import "GPBUnknownFieldSet_PackagePrivate.h"
36#import "GPBUtilities_PackagePrivate.h"
37#import "GPBWireFormat.h"
38
39NSString *const GPBCodedInputStreamException =
40    GPBNSStringifySymbol(GPBCodedInputStreamException);
41
42NSString *const GPBCodedInputStreamUnderlyingErrorKey =
43    GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey);
44
45NSString *const GPBCodedInputStreamErrorDomain =
46    GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain);
47
48static const NSUInteger kDefaultRecursionLimit = 64;
49
50static void RaiseException(NSInteger code, NSString *reason) {
51  NSDictionary *errorInfo = nil;
52  if ([reason length]) {
53    errorInfo = @{ GPBErrorReasonKey: reason };
54  }
55  NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain
56                                       code:code
57                                   userInfo:errorInfo];
58
59  NSDictionary *exceptionInfo =
60      @{ GPBCodedInputStreamUnderlyingErrorKey: error };
61  [[[NSException alloc] initWithName:GPBCodedInputStreamException
62                              reason:reason
63                            userInfo:exceptionInfo] raise];
64}
65
66static void CheckSize(GPBCodedInputStreamState *state, size_t size) {
67  size_t newSize = state->bufferPos + size;
68  if (newSize > state->bufferSize) {
69    RaiseException(GPBCodedInputStreamErrorInvalidSize, nil);
70  }
71  if (newSize > state->currentLimit) {
72    // Fast forward to end of currentLimit;
73    state->bufferPos = state->currentLimit;
74    RaiseException(GPBCodedInputStreamErrorSubsectionLimitReached, nil);
75  }
76}
77
78static int8_t ReadRawByte(GPBCodedInputStreamState *state) {
79  CheckSize(state, sizeof(int8_t));
80  return ((int8_t *)state->bytes)[state->bufferPos++];
81}
82
83static int32_t ReadRawLittleEndian32(GPBCodedInputStreamState *state) {
84  CheckSize(state, sizeof(int32_t));
85  int32_t value = OSReadLittleInt32(state->bytes, state->bufferPos);
86  state->bufferPos += sizeof(int32_t);
87  return value;
88}
89
90static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) {
91  CheckSize(state, sizeof(int64_t));
92  int64_t value = OSReadLittleInt64(state->bytes, state->bufferPos);
93  state->bufferPos += sizeof(int64_t);
94  return value;
95}
96
97static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) {
98  int8_t tmp = ReadRawByte(state);
99  if (tmp >= 0) {
100    return tmp;
101  }
102  int32_t result = tmp & 0x7f;
103  if ((tmp = ReadRawByte(state)) >= 0) {
104    result |= tmp << 7;
105  } else {
106    result |= (tmp & 0x7f) << 7;
107    if ((tmp = ReadRawByte(state)) >= 0) {
108      result |= tmp << 14;
109    } else {
110      result |= (tmp & 0x7f) << 14;
111      if ((tmp = ReadRawByte(state)) >= 0) {
112        result |= tmp << 21;
113      } else {
114        result |= (tmp & 0x7f) << 21;
115        result |= (tmp = ReadRawByte(state)) << 28;
116        if (tmp < 0) {
117          // Discard upper 32 bits.
118          for (int i = 0; i < 5; i++) {
119            if (ReadRawByte(state) >= 0) {
120              return result;
121            }
122          }
123          RaiseException(GPBCodedInputStreamErrorInvalidVarInt,
124                         @"Invalid VarInt32");
125        }
126      }
127    }
128  }
129  return result;
130}
131
132static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) {
133  int32_t shift = 0;
134  int64_t result = 0;
135  while (shift < 64) {
136    int8_t b = ReadRawByte(state);
137    result |= (int64_t)(b & 0x7F) << shift;
138    if ((b & 0x80) == 0) {
139      return result;
140    }
141    shift += 7;
142  }
143  RaiseException(GPBCodedInputStreamErrorInvalidVarInt, @"Invalid VarInt64");
144  return 0;
145}
146
147static void SkipRawData(GPBCodedInputStreamState *state, size_t size) {
148  CheckSize(state, size);
149  state->bufferPos += size;
150}
151
152double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state) {
153  int64_t value = ReadRawLittleEndian64(state);
154  return GPBConvertInt64ToDouble(value);
155}
156
157float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state) {
158  int32_t value = ReadRawLittleEndian32(state);
159  return GPBConvertInt32ToFloat(value);
160}
161
162uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state) {
163  uint64_t value = ReadRawVarint64(state);
164  return value;
165}
166
167uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state) {
168  uint32_t value = ReadRawVarint32(state);
169  return value;
170}
171
172int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state) {
173  int64_t value = ReadRawVarint64(state);
174  return value;
175}
176
177int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state) {
178  int32_t value = ReadRawVarint32(state);
179  return value;
180}
181
182uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state) {
183  uint64_t value = ReadRawLittleEndian64(state);
184  return value;
185}
186
187uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state) {
188  uint32_t value = ReadRawLittleEndian32(state);
189  return value;
190}
191
192int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state) {
193  int32_t value = ReadRawVarint32(state);
194  return value;
195}
196
197int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state) {
198  int32_t value = ReadRawLittleEndian32(state);
199  return value;
200}
201
202int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state) {
203  int64_t value = ReadRawLittleEndian64(state);
204  return value;
205}
206
207int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state) {
208  int32_t value = GPBDecodeZigZag32(ReadRawVarint32(state));
209  return value;
210}
211
212int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state) {
213  int64_t value = GPBDecodeZigZag64(ReadRawVarint64(state));
214  return value;
215}
216
217BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state) {
218  return ReadRawVarint32(state) != 0;
219}
220
221int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) {
222  if (GPBCodedInputStreamIsAtEnd(state)) {
223    state->lastTag = 0;
224    return 0;
225  }
226
227  state->lastTag = ReadRawVarint32(state);
228  if (state->lastTag == 0) {
229    // If we actually read zero, that's not a valid tag.
230    RaiseException(GPBCodedInputStreamErrorInvalidTag,
231                   @"A zero tag on the wire is invalid.");
232  }
233  // Tags have to include a valid wireformat, check that also.
234  if (!GPBWireFormatIsValidTag(state->lastTag)) {
235    RaiseException(GPBCodedInputStreamErrorInvalidTag,
236                   @"Invalid wireformat in tag.");
237  }
238  return state->lastTag;
239}
240
241NSString *GPBCodedInputStreamReadRetainedString(
242    GPBCodedInputStreamState *state) {
243  int32_t size = ReadRawVarint32(state);
244  NSString *result;
245  if (size == 0) {
246    result = @"";
247  } else {
248    CheckSize(state, size);
249    result = [[NSString alloc] initWithBytes:&state->bytes[state->bufferPos]
250                                      length:size
251                                    encoding:NSUTF8StringEncoding];
252    state->bufferPos += size;
253    if (!result) {
254#ifdef DEBUG
255      // https://developers.google.com/protocol-buffers/docs/proto#scalar
256      NSLog(@"UTF-8 failure, is some field type 'string' when it should be "
257            @"'bytes'?");
258#endif
259      RaiseException(GPBCodedInputStreamErrorInvalidUTF8, nil);
260    }
261  }
262  return result;
263}
264
265NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) {
266  int32_t size = ReadRawVarint32(state);
267  if (size < 0) return nil;
268  CheckSize(state, size);
269  NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos
270                                          length:size];
271  state->bufferPos += size;
272  return result;
273}
274
275NSData *GPBCodedInputStreamReadRetainedBytesNoCopy(
276    GPBCodedInputStreamState *state) {
277  int32_t size = ReadRawVarint32(state);
278  if (size < 0) return nil;
279  CheckSize(state, size);
280  // Cast is safe because freeWhenDone is NO.
281  NSData *result = [[NSData alloc]
282      initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos)
283                   length:size
284             freeWhenDone:NO];
285  state->bufferPos += size;
286  return result;
287}
288
289size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state,
290                                    size_t byteLimit) {
291  byteLimit += state->bufferPos;
292  size_t oldLimit = state->currentLimit;
293  if (byteLimit > oldLimit) {
294    RaiseException(GPBCodedInputStreamErrorInvalidSubsectionLimit, nil);
295  }
296  state->currentLimit = byteLimit;
297  return oldLimit;
298}
299
300void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state,
301                                 size_t oldLimit) {
302  state->currentLimit = oldLimit;
303}
304
305size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) {
306  return state->currentLimit - state->bufferPos;
307}
308
309BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) {
310  return (state->bufferPos == state->bufferSize) ||
311         (state->bufferPos == state->currentLimit);
312}
313
314void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
315                                        int32_t value) {
316  if (state->lastTag != value) {
317    RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read");
318  }
319}
320
321@implementation GPBCodedInputStream
322
323+ (instancetype)streamWithData:(NSData *)data {
324  return [[[self alloc] initWithData:data] autorelease];
325}
326
327- (instancetype)initWithData:(NSData *)data {
328  if ((self = [super init])) {
329#ifdef DEBUG
330    NSCAssert([self class] == [GPBCodedInputStream class],
331              @"Subclassing of GPBCodedInputStream is not allowed.");
332#endif
333    buffer_ = [data retain];
334    state_.bytes = (const uint8_t *)[data bytes];
335    state_.bufferSize = [data length];
336    state_.currentLimit = state_.bufferSize;
337  }
338  return self;
339}
340
341- (void)dealloc {
342  [buffer_ release];
343  [super dealloc];
344}
345
346// Direct access is use for speed, to avoid even internally declaring things
347// read/write, etc. The warning is enabled in the project to ensure code calling
348// protos can turn on -Wdirect-ivar-access without issues.
349#pragma clang diagnostic push
350#pragma clang diagnostic ignored "-Wdirect-ivar-access"
351
352- (int32_t)readTag {
353  return GPBCodedInputStreamReadTag(&state_);
354}
355
356- (void)checkLastTagWas:(int32_t)value {
357  GPBCodedInputStreamCheckLastTagWas(&state_, value);
358}
359
360- (BOOL)skipField:(int32_t)tag {
361  NSAssert(GPBWireFormatIsValidTag(tag), @"Invalid tag");
362  switch (GPBWireFormatGetTagWireType(tag)) {
363    case GPBWireFormatVarint:
364      GPBCodedInputStreamReadInt32(&state_);
365      return YES;
366    case GPBWireFormatFixed64:
367      SkipRawData(&state_, sizeof(int64_t));
368      return YES;
369    case GPBWireFormatLengthDelimited:
370      SkipRawData(&state_, ReadRawVarint32(&state_));
371      return YES;
372    case GPBWireFormatStartGroup:
373      [self skipMessage];
374      GPBCodedInputStreamCheckLastTagWas(
375          &state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag),
376                                        GPBWireFormatEndGroup));
377      return YES;
378    case GPBWireFormatEndGroup:
379      return NO;
380    case GPBWireFormatFixed32:
381      SkipRawData(&state_, sizeof(int32_t));
382      return YES;
383  }
384}
385
386- (void)skipMessage {
387  while (YES) {
388    int32_t tag = GPBCodedInputStreamReadTag(&state_);
389    if (tag == 0 || ![self skipField:tag]) {
390      return;
391    }
392  }
393}
394
395- (BOOL)isAtEnd {
396  return GPBCodedInputStreamIsAtEnd(&state_);
397}
398
399- (size_t)position {
400  return state_.bufferPos;
401}
402
403- (double)readDouble {
404  return GPBCodedInputStreamReadDouble(&state_);
405}
406
407- (float)readFloat {
408  return GPBCodedInputStreamReadFloat(&state_);
409}
410
411- (uint64_t)readUInt64 {
412  return GPBCodedInputStreamReadUInt64(&state_);
413}
414
415- (int64_t)readInt64 {
416  return GPBCodedInputStreamReadInt64(&state_);
417}
418
419- (int32_t)readInt32 {
420  return GPBCodedInputStreamReadInt32(&state_);
421}
422
423- (uint64_t)readFixed64 {
424  return GPBCodedInputStreamReadFixed64(&state_);
425}
426
427- (uint32_t)readFixed32 {
428  return GPBCodedInputStreamReadFixed32(&state_);
429}
430
431- (BOOL)readBool {
432  return GPBCodedInputStreamReadBool(&state_);
433}
434
435- (NSString *)readString {
436  return [GPBCodedInputStreamReadRetainedString(&state_) autorelease];
437}
438
439- (void)readGroup:(int32_t)fieldNumber
440              message:(GPBMessage *)message
441    extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
442  if (state_.recursionDepth >= kDefaultRecursionLimit) {
443    RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
444  }
445  ++state_.recursionDepth;
446  [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
447  GPBCodedInputStreamCheckLastTagWas(
448      &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
449  --state_.recursionDepth;
450}
451
452- (void)readUnknownGroup:(int32_t)fieldNumber
453                 message:(GPBUnknownFieldSet *)message {
454  if (state_.recursionDepth >= kDefaultRecursionLimit) {
455    RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
456  }
457  ++state_.recursionDepth;
458  [message mergeFromCodedInputStream:self];
459  GPBCodedInputStreamCheckLastTagWas(
460      &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
461  --state_.recursionDepth;
462}
463
464- (void)readMessage:(GPBMessage *)message
465    extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
466  int32_t length = ReadRawVarint32(&state_);
467  if (state_.recursionDepth >= kDefaultRecursionLimit) {
468    RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
469  }
470  size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
471  ++state_.recursionDepth;
472  [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
473  GPBCodedInputStreamCheckLastTagWas(&state_, 0);
474  --state_.recursionDepth;
475  GPBCodedInputStreamPopLimit(&state_, oldLimit);
476}
477
478- (void)readMapEntry:(id)mapDictionary
479    extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
480                field:(GPBFieldDescriptor *)field
481        parentMessage:(GPBMessage *)parentMessage {
482  int32_t length = ReadRawVarint32(&state_);
483  if (state_.recursionDepth >= kDefaultRecursionLimit) {
484    RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
485  }
486  size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
487  ++state_.recursionDepth;
488  GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field,
489                         parentMessage);
490  GPBCodedInputStreamCheckLastTagWas(&state_, 0);
491  --state_.recursionDepth;
492  GPBCodedInputStreamPopLimit(&state_, oldLimit);
493}
494
495- (NSData *)readBytes {
496  return [GPBCodedInputStreamReadRetainedBytes(&state_) autorelease];
497}
498
499- (uint32_t)readUInt32 {
500  return GPBCodedInputStreamReadUInt32(&state_);
501}
502
503- (int32_t)readEnum {
504  return GPBCodedInputStreamReadEnum(&state_);
505}
506
507- (int32_t)readSFixed32 {
508  return GPBCodedInputStreamReadSFixed32(&state_);
509}
510
511- (int64_t)readSFixed64 {
512  return GPBCodedInputStreamReadSFixed64(&state_);
513}
514
515- (int32_t)readSInt32 {
516  return GPBCodedInputStreamReadSInt32(&state_);
517}
518
519- (int64_t)readSInt64 {
520  return GPBCodedInputStreamReadSInt64(&state_);
521}
522
523#pragma clang diagnostic pop
524
525@end
526