GPBCodedInputStream.m 16 KB

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