GPBCodedInputStream.m 15 KB

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