You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

505 lines
16 KiB

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