GPBCodedInputStream.m 17 KB

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