GPBCodedInputStream.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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. #import "GPBCodedInputStream_PackagePrivate.h"
  31. #import "GPBDictionary_PackagePrivate.h"
  32. #import "GPBMessage_PackagePrivate.h"
  33. #import "GPBUnknownFieldSet_PackagePrivate.h"
  34. #import "GPBUtilities_PackagePrivate.h"
  35. #import "GPBWireFormat.h"
  36. NSString *const GPBCodedInputStreamException =
  37. GPBNSStringifySymbol(GPBCodedInputStreamException);
  38. NSString *const GPBCodedInputStreamUnderlyingErrorKey =
  39. GPBNSStringifySymbol(GPBCodedInputStreamUnderlyingErrorKey);
  40. NSString *const GPBCodedInputStreamErrorDomain =
  41. GPBNSStringifySymbol(GPBCodedInputStreamErrorDomain);
  42. // Matching:
  43. // https://github.com/google/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/CodedInputStream.java#L62
  44. // private static final int DEFAULT_RECURSION_LIMIT = 100;
  45. // https://github.com/google/protobuf/blob/master/src/google/protobuf/io/coded_stream.cc#L86
  46. // int CodedInputStream::default_recursion_limit_ = 100;
  47. static const NSUInteger kDefaultRecursionLimit = 100;
  48. static void RaiseException(NSInteger code, NSString *reason) {
  49. NSDictionary *errorInfo = nil;
  50. if ([reason length]) {
  51. errorInfo = @{ GPBErrorReasonKey: reason };
  52. }
  53. NSError *error = [NSError errorWithDomain:GPBCodedInputStreamErrorDomain
  54. code:code
  55. userInfo:errorInfo];
  56. @try {
  57. NSDictionary *exceptionInfo =
  58. @{ GPBCodedInputStreamUnderlyingErrorKey: error };
  59. [[NSException exceptionWithName:GPBCodedInputStreamException
  60. reason:reason
  61. userInfo:exceptionInfo] raise];
  62. } @catch (NSException *exception) {
  63. } @finally {
  64. }
  65. }
  66. static void CheckRecursionLimit(GPBCodedInputStreamState *state) {
  67. if (state->recursionDepth >= kDefaultRecursionLimit) {
  68. RaiseException(GPBCodedInputStreamErrorRecursionDepthExceeded, nil);
  69. }
  70. }
  71. static void CheckSize(GPBCodedInputStreamState *state, size_t size) {
  72. size_t newSize = state->bufferPos + size;
  73. if (newSize > state->bufferSize) {
  74. RaiseException(GPBCodedInputStreamErrorInvalidSize, nil);
  75. }
  76. if (newSize > state->currentLimit) {
  77. // Fast forward to end of currentLimit;
  78. state->bufferPos = state->currentLimit;
  79. RaiseException(GPBCodedInputStreamErrorSubsectionLimitReached, nil);
  80. }
  81. }
  82. static int8_t ReadRawByte(GPBCodedInputStreamState *state) {
  83. CheckSize(state, sizeof(int8_t));
  84. return ((int8_t *)state->bytes)[state->bufferPos++];
  85. }
  86. static int32_t ReadRawLittleEndian32(GPBCodedInputStreamState *state) {
  87. CheckSize(state, sizeof(int32_t));
  88. int32_t value = OSReadLittleInt32(state->bytes, state->bufferPos);
  89. state->bufferPos += sizeof(int32_t);
  90. return value;
  91. }
  92. static int64_t ReadRawLittleEndian64(GPBCodedInputStreamState *state) {
  93. CheckSize(state, sizeof(int64_t));
  94. int64_t value = OSReadLittleInt64(state->bytes, state->bufferPos);
  95. state->bufferPos += sizeof(int64_t);
  96. return value;
  97. }
  98. static int64_t ReadRawVarint64(GPBCodedInputStreamState *state) {
  99. int32_t shift = 0;
  100. int64_t result = 0;
  101. while (shift < 64) {
  102. int8_t b = ReadRawByte(state);
  103. result |= (int64_t)((uint64_t)(b & 0x7F) << shift);
  104. if ((b & 0x80) == 0) {
  105. return result;
  106. }
  107. shift += 7;
  108. }
  109. RaiseException(GPBCodedInputStreamErrorInvalidVarInt, @"Invalid VarInt64");
  110. return 0;
  111. }
  112. static int32_t ReadRawVarint32(GPBCodedInputStreamState *state) {
  113. return (int32_t)ReadRawVarint64(state);
  114. }
  115. static void SkipRawData(GPBCodedInputStreamState *state, size_t size) {
  116. CheckSize(state, size);
  117. state->bufferPos += size;
  118. }
  119. double GPBCodedInputStreamReadDouble(GPBCodedInputStreamState *state) {
  120. int64_t value = ReadRawLittleEndian64(state);
  121. return GPBConvertInt64ToDouble(value);
  122. }
  123. float GPBCodedInputStreamReadFloat(GPBCodedInputStreamState *state) {
  124. int32_t value = ReadRawLittleEndian32(state);
  125. return GPBConvertInt32ToFloat(value);
  126. }
  127. uint64_t GPBCodedInputStreamReadUInt64(GPBCodedInputStreamState *state) {
  128. uint64_t value = ReadRawVarint64(state);
  129. return value;
  130. }
  131. uint32_t GPBCodedInputStreamReadUInt32(GPBCodedInputStreamState *state) {
  132. uint32_t value = ReadRawVarint32(state);
  133. return value;
  134. }
  135. int64_t GPBCodedInputStreamReadInt64(GPBCodedInputStreamState *state) {
  136. int64_t value = ReadRawVarint64(state);
  137. return value;
  138. }
  139. int32_t GPBCodedInputStreamReadInt32(GPBCodedInputStreamState *state) {
  140. int32_t value = ReadRawVarint32(state);
  141. return value;
  142. }
  143. uint64_t GPBCodedInputStreamReadFixed64(GPBCodedInputStreamState *state) {
  144. uint64_t value = ReadRawLittleEndian64(state);
  145. return value;
  146. }
  147. uint32_t GPBCodedInputStreamReadFixed32(GPBCodedInputStreamState *state) {
  148. uint32_t value = ReadRawLittleEndian32(state);
  149. return value;
  150. }
  151. int32_t GPBCodedInputStreamReadEnum(GPBCodedInputStreamState *state) {
  152. int32_t value = ReadRawVarint32(state);
  153. return value;
  154. }
  155. int32_t GPBCodedInputStreamReadSFixed32(GPBCodedInputStreamState *state) {
  156. int32_t value = ReadRawLittleEndian32(state);
  157. return value;
  158. }
  159. int64_t GPBCodedInputStreamReadSFixed64(GPBCodedInputStreamState *state) {
  160. int64_t value = ReadRawLittleEndian64(state);
  161. return value;
  162. }
  163. int32_t GPBCodedInputStreamReadSInt32(GPBCodedInputStreamState *state) {
  164. int32_t value = GPBDecodeZigZag32(ReadRawVarint32(state));
  165. return value;
  166. }
  167. int64_t GPBCodedInputStreamReadSInt64(GPBCodedInputStreamState *state) {
  168. int64_t value = GPBDecodeZigZag64(ReadRawVarint64(state));
  169. return value;
  170. }
  171. BOOL GPBCodedInputStreamReadBool(GPBCodedInputStreamState *state) {
  172. return ReadRawVarint32(state) != 0;
  173. }
  174. int32_t GPBCodedInputStreamReadTag(GPBCodedInputStreamState *state) {
  175. if (GPBCodedInputStreamIsAtEnd(state)) {
  176. state->lastTag = 0;
  177. return 0;
  178. }
  179. state->lastTag = ReadRawVarint32(state);
  180. // Tags have to include a valid wireformat.
  181. if (!GPBWireFormatIsValidTag(state->lastTag)) {
  182. RaiseException(GPBCodedInputStreamErrorInvalidTag,
  183. @"Invalid wireformat in tag.");
  184. }
  185. // Zero is not a valid field number.
  186. if (GPBWireFormatGetTagFieldNumber(state->lastTag) == 0) {
  187. RaiseException(GPBCodedInputStreamErrorInvalidTag,
  188. @"A zero field number on the wire is invalid.");
  189. }
  190. return state->lastTag;
  191. }
  192. NSString *GPBCodedInputStreamReadRetainedString(
  193. GPBCodedInputStreamState *state) {
  194. int32_t size = ReadRawVarint32(state);
  195. NSString *result;
  196. if (size == 0) {
  197. result = @"";
  198. } else {
  199. CheckSize(state, size);
  200. result = [[NSString alloc] initWithBytes:&state->bytes[state->bufferPos]
  201. length:size
  202. encoding:NSUTF8StringEncoding];
  203. state->bufferPos += size;
  204. if (!result) {
  205. #ifdef DEBUG
  206. // https://developers.google.com/protocol-buffers/docs/proto#scalar
  207. NSLog(@"UTF-8 failure, is some field type 'string' when it should be "
  208. @"'bytes'?");
  209. #endif
  210. RaiseException(GPBCodedInputStreamErrorInvalidUTF8, nil);
  211. }
  212. }
  213. return result;
  214. }
  215. NSData *GPBCodedInputStreamReadRetainedBytes(GPBCodedInputStreamState *state) {
  216. int32_t size = ReadRawVarint32(state);
  217. if (size < 0) return nil;
  218. CheckSize(state, size);
  219. NSData *result = [[NSData alloc] initWithBytes:state->bytes + state->bufferPos
  220. length:size];
  221. state->bufferPos += size;
  222. return result;
  223. }
  224. NSData *GPBCodedInputStreamReadRetainedBytesNoCopy(
  225. GPBCodedInputStreamState *state) {
  226. int32_t size = ReadRawVarint32(state);
  227. if (size < 0) return nil;
  228. CheckSize(state, size);
  229. // Cast is safe because freeWhenDone is NO.
  230. NSData *result = [[NSData alloc]
  231. initWithBytesNoCopy:(void *)(state->bytes + state->bufferPos)
  232. length:size
  233. freeWhenDone:NO];
  234. state->bufferPos += size;
  235. return result;
  236. }
  237. size_t GPBCodedInputStreamPushLimit(GPBCodedInputStreamState *state,
  238. size_t byteLimit) {
  239. byteLimit += state->bufferPos;
  240. size_t oldLimit = state->currentLimit;
  241. if (byteLimit > oldLimit) {
  242. RaiseException(GPBCodedInputStreamErrorInvalidSubsectionLimit, nil);
  243. }
  244. state->currentLimit = byteLimit;
  245. return oldLimit;
  246. }
  247. void GPBCodedInputStreamPopLimit(GPBCodedInputStreamState *state,
  248. size_t oldLimit) {
  249. state->currentLimit = oldLimit;
  250. }
  251. size_t GPBCodedInputStreamBytesUntilLimit(GPBCodedInputStreamState *state) {
  252. return state->currentLimit - state->bufferPos;
  253. }
  254. BOOL GPBCodedInputStreamIsAtEnd(GPBCodedInputStreamState *state) {
  255. return (state->bufferPos == state->bufferSize) ||
  256. (state->bufferPos == state->currentLimit);
  257. }
  258. void GPBCodedInputStreamCheckLastTagWas(GPBCodedInputStreamState *state,
  259. int32_t value) {
  260. if (state->lastTag != value) {
  261. RaiseException(GPBCodedInputStreamErrorInvalidTag, @"Unexpected tag read");
  262. }
  263. }
  264. @implementation GPBCodedInputStream
  265. + (instancetype)streamWithData:(NSData *)data {
  266. return [[[self alloc] initWithData:data] autorelease];
  267. }
  268. - (instancetype)initWithData:(NSData *)data {
  269. if ((self = [super init])) {
  270. #ifdef DEBUG
  271. NSCAssert([self class] == [GPBCodedInputStream class],
  272. @"Subclassing of GPBCodedInputStream is not allowed.");
  273. #endif
  274. buffer_ = [data retain];
  275. state_.bytes = (const uint8_t *)[data bytes];
  276. state_.bufferSize = [data length];
  277. state_.currentLimit = state_.bufferSize;
  278. }
  279. return self;
  280. }
  281. - (void)dealloc {
  282. [buffer_ release];
  283. [super dealloc];
  284. }
  285. // Direct access is use for speed, to avoid even internally declaring things
  286. // read/write, etc. The warning is enabled in the project to ensure code calling
  287. // protos can turn on -Wdirect-ivar-access without issues.
  288. #pragma clang diagnostic push
  289. #pragma clang diagnostic ignored "-Wdirect-ivar-access"
  290. - (int32_t)readTag {
  291. return GPBCodedInputStreamReadTag(&state_);
  292. }
  293. - (void)checkLastTagWas:(int32_t)value {
  294. GPBCodedInputStreamCheckLastTagWas(&state_, value);
  295. }
  296. - (BOOL)skipField:(int32_t)tag {
  297. NSAssert(GPBWireFormatIsValidTag(tag), @"Invalid tag");
  298. switch (GPBWireFormatGetTagWireType(tag)) {
  299. case GPBWireFormatVarint:
  300. GPBCodedInputStreamReadInt32(&state_);
  301. return YES;
  302. case GPBWireFormatFixed64:
  303. SkipRawData(&state_, sizeof(int64_t));
  304. return YES;
  305. case GPBWireFormatLengthDelimited:
  306. SkipRawData(&state_, ReadRawVarint32(&state_));
  307. return YES;
  308. case GPBWireFormatStartGroup:
  309. [self skipMessage];
  310. GPBCodedInputStreamCheckLastTagWas(
  311. &state_, GPBWireFormatMakeTag(GPBWireFormatGetTagFieldNumber(tag),
  312. GPBWireFormatEndGroup));
  313. return YES;
  314. case GPBWireFormatEndGroup:
  315. return NO;
  316. case GPBWireFormatFixed32:
  317. SkipRawData(&state_, sizeof(int32_t));
  318. return YES;
  319. }
  320. }
  321. - (void)skipMessage {
  322. while (YES) {
  323. int32_t tag = GPBCodedInputStreamReadTag(&state_);
  324. if (tag == 0 || ![self skipField:tag]) {
  325. return;
  326. }
  327. }
  328. }
  329. - (BOOL)isAtEnd {
  330. return GPBCodedInputStreamIsAtEnd(&state_);
  331. }
  332. - (size_t)position {
  333. return state_.bufferPos;
  334. }
  335. - (size_t)pushLimit:(size_t)byteLimit {
  336. return GPBCodedInputStreamPushLimit(&state_, byteLimit);
  337. }
  338. - (void)popLimit:(size_t)oldLimit {
  339. GPBCodedInputStreamPopLimit(&state_, oldLimit);
  340. }
  341. - (double)readDouble {
  342. return GPBCodedInputStreamReadDouble(&state_);
  343. }
  344. - (float)readFloat {
  345. return GPBCodedInputStreamReadFloat(&state_);
  346. }
  347. - (uint64_t)readUInt64 {
  348. return GPBCodedInputStreamReadUInt64(&state_);
  349. }
  350. - (int64_t)readInt64 {
  351. return GPBCodedInputStreamReadInt64(&state_);
  352. }
  353. - (int32_t)readInt32 {
  354. return GPBCodedInputStreamReadInt32(&state_);
  355. }
  356. - (uint64_t)readFixed64 {
  357. return GPBCodedInputStreamReadFixed64(&state_);
  358. }
  359. - (uint32_t)readFixed32 {
  360. return GPBCodedInputStreamReadFixed32(&state_);
  361. }
  362. - (BOOL)readBool {
  363. return GPBCodedInputStreamReadBool(&state_);
  364. }
  365. - (NSString *)readString {
  366. return [GPBCodedInputStreamReadRetainedString(&state_) autorelease];
  367. }
  368. - (void)readGroup:(int32_t)fieldNumber
  369. message:(GPBMessage *)message
  370. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  371. CheckRecursionLimit(&state_);
  372. ++state_.recursionDepth;
  373. [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
  374. GPBCodedInputStreamCheckLastTagWas(
  375. &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
  376. --state_.recursionDepth;
  377. }
  378. - (void)readUnknownGroup:(int32_t)fieldNumber
  379. message:(GPBUnknownFieldSet *)message {
  380. CheckRecursionLimit(&state_);
  381. ++state_.recursionDepth;
  382. [message mergeFromCodedInputStream:self];
  383. GPBCodedInputStreamCheckLastTagWas(
  384. &state_, GPBWireFormatMakeTag(fieldNumber, GPBWireFormatEndGroup));
  385. --state_.recursionDepth;
  386. }
  387. - (void)readMessage:(GPBMessage *)message
  388. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry {
  389. CheckRecursionLimit(&state_);
  390. int32_t length = ReadRawVarint32(&state_);
  391. size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
  392. ++state_.recursionDepth;
  393. [message mergeFromCodedInputStream:self extensionRegistry:extensionRegistry];
  394. GPBCodedInputStreamCheckLastTagWas(&state_, 0);
  395. --state_.recursionDepth;
  396. GPBCodedInputStreamPopLimit(&state_, oldLimit);
  397. }
  398. - (void)readMapEntry:(id)mapDictionary
  399. extensionRegistry:(GPBExtensionRegistry *)extensionRegistry
  400. field:(GPBFieldDescriptor *)field
  401. parentMessage:(GPBMessage *)parentMessage {
  402. CheckRecursionLimit(&state_);
  403. int32_t length = ReadRawVarint32(&state_);
  404. size_t oldLimit = GPBCodedInputStreamPushLimit(&state_, length);
  405. ++state_.recursionDepth;
  406. GPBDictionaryReadEntry(mapDictionary, self, extensionRegistry, field,
  407. parentMessage);
  408. GPBCodedInputStreamCheckLastTagWas(&state_, 0);
  409. --state_.recursionDepth;
  410. GPBCodedInputStreamPopLimit(&state_, oldLimit);
  411. }
  412. - (NSData *)readBytes {
  413. return [GPBCodedInputStreamReadRetainedBytes(&state_) autorelease];
  414. }
  415. - (uint32_t)readUInt32 {
  416. return GPBCodedInputStreamReadUInt32(&state_);
  417. }
  418. - (int32_t)readEnum {
  419. return GPBCodedInputStreamReadEnum(&state_);
  420. }
  421. - (int32_t)readSFixed32 {
  422. return GPBCodedInputStreamReadSFixed32(&state_);
  423. }
  424. - (int64_t)readSFixed64 {
  425. return GPBCodedInputStreamReadSFixed64(&state_);
  426. }
  427. - (int32_t)readSInt32 {
  428. return GPBCodedInputStreamReadSInt32(&state_);
  429. }
  430. - (int64_t)readSInt64 {
  431. return GPBCodedInputStreamReadSInt64(&state_);
  432. }
  433. #pragma clang diagnostic pop
  434. @end