• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
31 #include <google/protobuf/arena.h>
32 
33 #include <algorithm>
34 #include <cstring>
35 #include <memory>
36 #ifndef _SHARED_PTR_H
37 #include <google/protobuf/stubs/shared_ptr.h>
38 #endif
39 #include <string>
40 #include <typeinfo>
41 #include <vector>
42 
43 #include <google/protobuf/stubs/logging.h>
44 #include <google/protobuf/stubs/common.h>
45 #include <google/protobuf/stubs/scoped_ptr.h>
46 #include <google/protobuf/arena_test_util.h>
47 #include <google/protobuf/test_util.h>
48 #include <google/protobuf/unittest.pb.h>
49 #include <google/protobuf/unittest_arena.pb.h>
50 #include <google/protobuf/unittest_no_arena.pb.h>
51 #include <google/protobuf/io/coded_stream.h>
52 #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
53 #include <google/protobuf/descriptor.h>
54 #include <google/protobuf/extension_set.h>
55 #include <google/protobuf/message.h>
56 #include <google/protobuf/message_lite.h>
57 #include <google/protobuf/repeated_field.h>
58 #include <google/protobuf/wire_format_lite.h>
59 #include <google/protobuf/unknown_field_set.h>
60 #include <gtest/gtest.h>
61 
62 
63 namespace google {
64 using proto2_arena_unittest::ArenaMessage;
65 using protobuf_unittest::TestAllTypes;
66 using protobuf_unittest::TestAllExtensions;
67 using protobuf_unittest::TestOneof2;
68 using protobuf_unittest::TestEmptyMessage;
69 
70 namespace protobuf {
71 namespace {
72 
73 class Notifier {
74  public:
Notifier()75   Notifier() : count_(0) {}
Notify()76   void Notify() {
77     count_++;
78   }
GetCount()79   int GetCount() {
80     return count_;
81   }
82 
83  private:
84   int count_;
85 };
86 
87 class SimpleDataType {
88  public:
SimpleDataType()89   SimpleDataType() : notifier_(NULL) {}
SetNotifier(Notifier * notifier)90   void SetNotifier(Notifier* notifier) {
91     notifier_ = notifier;
92   }
~SimpleDataType()93   virtual ~SimpleDataType() {
94     if (notifier_ != NULL) {
95       notifier_->Notify();
96     }
97   };
98  private:
99   Notifier* notifier_;
100 };
101 
102 // A simple class that does not allow copying and so cannot be used as a
103 // parameter type without "const &".
104 class PleaseDontCopyMe {
105  public:
PleaseDontCopyMe(int value)106   explicit PleaseDontCopyMe(int value) : value_(value) {}
107 
value() const108   int value() const { return value_; }
109 
110  private:
111   int value_;
112   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PleaseDontCopyMe);
113 };
114 
115 // A class that takes four different types as constructor arguments.
116 class MustBeConstructedWithOneThroughFour {
117  public:
MustBeConstructedWithOneThroughFour(int one,const char * two,const string & three,const PleaseDontCopyMe * four)118   MustBeConstructedWithOneThroughFour(
119       int one, const char* two, const string& three,
120       const PleaseDontCopyMe* four)
121       : one_(one), two_(two), three_(three), four_(four) {}
122 
123   int one_;
124   const char* const two_;
125   string three_;
126   const PleaseDontCopyMe* four_;
127 
128  private:
129   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughFour);
130 };
131 
132 // A class that takes eight different types as constructor arguments.
133 class MustBeConstructedWithOneThroughEight {
134  public:
MustBeConstructedWithOneThroughEight(int one,const char * two,const string & three,const PleaseDontCopyMe * four,int five,const char * six,const string & seven,const string & eight)135   MustBeConstructedWithOneThroughEight(
136       int one, const char* two, const string& three,
137       const PleaseDontCopyMe* four, int five, const char* six,
138       const string& seven, const string& eight)
139       : one_(one), two_(two), three_(three), four_(four), five_(five),
140         six_(six), seven_(seven), eight_(eight) {}
141 
142   int one_;
143   const char* const two_;
144   string three_;
145   const PleaseDontCopyMe* four_;
146   int five_;
147   const char* const six_;
148   string seven_;
149   string eight_;
150 
151  private:
152   GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MustBeConstructedWithOneThroughEight);
153 };
154 
155 }  // namespace
156 
TEST(ArenaTest,ArenaConstructable)157 TEST(ArenaTest, ArenaConstructable) {
158   EXPECT_TRUE(Arena::is_arena_constructable<TestAllTypes>::type::value);
159   EXPECT_TRUE(Arena::is_arena_constructable<const TestAllTypes>::type::value);
160   EXPECT_FALSE(Arena::is_arena_constructable<Arena>::type::value);
161 }
162 
TEST(ArenaTest,BasicCreate)163 TEST(ArenaTest, BasicCreate) {
164   Arena arena;
165   EXPECT_TRUE(Arena::Create<int32>(&arena) != NULL);
166   EXPECT_TRUE(Arena::Create<int64>(&arena) != NULL);
167   EXPECT_TRUE(Arena::Create<float>(&arena) != NULL);
168   EXPECT_TRUE(Arena::Create<double>(&arena) != NULL);
169   EXPECT_TRUE(Arena::Create<string>(&arena) != NULL);
170   arena.Own(new int32);
171   arena.Own(new int64);
172   arena.Own(new float);
173   arena.Own(new double);
174   arena.Own(new string);
175   arena.Own<int>(NULL);
176   Notifier notifier;
177   SimpleDataType* data = Arena::Create<SimpleDataType>(&arena);
178   data->SetNotifier(&notifier);
179   data = new SimpleDataType;
180   data->SetNotifier(&notifier);
181   arena.Own(data);
182   arena.Reset();
183   EXPECT_EQ(2, notifier.GetCount());
184 }
185 
TEST(ArenaTest,CreateWithFourConstructorArguments)186 TEST(ArenaTest, CreateWithFourConstructorArguments) {
187   Arena arena;
188   const string three("3");
189   const PleaseDontCopyMe four(4);
190   const MustBeConstructedWithOneThroughFour* new_object =
191       Arena::Create<MustBeConstructedWithOneThroughFour>(
192           &arena, 1, "2", three, &four);
193   EXPECT_TRUE(new_object != NULL);
194   ASSERT_EQ(1, new_object->one_);
195   ASSERT_STREQ("2", new_object->two_);
196   ASSERT_EQ("3", new_object->three_);
197   ASSERT_EQ(4, new_object->four_->value());
198 }
199 
TEST(ArenaTest,CreateWithEightConstructorArguments)200 TEST(ArenaTest, CreateWithEightConstructorArguments) {
201   Arena arena;
202   const string three("3");
203   const PleaseDontCopyMe four(4);
204   const string seven("7");
205   const string eight("8");
206   const MustBeConstructedWithOneThroughEight* new_object =
207       Arena::Create<MustBeConstructedWithOneThroughEight>(
208           &arena, 1, "2", three, &four, 5, "6", seven, eight);
209   EXPECT_TRUE(new_object != NULL);
210   ASSERT_EQ(1, new_object->one_);
211   ASSERT_STREQ("2", new_object->two_);
212   ASSERT_EQ("3", new_object->three_);
213   ASSERT_EQ(4, new_object->four_->value());
214   ASSERT_EQ(5, new_object->five_);
215   ASSERT_STREQ("6", new_object->six_);
216   ASSERT_EQ("7", new_object->seven_);
217   ASSERT_EQ("8", new_object->eight_);
218 }
219 
TEST(ArenaTest,InitialBlockTooSmall)220 TEST(ArenaTest, InitialBlockTooSmall) {
221   // Construct a small (64 byte) initial block of memory to be used by the
222   // arena allocator; then, allocate an object which will not fit in the
223   // initial block.
224   std::vector<char> arena_block(64);
225   ArenaOptions options;
226   options.initial_block = &arena_block[0];
227   options.initial_block_size = arena_block.size();
228   Arena arena(options);
229 
230   char* p = ::google::protobuf::Arena::CreateArray<char>(&arena, 96);
231   uintptr_t allocation = reinterpret_cast<uintptr_t>(p);
232 
233   // Ensure that the arena allocator did not return memory pointing into the
234   // initial block of memory.
235   uintptr_t arena_start = reinterpret_cast<uintptr_t>(&arena_block[0]);
236   uintptr_t arena_end = arena_start + arena_block.size();
237   EXPECT_FALSE(allocation >= arena_start && allocation < arena_end);
238 
239   // Write to the memory we allocated; this should (but is not guaranteed to)
240   // trigger a check for heap corruption if the object was allocated from the
241   // initially-provided block.
242   memset(p, '\0', 96);
243 }
244 
TEST(ArenaTest,Parsing)245 TEST(ArenaTest, Parsing) {
246   TestAllTypes original;
247   TestUtil::SetAllFields(&original);
248 
249   // Test memory leak.
250   Arena arena;
251   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
252   arena_message->ParseFromString(original.SerializeAsString());
253   TestUtil::ExpectAllFieldsSet(*arena_message);
254 
255   // Test that string fields have null terminator bytes (earlier bug).
256   EXPECT_EQ(strlen(original.optional_string().c_str()),
257             strlen(arena_message->optional_string().c_str()));
258 }
259 
TEST(ArenaTest,UnknownFields)260 TEST(ArenaTest, UnknownFields) {
261   TestAllTypes original;
262   TestUtil::SetAllFields(&original);
263 
264   // Test basic parsing into (populating) and reading out of unknown fields on
265   // an arena.
266   Arena arena;
267   TestEmptyMessage* arena_message =
268       Arena::CreateMessage<TestEmptyMessage>(&arena);
269   arena_message->ParseFromString(original.SerializeAsString());
270 
271   TestAllTypes copied;
272   copied.ParseFromString(arena_message->SerializeAsString());
273   TestUtil::ExpectAllFieldsSet(copied);
274 
275   // Exercise UFS manual manipulation (setters).
276   arena_message = Arena::CreateMessage<TestEmptyMessage>(&arena);
277   arena_message->mutable_unknown_fields()->AddVarint(
278       TestAllTypes::kOptionalInt32FieldNumber, 42);
279   copied.Clear();
280   copied.ParseFromString(arena_message->SerializeAsString());
281   EXPECT_TRUE(copied.has_optional_int32());
282   EXPECT_EQ(42, copied.optional_int32());
283 
284   // Exercise UFS swap path.
285   TestEmptyMessage* arena_message_2 =
286       Arena::CreateMessage<TestEmptyMessage>(&arena);
287   arena_message_2->Swap(arena_message);
288   copied.Clear();
289   copied.ParseFromString(arena_message_2->SerializeAsString());
290   EXPECT_TRUE(copied.has_optional_int32());
291   EXPECT_EQ(42, copied.optional_int32());
292 
293   // Test field manipulation.
294   TestEmptyMessage* arena_message_3 =
295       Arena::CreateMessage<TestEmptyMessage>(&arena);
296   arena_message_3->mutable_unknown_fields()->AddVarint(1000, 42);
297   arena_message_3->mutable_unknown_fields()->AddFixed32(1001, 42);
298   arena_message_3->mutable_unknown_fields()->AddFixed64(1002, 42);
299   arena_message_3->mutable_unknown_fields()->AddLengthDelimited(1003);
300   arena_message_3->mutable_unknown_fields()->DeleteSubrange(0, 2);
301   arena_message_3->mutable_unknown_fields()->DeleteByNumber(1002);
302   arena_message_3->mutable_unknown_fields()->DeleteByNumber(1003);
303   EXPECT_TRUE(arena_message_3->unknown_fields().empty());
304 }
305 
TEST(ArenaTest,Swap)306 TEST(ArenaTest, Swap) {
307   Arena arena1;
308   Arena arena2;
309   TestAllTypes* arena1_message;
310   TestAllTypes* arena2_message;
311 
312   // Case 1: Swap(), no UFS on either message, both messages on different
313   // arenas. Arena pointers should remain the same after swap.
314   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
315   arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
316   arena1_message->Swap(arena2_message);
317   EXPECT_EQ(&arena1, arena1_message->GetArena());
318   EXPECT_EQ(&arena2, arena2_message->GetArena());
319 
320   // Case 2: Swap(), UFS on one message, both messages on different arenas.
321   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
322   arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
323   arena1_message->mutable_unknown_fields()->AddVarint(1, 42);
324   arena1_message->Swap(arena2_message);
325   EXPECT_EQ(&arena1, arena1_message->GetArena());
326   EXPECT_EQ(&arena2, arena2_message->GetArena());
327   EXPECT_EQ(0, arena1_message->unknown_fields().field_count());
328   EXPECT_EQ(1, arena2_message->unknown_fields().field_count());
329   EXPECT_EQ(42, arena2_message->unknown_fields().field(0).varint());
330 
331   // Case 3: Swap(), UFS on both messages, both messages on different arenas.
332   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
333   arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
334   arena1_message->mutable_unknown_fields()->AddVarint(1, 42);
335   arena2_message->mutable_unknown_fields()->AddVarint(2, 84);
336   arena1_message->Swap(arena2_message);
337   EXPECT_EQ(&arena1, arena1_message->GetArena());
338   EXPECT_EQ(&arena2, arena2_message->GetArena());
339   EXPECT_EQ(1, arena1_message->unknown_fields().field_count());
340   EXPECT_EQ(1, arena2_message->unknown_fields().field_count());
341   EXPECT_EQ(84, arena1_message->unknown_fields().field(0).varint());
342   EXPECT_EQ(42, arena2_message->unknown_fields().field(0).varint());
343 }
344 
TEST(ArenaTest,ReflectionSwapFields)345 TEST(ArenaTest, ReflectionSwapFields) {
346   Arena arena1;
347   Arena arena2;
348   TestAllTypes* arena1_message;
349   TestAllTypes* arena2_message;
350 
351   // Case 1: messages on different arenas, only one message is set.
352   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
353   arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
354   TestUtil::SetAllFields(arena1_message);
355   const Reflection* reflection = arena1_message->GetReflection();
356   std::vector<const FieldDescriptor*> fields;
357   reflection->ListFields(*arena1_message, &fields);
358   reflection->SwapFields(arena1_message, arena2_message, fields);
359   EXPECT_EQ(&arena1, arena1_message->GetArena());
360   EXPECT_EQ(&arena2, arena2_message->GetArena());
361   string output;
362   arena1_message->SerializeToString(&output);
363   EXPECT_EQ(0, output.size());
364   TestUtil::ExpectAllFieldsSet(*arena2_message);
365   reflection->SwapFields(arena1_message, arena2_message, fields);
366   arena2_message->SerializeToString(&output);
367   EXPECT_EQ(0, output.size());
368   TestUtil::ExpectAllFieldsSet(*arena1_message);
369 
370   // Case 2: messages on different arenas, both messages are set.
371   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
372   arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
373   TestUtil::SetAllFields(arena1_message);
374   TestUtil::SetAllFields(arena2_message);
375   reflection->SwapFields(arena1_message, arena2_message, fields);
376   EXPECT_EQ(&arena1, arena1_message->GetArena());
377   EXPECT_EQ(&arena2, arena2_message->GetArena());
378   TestUtil::ExpectAllFieldsSet(*arena1_message);
379   TestUtil::ExpectAllFieldsSet(*arena2_message);
380 
381   // Case 3: messages on different arenas with different lifetimes.
382   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
383   {
384     Arena arena3;
385     TestAllTypes* arena3_message = Arena::CreateMessage<TestAllTypes>(&arena3);
386     TestUtil::SetAllFields(arena3_message);
387     reflection->SwapFields(arena1_message, arena3_message, fields);
388   }
389   TestUtil::ExpectAllFieldsSet(*arena1_message);
390 
391   // Case 4: one message on arena, the other on heap.
392   arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
393   TestAllTypes message;
394   TestUtil::SetAllFields(arena1_message);
395   reflection->SwapFields(arena1_message, &message, fields);
396   EXPECT_EQ(&arena1, arena1_message->GetArena());
397   EXPECT_EQ(NULL, message.GetArena());
398   arena1_message->SerializeToString(&output);
399   EXPECT_EQ(0, output.size());
400   TestUtil::ExpectAllFieldsSet(message);
401 }
402 
TEST(ArenaTest,SetAllocatedMessage)403 TEST(ArenaTest, SetAllocatedMessage) {
404   Arena arena;
405   TestAllTypes *arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
406   TestAllTypes::NestedMessage* nested = new TestAllTypes::NestedMessage;
407   nested->set_bb(118);
408   arena_message->set_allocated_optional_nested_message(nested);
409   EXPECT_EQ(118, arena_message->optional_nested_message().bb());
410 
411   protobuf_unittest_no_arena::TestNoArenaMessage no_arena_message;
412   EXPECT_FALSE(no_arena_message.has_arena_message());
413   no_arena_message.set_allocated_arena_message(NULL);
414   EXPECT_FALSE(no_arena_message.has_arena_message());
415   no_arena_message.set_allocated_arena_message(new ArenaMessage);
416   EXPECT_TRUE(no_arena_message.has_arena_message());
417 }
418 
TEST(ArenaTest,ReleaseMessage)419 TEST(ArenaTest, ReleaseMessage) {
420   Arena arena;
421   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
422   arena_message->mutable_optional_nested_message()->set_bb(118);
423   google::protobuf::scoped_ptr<TestAllTypes::NestedMessage> nested(
424       arena_message->release_optional_nested_message());
425   EXPECT_EQ(118, nested->bb());
426 
427   TestAllTypes::NestedMessage* released_null =
428       arena_message->release_optional_nested_message();
429   EXPECT_EQ(NULL, released_null);
430 }
431 
TEST(ArenaTest,SetAllocatedString)432 TEST(ArenaTest, SetAllocatedString) {
433   Arena arena;
434   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
435   string* allocated_str = new string("hello");
436   arena_message->set_allocated_optional_string(allocated_str);
437   EXPECT_EQ("hello", arena_message->optional_string());
438 }
439 
TEST(ArenaTest,ReleaseString)440 TEST(ArenaTest, ReleaseString) {
441   Arena arena;
442   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
443   arena_message->set_optional_string("hello");
444   google::protobuf::scoped_ptr<string> released_str(
445       arena_message->release_optional_string());
446   EXPECT_EQ("hello", *released_str);
447 
448   // Test default value.
449 }
450 
451 
TEST(ArenaTest,SwapBetweenArenasWithAllFieldsSet)452 TEST(ArenaTest, SwapBetweenArenasWithAllFieldsSet) {
453   Arena arena1;
454   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
455   {
456     Arena arena2;
457     TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
458     TestUtil::SetAllFields(arena2_message);
459     arena2_message->Swap(arena1_message);
460     string output;
461     arena2_message->SerializeToString(&output);
462     EXPECT_EQ(0, output.size());
463   }
464   TestUtil::ExpectAllFieldsSet(*arena1_message);
465 }
466 
TEST(ArenaTest,SwapBetweenArenaAndNonArenaWithAllFieldsSet)467 TEST(ArenaTest, SwapBetweenArenaAndNonArenaWithAllFieldsSet) {
468   TestAllTypes non_arena_message;
469   TestUtil::SetAllFields(&non_arena_message);
470   {
471     Arena arena2;
472     TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
473     TestUtil::SetAllFields(arena2_message);
474     arena2_message->Swap(&non_arena_message);
475     TestUtil::ExpectAllFieldsSet(*arena2_message);
476     TestUtil::ExpectAllFieldsSet(non_arena_message);
477   }
478 }
479 
TEST(ArenaTest,UnsafeArenaSwap)480 TEST(ArenaTest, UnsafeArenaSwap) {
481   Arena shared_arena;
482   TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&shared_arena);
483   TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&shared_arena);
484   TestUtil::SetAllFields(message1);
485   message1->UnsafeArenaSwap(message2);
486   TestUtil::ExpectAllFieldsSet(*message2);
487 }
488 
TEST(ArenaTest,SwapBetweenArenasUsingReflection)489 TEST(ArenaTest, SwapBetweenArenasUsingReflection) {
490   Arena arena1;
491   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
492   {
493     Arena arena2;
494     TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
495     TestUtil::SetAllFields(arena2_message);
496     const Reflection* r = arena2_message->GetReflection();
497     r->Swap(arena1_message, arena2_message);
498     string output;
499     arena2_message->SerializeToString(&output);
500     EXPECT_EQ(0, output.size());
501   }
502   TestUtil::ExpectAllFieldsSet(*arena1_message);
503 }
504 
TEST(ArenaTest,SwapBetweenArenaAndNonArenaUsingReflection)505 TEST(ArenaTest, SwapBetweenArenaAndNonArenaUsingReflection) {
506   TestAllTypes non_arena_message;
507   TestUtil::SetAllFields(&non_arena_message);
508   {
509     Arena arena2;
510     TestAllTypes* arena2_message = Arena::CreateMessage<TestAllTypes>(&arena2);
511     TestUtil::SetAllFields(arena2_message);
512     const Reflection* r = arena2_message->GetReflection();
513     r->Swap(&non_arena_message, arena2_message);
514     TestUtil::ExpectAllFieldsSet(*arena2_message);
515     TestUtil::ExpectAllFieldsSet(non_arena_message);
516   }
517 }
518 
TEST(ArenaTest,ReleaseFromArenaMessageMakesCopy)519 TEST(ArenaTest, ReleaseFromArenaMessageMakesCopy) {
520   TestAllTypes::NestedMessage* nested_msg = NULL;
521   string* nested_string = NULL;
522   {
523     Arena arena;
524     TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
525     arena_message->mutable_optional_nested_message()->set_bb(42);
526     *arena_message->mutable_optional_string() = "Hello";
527     nested_msg = arena_message->release_optional_nested_message();
528     nested_string = arena_message->release_optional_string();
529   }
530   EXPECT_EQ(42, nested_msg->bb());
531   EXPECT_EQ("Hello", *nested_string);
532   delete nested_msg;
533   delete nested_string;
534 }
535 
536 #ifndef GOOGLE_PROTOBUF_NO_RTTI
TEST(ArenaTest,ReleaseFromArenaMessageUsingReflectionMakesCopy)537 TEST(ArenaTest, ReleaseFromArenaMessageUsingReflectionMakesCopy) {
538   TestAllTypes::NestedMessage* nested_msg = NULL;
539   // Note: no string: reflection API only supports releasing submessages.
540   {
541     Arena arena;
542     TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
543     arena_message->mutable_optional_nested_message()->set_bb(42);
544     const Reflection* r = arena_message->GetReflection();
545     const FieldDescriptor* f = arena_message->GetDescriptor()->FindFieldByName(
546         "optional_nested_message");
547     nested_msg = static_cast<TestAllTypes::NestedMessage*>(
548         r->ReleaseMessage(arena_message, f));
549   }
550   EXPECT_EQ(42, nested_msg->bb());
551   delete nested_msg;
552 }
553 #endif  // !GOOGLE_PROTOBUF_NO_RTTI
554 
TEST(ArenaTest,UnsafeArenaReleaseDoesNotMakeCopy)555 TEST(ArenaTest, UnsafeArenaReleaseDoesNotMakeCopy) {
556   Arena arena;
557   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
558   TestAllTypes::NestedMessage* nested_msg = NULL;
559   TestAllTypes::NestedMessage* orig_nested_msg = NULL;
560   string* nested_string = NULL;
561   string* orig_nested_string = NULL;
562   arena_message->mutable_optional_nested_message()->set_bb(42);
563   *arena_message->mutable_optional_string() = "Hello";
564   orig_nested_msg = arena_message->mutable_optional_nested_message();
565   orig_nested_string = arena_message->mutable_optional_string();
566   nested_msg = arena_message->unsafe_arena_release_optional_nested_message();
567   nested_string = arena_message->unsafe_arena_release_optional_string();
568 
569   EXPECT_EQ(orig_nested_msg, nested_msg);
570   EXPECT_EQ(orig_nested_string, nested_string);
571   // Released pointers still on arena; no 'delete' calls needed here.
572 }
573 
TEST(ArenaTest,SetAllocatedAcrossArenas)574 TEST(ArenaTest, SetAllocatedAcrossArenas) {
575   Arena arena1;
576   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
577   TestAllTypes::NestedMessage* heap_submessage =
578       new TestAllTypes::NestedMessage();
579   heap_submessage->set_bb(42);
580   arena1_message->set_allocated_optional_nested_message(heap_submessage);
581   // Should keep same object and add to arena's Own()-list.
582   EXPECT_EQ(heap_submessage,
583             arena1_message->mutable_optional_nested_message());
584   {
585     Arena arena2;
586     TestAllTypes::NestedMessage* arena2_submessage =
587         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
588     arena2_submessage->set_bb(42);
589     arena1_message->set_allocated_optional_nested_message(arena2_submessage);
590     EXPECT_NE(arena2_submessage,
591               arena1_message->mutable_optional_nested_message());
592   }
593 
594   TestAllTypes::NestedMessage* arena1_submessage =
595       Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena1);
596   arena1_submessage->set_bb(42);
597   TestAllTypes* heap_message = new TestAllTypes;
598   heap_message->set_allocated_optional_nested_message(arena1_submessage);
599   EXPECT_NE(arena1_submessage,
600             heap_message->mutable_optional_nested_message());
601   delete heap_message;
602 }
603 
TEST(ArenaTest,SetAllocatedAcrossArenasWithReflection)604 TEST(ArenaTest, SetAllocatedAcrossArenasWithReflection) {
605   // Same as above, with reflection.
606   Arena arena1;
607   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
608   const Reflection* r = arena1_message->GetReflection();
609   const Descriptor* d = arena1_message->GetDescriptor();
610   const FieldDescriptor* msg_field = d->FindFieldByName(
611       "optional_nested_message");
612   TestAllTypes::NestedMessage* heap_submessage =
613       new TestAllTypes::NestedMessage();
614   heap_submessage->set_bb(42);
615   r->SetAllocatedMessage(arena1_message, heap_submessage, msg_field);
616   // Should keep same object and add to arena's Own()-list.
617   EXPECT_EQ(heap_submessage,
618             arena1_message->mutable_optional_nested_message());
619   {
620     Arena arena2;
621     TestAllTypes::NestedMessage* arena2_submessage =
622         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
623     arena2_submessage->set_bb(42);
624     r->SetAllocatedMessage(arena1_message, arena2_submessage, msg_field);
625     EXPECT_NE(arena2_submessage,
626               arena1_message->mutable_optional_nested_message());
627   }
628 
629   TestAllTypes::NestedMessage* arena1_submessage =
630       Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena1);
631   arena1_submessage->set_bb(42);
632   TestAllTypes* heap_message = new TestAllTypes;
633   r->SetAllocatedMessage(heap_message, arena1_submessage, msg_field);
634   EXPECT_NE(arena1_submessage,
635             heap_message->mutable_optional_nested_message());
636   delete heap_message;
637 }
638 
TEST(ArenaTest,AddAllocatedWithReflection)639 TEST(ArenaTest, AddAllocatedWithReflection) {
640   Arena arena1;
641   ArenaMessage* arena1_message = Arena::CreateMessage<ArenaMessage>(&arena1);
642   const Reflection* r = arena1_message->GetReflection();
643   const Descriptor* d = arena1_message->GetDescriptor();
644   const FieldDescriptor* fd =
645       d->FindFieldByName("repeated_import_no_arena_message");
646   // Message with cc_enable_arenas = false;
647   r->AddMessage(arena1_message, fd);
648   r->AddMessage(arena1_message, fd);
649   r->AddMessage(arena1_message, fd);
650   EXPECT_EQ(3, r->FieldSize(*arena1_message, fd));
651   // Message with cc_enable_arenas = true;
652   fd = d->FindFieldByName("repeated_nested_message");
653   r->AddMessage(arena1_message, fd);
654   r->AddMessage(arena1_message, fd);
655   r->AddMessage(arena1_message, fd);
656   EXPECT_EQ(3, r->FieldSize(*arena1_message, fd));
657 }
658 
TEST(ArenaTest,RepeatedPtrFieldAddClearedTest)659 TEST(ArenaTest, RepeatedPtrFieldAddClearedTest) {
660   {
661     RepeatedPtrField<TestAllTypes> repeated_field;
662     EXPECT_TRUE(repeated_field.empty());
663     EXPECT_EQ(0, repeated_field.size());
664     // Ownership is passed to repeated_field.
665     TestAllTypes* cleared = new TestAllTypes();
666     repeated_field.AddCleared(cleared);
667     EXPECT_TRUE(repeated_field.empty());
668     EXPECT_EQ(0, repeated_field.size());
669   }
670   {
671     RepeatedPtrField<TestAllTypes> repeated_field;
672     EXPECT_TRUE(repeated_field.empty());
673     EXPECT_EQ(0, repeated_field.size());
674     // Ownership is passed to repeated_field.
675     TestAllTypes* cleared = new TestAllTypes();
676     repeated_field.AddAllocated(cleared);
677     EXPECT_FALSE(repeated_field.empty());
678     EXPECT_EQ(1, repeated_field.size());
679   }
680 }
681 
TEST(ArenaTest,AddAllocatedToRepeatedField)682 TEST(ArenaTest, AddAllocatedToRepeatedField) {
683   // Heap->arena case.
684   Arena arena1;
685   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
686   for (int i = 0; i < 10; i++) {
687     TestAllTypes::NestedMessage* heap_submessage =
688         new TestAllTypes::NestedMessage();
689     heap_submessage->set_bb(42);
690     arena1_message->mutable_repeated_nested_message()->
691         AddAllocated(heap_submessage);
692     // Should not copy object -- will use arena_->Own().
693     EXPECT_EQ(heap_submessage,
694               &arena1_message->repeated_nested_message(i));
695     EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb());
696   }
697 
698   // Arena1->Arena2 case.
699   arena1_message->Clear();
700   for (int i = 0; i < 10; i++) {
701     Arena arena2;
702     TestAllTypes::NestedMessage* arena2_submessage =
703         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
704     arena2_submessage->set_bb(42);
705     arena1_message->mutable_repeated_nested_message()->
706         AddAllocated(arena2_submessage);
707     // Should copy object.
708     EXPECT_NE(arena2_submessage,
709               &arena1_message->repeated_nested_message(i));
710     EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb());
711   }
712 
713   // Arena->heap case.
714   TestAllTypes* heap_message = new TestAllTypes();
715   for (int i = 0; i < 10; i++) {
716     Arena arena2;
717     TestAllTypes::NestedMessage* arena2_submessage =
718         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
719     arena2_submessage->set_bb(42);
720     heap_message->mutable_repeated_nested_message()->
721         AddAllocated(arena2_submessage);
722     // Should copy object.
723     EXPECT_NE(arena2_submessage,
724               &heap_message->repeated_nested_message(i));
725     EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb());
726   }
727   delete heap_message;
728 
729   // Heap-arena case for strings (which are not arena-allocated).
730   arena1_message->Clear();
731   for (int i = 0; i < 10; i++) {
732     string* s = new string("Test");
733     arena1_message->mutable_repeated_string()->
734         AddAllocated(s);
735     // Should not copy.
736     EXPECT_EQ(s, &arena1_message->repeated_string(i));
737     EXPECT_EQ("Test", arena1_message->repeated_string(i));
738   }
739 }
740 
TEST(ArenaTest,AddAllocatedToRepeatedFieldViaReflection)741 TEST(ArenaTest, AddAllocatedToRepeatedFieldViaReflection) {
742   // Heap->arena case.
743   Arena arena1;
744   TestAllTypes* arena1_message = Arena::CreateMessage<TestAllTypes>(&arena1);
745   const Reflection* r = arena1_message->GetReflection();
746   const Descriptor* d = arena1_message->GetDescriptor();
747   const FieldDescriptor* fd =
748       d->FindFieldByName("repeated_nested_message");
749   for (int i = 0; i < 10; i++) {
750     TestAllTypes::NestedMessage* heap_submessage =
751         new TestAllTypes::NestedMessage;
752     heap_submessage->set_bb(42);
753     r->AddAllocatedMessage(arena1_message, fd, heap_submessage);
754     // Should not copy object -- will use arena_->Own().
755     EXPECT_EQ(heap_submessage,
756               &arena1_message->repeated_nested_message(i));
757     EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb());
758   }
759 
760   // Arena1->Arena2 case.
761   arena1_message->Clear();
762   for (int i = 0; i < 10; i++) {
763     Arena arena2;
764     TestAllTypes::NestedMessage* arena2_submessage =
765         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
766     arena2_submessage->set_bb(42);
767     r->AddAllocatedMessage(arena1_message, fd, arena2_submessage);
768     // Should copy object.
769     EXPECT_NE(arena2_submessage,
770               &arena1_message->repeated_nested_message(i));
771     EXPECT_EQ(42, arena1_message->repeated_nested_message(i).bb());
772   }
773 
774   // Arena->heap case.
775   TestAllTypes* heap_message = new TestAllTypes;
776   for (int i = 0; i < 10; i++) {
777     Arena arena2;
778     TestAllTypes::NestedMessage* arena2_submessage =
779         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena2);
780     arena2_submessage->set_bb(42);
781     r->AddAllocatedMessage(heap_message, fd, arena2_submessage);
782     // Should copy object.
783     EXPECT_NE(arena2_submessage,
784               &heap_message->repeated_nested_message(i));
785     EXPECT_EQ(42, heap_message->repeated_nested_message(i).bb());
786   }
787   delete heap_message;
788 }
789 
TEST(ArenaTest,ReleaseLastRepeatedField)790 TEST(ArenaTest, ReleaseLastRepeatedField) {
791   // Release from arena-allocated repeated field and ensure that returned object
792   // is heap-allocated.
793   Arena arena;
794   TestAllTypes* arena_message = Arena::CreateMessage<TestAllTypes>(&arena);
795   for (int i = 0; i < 10; i++) {
796     TestAllTypes::NestedMessage* nested =
797         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena);
798     nested->set_bb(42);
799     arena_message->mutable_repeated_nested_message()->AddAllocated(nested);
800   }
801 
802   for (int i = 0; i < 10; i++) {
803     const TestAllTypes::NestedMessage *orig_submessage =
804         &arena_message->repeated_nested_message(10 - 1 - i);  // last element
805     TestAllTypes::NestedMessage *released =
806         arena_message->mutable_repeated_nested_message()->ReleaseLast();
807     EXPECT_NE(released, orig_submessage);
808     EXPECT_EQ(42, released->bb());
809     delete released;
810   }
811 
812   // Test UnsafeArenaReleaseLast().
813   for (int i = 0; i < 10; i++) {
814     TestAllTypes::NestedMessage* nested =
815         Arena::CreateMessage<TestAllTypes::NestedMessage>(&arena);
816     nested->set_bb(42);
817     arena_message->mutable_repeated_nested_message()->AddAllocated(nested);
818   }
819 
820   for (int i = 0; i < 10; i++) {
821     const TestAllTypes::NestedMessage *orig_submessage =
822         &arena_message->repeated_nested_message(10 - 1 - i);  // last element
823     TestAllTypes::NestedMessage *released =
824         arena_message->mutable_repeated_nested_message()->
825         UnsafeArenaReleaseLast();
826     EXPECT_EQ(released, orig_submessage);
827     EXPECT_EQ(42, released->bb());
828     // no delete -- |released| is on the arena.
829   }
830 
831   // Test string case as well. ReleaseLast() in this case must copy the string,
832   // even though it was originally heap-allocated and its pointer was simply
833   // appended to the repeated field's internal vector, because the string was
834   // placed on the arena's destructor list and cannot be removed from that list
835   // (so the arena permanently owns the original instance).
836   arena_message->Clear();
837   for (int i = 0; i < 10; i++) {
838     string* s = new string("Test");
839     arena_message->mutable_repeated_string()->AddAllocated(s);
840   }
841   for (int i = 0; i < 10; i++) {
842     const string* orig_element = &arena_message->repeated_string(10 - 1 - i);
843     string* released = arena_message->mutable_repeated_string()->ReleaseLast();
844     EXPECT_NE(released, orig_element);
845     EXPECT_EQ("Test", *released);
846     delete released;
847   }
848 }
849 
TEST(ArenaTest,UnsafeArenaReleaseAdd)850 TEST(ArenaTest, UnsafeArenaReleaseAdd) {
851   // Use unsafe_arena_release() and unsafe_arena_set_allocated() to transfer an
852   // arena-allocated string from one message to another.
853   Arena arena;
854   TestAllTypes* message1 = Arena::CreateMessage<TestAllTypes>(&arena);
855   TestAllTypes* message2 = Arena::CreateMessage<TestAllTypes>(&arena);
856   string* arena_string = Arena::Create<string>(&arena);
857   *arena_string = "Test content";
858 
859   message1->unsafe_arena_set_allocated_optional_string(arena_string);
860   EXPECT_EQ(arena_string, message1->mutable_optional_string());
861   message2->unsafe_arena_set_allocated_optional_string(
862       message1->unsafe_arena_release_optional_string());
863   EXPECT_EQ(arena_string, message2->mutable_optional_string());
864 }
865 
TEST(ArenaTest,UnsafeArenaAddAllocated)866 TEST(ArenaTest, UnsafeArenaAddAllocated) {
867   Arena arena;
868   TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
869   for (int i = 0; i < 10; i++) {
870     string* arena_string = Arena::Create<string>(&arena);
871     message->mutable_repeated_string()->UnsafeArenaAddAllocated(arena_string);
872     EXPECT_EQ(arena_string, message->mutable_repeated_string(i));
873   }
874 }
875 
TEST(ArenaTest,UnsafeArenaRelease)876 TEST(ArenaTest, UnsafeArenaRelease) {
877   Arena arena;
878   TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
879 
880   string* s = new string("test string");
881   message->unsafe_arena_set_allocated_optional_string(s);
882   EXPECT_TRUE(message->has_optional_string());
883   EXPECT_EQ("test string", message->optional_string());
884   s = message->unsafe_arena_release_optional_string();
885   EXPECT_FALSE(message->has_optional_string());
886   delete s;
887 
888   s = new string("test string");
889   message->unsafe_arena_set_allocated_oneof_string(s);
890   EXPECT_TRUE(message->has_oneof_string());
891   EXPECT_EQ("test string", message->oneof_string());
892   s = message->unsafe_arena_release_oneof_string();
893   EXPECT_FALSE(message->has_oneof_string());
894   delete s;
895 }
896 
TEST(ArenaTest,ArenaOneofReflection)897 TEST(ArenaTest, ArenaOneofReflection) {
898   Arena arena;
899   TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
900   const Descriptor* desc = message->GetDescriptor();
901   const Reflection* refl = message->GetReflection();
902 
903   const FieldDescriptor* string_field = desc->FindFieldByName(
904       "oneof_string");
905   const FieldDescriptor* msg_field = desc->FindFieldByName(
906       "oneof_nested_message");
907   const OneofDescriptor* oneof = desc->FindOneofByName(
908       "oneof_field");
909 
910   refl->SetString(message, string_field, "Test value");
911   EXPECT_TRUE(refl->HasOneof(*message, oneof));
912   refl->ClearOneof(message, oneof);
913   EXPECT_FALSE(refl->HasOneof(*message, oneof));
914 
915   Message* submsg = refl->MutableMessage(message, msg_field);
916   EXPECT_TRUE(refl->HasOneof(*message, oneof));
917   refl->ClearOneof(message, oneof);
918   EXPECT_FALSE(refl->HasOneof(*message, oneof));
919   refl->MutableMessage(message, msg_field);
920   EXPECT_TRUE(refl->HasOneof(*message, oneof));
921   submsg = refl->ReleaseMessage(message, msg_field);
922   EXPECT_FALSE(refl->HasOneof(*message, oneof));
923   EXPECT_TRUE(submsg->GetArena() == NULL);
924   delete submsg;
925 }
926 
927 namespace {
TestSwapRepeatedField(Arena * arena1,Arena * arena2)928 void TestSwapRepeatedField(Arena* arena1, Arena* arena2) {
929   // Test "safe" (copying) semantics for direct Swap() on RepeatedPtrField
930   // between arenas.
931   RepeatedPtrField<TestAllTypes> field1(arena1);
932   RepeatedPtrField<TestAllTypes> field2(arena2);
933   for (int i = 0; i < 10; i++) {
934     TestAllTypes* t = Arena::CreateMessage<TestAllTypes>(arena1);
935     t->set_optional_string("field1");
936     t->set_optional_int32(i);
937     if (arena1 != NULL) {
938       field1.UnsafeArenaAddAllocated(t);
939     } else {
940       field1.AddAllocated(t);
941     }
942   }
943   for (int i = 0; i < 5; i++) {
944     TestAllTypes* t = Arena::CreateMessage<TestAllTypes>(arena2);
945     t->set_optional_string("field2");
946     t->set_optional_int32(i);
947     if (arena2 != NULL) {
948       field2.UnsafeArenaAddAllocated(t);
949     } else {
950       field2.AddAllocated(t);
951     }
952   }
953   field1.Swap(&field2);
954   EXPECT_EQ(5, field1.size());
955   EXPECT_EQ(10, field2.size());
956   EXPECT_TRUE(string("field1") == field2.Get(0).optional_string());
957   EXPECT_TRUE(string("field2") == field1.Get(0).optional_string());
958   // Ensure that fields retained their original order:
959   for (int i = 0; i < field1.size(); i++) {
960     EXPECT_EQ(i, field1.Get(i).optional_int32());
961   }
962   for (int i = 0; i < field2.size(); i++) {
963     EXPECT_EQ(i, field2.Get(i).optional_int32());
964   }
965 }
966 }  // namespace
967 
TEST(ArenaTest,SwapRepeatedField)968 TEST(ArenaTest, SwapRepeatedField) {
969   Arena arena;
970   TestSwapRepeatedField(&arena, &arena);
971 }
972 
TEST(ArenaTest,SwapRepeatedFieldWithDifferentArenas)973 TEST(ArenaTest, SwapRepeatedFieldWithDifferentArenas) {
974   Arena arena1;
975   Arena arena2;
976   TestSwapRepeatedField(&arena1, &arena2);
977 }
978 
TEST(ArenaTest,SwapRepeatedFieldWithNoArenaOnRightHandSide)979 TEST(ArenaTest, SwapRepeatedFieldWithNoArenaOnRightHandSide) {
980   Arena arena;
981   TestSwapRepeatedField(&arena, NULL);
982 }
983 
TEST(ArenaTest,SwapRepeatedFieldWithNoArenaOnLeftHandSide)984 TEST(ArenaTest, SwapRepeatedFieldWithNoArenaOnLeftHandSide) {
985   Arena arena;
986   TestSwapRepeatedField(NULL, &arena);
987 }
988 
TEST(ArenaTest,ExtensionsOnArena)989 TEST(ArenaTest, ExtensionsOnArena) {
990   Arena arena;
991   // Ensure no leaks.
992   TestAllExtensions* message_ext =
993       Arena::CreateMessage<TestAllExtensions>(&arena);
994   message_ext->SetExtension(
995       protobuf_unittest::optional_int32_extension, 42);
996   message_ext->SetExtension(
997       protobuf_unittest::optional_string_extension, string("test"));
998   message_ext->MutableExtension(
999       protobuf_unittest::optional_nested_message_extension)->set_bb(42);
1000 }
1001 
TEST(ArenaTest,RepeatedFieldOnArena)1002 TEST(ArenaTest, RepeatedFieldOnArena) {
1003   // Preallocate an initial arena block to avoid mallocs during hooked region.
1004   std::vector<char> arena_block(1024 * 1024);
1005   ArenaOptions options;
1006   options.initial_block = &arena_block[0];
1007   options.initial_block_size = arena_block.size();
1008   Arena arena(options);
1009 
1010   {
1011     internal::NoHeapChecker no_heap;
1012 
1013     // Fill some repeated fields on the arena to test for leaks. Also verify no
1014     // memory allocations.
1015     RepeatedField<int32> repeated_int32(&arena);
1016     RepeatedPtrField<TestAllTypes> repeated_message(&arena);
1017     for (int i = 0; i < 100; i++) {
1018       repeated_int32.Add(42);
1019       repeated_message.Add()->set_optional_int32(42);
1020       EXPECT_EQ(&arena, repeated_message.Get(0).GetArena());
1021       const TestAllTypes* msg_in_repeated_field = &repeated_message.Get(0);
1022       TestAllTypes* msg = repeated_message.UnsafeArenaReleaseLast();
1023       EXPECT_EQ(msg_in_repeated_field, msg);
1024     }
1025 
1026     // UnsafeArenaExtractSubrange (i) should not leak and (ii) should return
1027     // on-arena pointers.
1028     for (int i = 0; i < 10; i++) {
1029       repeated_message.Add()->set_optional_int32(42);
1030     }
1031     TestAllTypes* extracted_messages[5];
1032     repeated_message.UnsafeArenaExtractSubrange(0, 5, extracted_messages);
1033     EXPECT_EQ(&arena, repeated_message.Get(0).GetArena());
1034     EXPECT_EQ(5, repeated_message.size());
1035   }
1036 
1037   // Now, outside the scope of the NoHeapChecker, test ExtractSubrange's copying
1038   // semantics.
1039   {
1040     RepeatedPtrField<TestAllTypes> repeated_message(&arena);
1041     for (int i = 0; i < 100; i++) {
1042       repeated_message.Add()->set_optional_int32(42);
1043     }
1044 
1045     TestAllTypes* extracted_messages[5];
1046     // ExtractSubrange should copy to the heap.
1047     repeated_message.ExtractSubrange(0, 5, extracted_messages);
1048     EXPECT_EQ(NULL, extracted_messages[0]->GetArena());
1049     // We need to free the heap-allocated messages to prevent a leak.
1050     for (int i = 0; i < 5; i++) {
1051       delete extracted_messages[i];
1052       extracted_messages[i] = NULL;
1053     }
1054   }
1055 
1056   // Now check that we can create RepeatedFields/RepeatedPtrFields themselves on
1057   // the arena. They have the necessary type traits so that they can behave like
1058   // messages in this way. This is useful for higher-level generic templated
1059   // code that may allocate messages or repeated fields of messages on an arena.
1060   {
1061     RepeatedPtrField<TestAllTypes>* repeated_ptr_on_arena =
1062         Arena::CreateMessage< RepeatedPtrField<TestAllTypes> >(&arena);
1063     for (int i = 0; i < 10; i++) {
1064       // Add some elements and let the leak-checker ensure that everything is
1065       // freed.
1066       repeated_ptr_on_arena->Add();
1067     }
1068 
1069     RepeatedField<int>* repeated_int_on_arena =
1070         Arena::CreateMessage< RepeatedField<int> >(&arena);
1071     for (int i = 0; i < 100; i++) {
1072       repeated_int_on_arena->Add(i);
1073     }
1074 
1075   }
1076 
1077   arena.Reset();
1078 }
1079 
1080 
1081 #ifndef GOOGLE_PROTOBUF_NO_RTTI
TEST(ArenaTest,MutableMessageReflection)1082 TEST(ArenaTest, MutableMessageReflection) {
1083   Arena arena;
1084   TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
1085   const Reflection* r = message->GetReflection();
1086   const Descriptor* d = message->GetDescriptor();
1087   const FieldDescriptor* field = d->FindFieldByName("optional_nested_message");
1088   TestAllTypes::NestedMessage* submessage =
1089       static_cast<TestAllTypes::NestedMessage*>(
1090           r->MutableMessage(message, field));
1091   TestAllTypes::NestedMessage* submessage_expected =
1092       message->mutable_optional_nested_message();
1093 
1094   EXPECT_EQ(submessage_expected, submessage);
1095   EXPECT_EQ(&arena, submessage->GetArena());
1096 
1097   const FieldDescriptor* oneof_field = d->FindFieldByName("oneof_nested_message");
1098   submessage = static_cast<TestAllTypes::NestedMessage*>(
1099       r->MutableMessage(message, oneof_field));
1100   submessage_expected = message->mutable_oneof_nested_message();
1101 
1102   EXPECT_EQ(submessage_expected, submessage);
1103   EXPECT_EQ(&arena, submessage->GetArena());
1104 }
1105 #endif  // !GOOGLE_PROTOBUF_NO_RTTI
1106 
1107 
1108 namespace {
1109 
FillArenaAwareFields(TestAllTypes * message)1110 void FillArenaAwareFields(TestAllTypes* message) {
1111   string test_string = "hello world";
1112   message->set_optional_int32(42);
1113   message->set_optional_string(test_string);
1114   message->set_optional_bytes(test_string);
1115   message->mutable_optional_nested_message()->set_bb(42);
1116 
1117   message->set_oneof_uint32(42);
1118   message->mutable_oneof_nested_message()->set_bb(42);
1119   message->set_oneof_string(test_string);
1120   message->set_oneof_bytes(test_string);
1121 
1122   message->add_repeated_int32(42);
1123   // No repeated string: not yet arena-aware.
1124   message->add_repeated_nested_message()->set_bb(42);
1125   message->mutable_optional_lazy_message()->set_bb(42);
1126 }
1127 
1128 }
1129 
1130 // Test: no allocations occur on heap while touching all supported field types.
TEST(ArenaTest,NoHeapAllocationsTest)1131 TEST(ArenaTest, NoHeapAllocationsTest) {
1132   // Allocate a large initial block to avoid mallocs during hooked test.
1133   std::vector<char> arena_block(128 * 1024);
1134   ArenaOptions options;
1135   options.initial_block = &arena_block[0];
1136   options.initial_block_size = arena_block.size();
1137   Arena arena(options);
1138 
1139   {
1140 
1141     TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
1142     FillArenaAwareFields(message);
1143   }
1144 
1145   arena.Reset();
1146 }
1147 
1148 #ifndef GOOGLE_PROTOBUF_NO_RTTI
1149 // Test construction on an arena via generic MessageLite interface. We should be
1150 // able to successfully deserialize on the arena without incurring heap
1151 // allocations, i.e., everything should still be arena-allocation-aware.
TEST(ArenaTest,MessageLiteOnArena)1152 TEST(ArenaTest, MessageLiteOnArena) {
1153   std::vector<char> arena_block(128 * 1024);
1154   ArenaOptions options;
1155   options.initial_block = &arena_block[0];
1156   options.initial_block_size = arena_block.size();
1157   Arena arena(options);
1158   const google::protobuf::MessageLite* prototype = &TestAllTypes::default_instance();
1159 
1160   TestAllTypes initial_message;
1161   FillArenaAwareFields(&initial_message);
1162   string serialized;
1163   initial_message.SerializeToString(&serialized);
1164 
1165   {
1166 
1167     google::protobuf::MessageLite* generic_message = prototype->New(&arena);
1168     EXPECT_TRUE(generic_message != NULL);
1169     EXPECT_EQ(&arena, generic_message->GetArena());
1170     EXPECT_TRUE(generic_message->ParseFromString(serialized));
1171     TestAllTypes* deserialized = static_cast<TestAllTypes*>(generic_message);
1172     EXPECT_EQ(42, deserialized->optional_int32());
1173   }
1174 
1175   arena.Reset();
1176 }
1177 #endif  // !GOOGLE_PROTOBUF_NO_RTTI
1178 
1179 
1180 // RepeatedField should support non-POD types, and invoke constructors and
1181 // destructors appropriately, because it's used this way by lots of other code
1182 // (even if this was not its original intent).
TEST(ArenaTest,RepeatedFieldWithNonPODType)1183 TEST(ArenaTest, RepeatedFieldWithNonPODType) {
1184   {
1185     RepeatedField<string> field_on_heap;
1186     for (int i = 0; i < 100; i++) {
1187       *field_on_heap.Add() = "test string long enough to exceed inline buffer";
1188     }
1189   }
1190   {
1191     Arena arena;
1192     RepeatedField<string> field_on_arena(&arena);
1193     for (int i = 0; i < 100; i++) {
1194       *field_on_arena.Add() = "test string long enough to exceed inline buffer";
1195     }
1196   }
1197 }
1198 
1199 // Align n to next multiple of 8
1200 namespace {
Align8(uint64 n)1201 uint64 Align8(uint64 n) { return (n + 7) & -8; }
1202 }  // namespace
1203 
TEST(ArenaTest,SpaceAllocated_and_Used)1204 TEST(ArenaTest, SpaceAllocated_and_Used) {
1205   ArenaOptions options;
1206   options.start_block_size = 256;
1207   options.max_block_size = 8192;
1208   Arena arena_1(options);
1209   EXPECT_EQ(0, arena_1.SpaceAllocated());
1210   EXPECT_EQ(0, arena_1.SpaceUsed());
1211   EXPECT_EQ(0, arena_1.Reset());
1212   ::google::protobuf::Arena::CreateArray<char>(&arena_1, 320);
1213   // Arena will allocate slightly more than 320 for the block headers.
1214   EXPECT_LE(320, arena_1.SpaceAllocated());
1215   EXPECT_EQ(Align8(320), arena_1.SpaceUsed());
1216   EXPECT_LE(320, arena_1.Reset());
1217 
1218   // Test with initial block.
1219   std::vector<char> arena_block(1024);
1220   options.initial_block = &arena_block[0];
1221   options.initial_block_size = arena_block.size();
1222   Arena arena_2(options);
1223   EXPECT_EQ(1024, arena_2.SpaceAllocated());
1224   EXPECT_EQ(0, arena_2.SpaceUsed());
1225   EXPECT_EQ(1024, arena_2.Reset());
1226   ::google::protobuf::Arena::CreateArray<char>(&arena_2, 55);
1227   EXPECT_EQ(1024, arena_2.SpaceAllocated());
1228   EXPECT_EQ(Align8(55), arena_2.SpaceUsed());
1229   EXPECT_EQ(1024, arena_2.Reset());
1230 
1231   // Reset options to test doubling policy explicitly.
1232   options.initial_block = NULL;
1233   options.initial_block_size = 0;
1234   Arena arena_3(options);
1235   EXPECT_EQ(0, arena_3.SpaceUsed());
1236   ::google::protobuf::Arena::CreateArray<char>(&arena_3, 190);
1237   EXPECT_EQ(256, arena_3.SpaceAllocated());
1238   EXPECT_EQ(Align8(190), arena_3.SpaceUsed());
1239   ::google::protobuf::Arena::CreateArray<char>(&arena_3, 70);
1240   EXPECT_EQ(256 + 512, arena_3.SpaceAllocated());
1241   EXPECT_EQ(Align8(190) + Align8(70), arena_3.SpaceUsed());
1242   EXPECT_EQ(256 + 512, arena_3.Reset());
1243 }
1244 
TEST(ArenaTest,Alignment)1245 TEST(ArenaTest, Alignment) {
1246   ::google::protobuf::Arena arena;
1247   for (int i = 0; i < 200; i++) {
1248     void* p = ::google::protobuf::Arena::CreateArray<char>(&arena, i);
1249     GOOGLE_CHECK_EQ(reinterpret_cast<uintptr_t>(p) % 8, 0) << i << ": " << p;
1250   }
1251 }
1252 
TEST(ArenaTest,GetArenaShouldReturnTheArenaForArenaAllocatedMessages)1253 TEST(ArenaTest, GetArenaShouldReturnTheArenaForArenaAllocatedMessages) {
1254   ::google::protobuf::Arena arena;
1255   ArenaMessage* message = Arena::CreateMessage<ArenaMessage>(&arena);
1256   const ArenaMessage* const_pointer_to_message = message;
1257   EXPECT_EQ(&arena, Arena::GetArena(message));
1258   EXPECT_EQ(&arena, Arena::GetArena(const_pointer_to_message));
1259 }
1260 
TEST(ArenaTest,GetArenaShouldReturnNullForNonArenaAllocatedMessages)1261 TEST(ArenaTest, GetArenaShouldReturnNullForNonArenaAllocatedMessages) {
1262   ArenaMessage message;
1263   const ArenaMessage* const_pointer_to_message = &message;
1264   EXPECT_EQ(NULL, Arena::GetArena(&message));
1265   EXPECT_EQ(NULL, Arena::GetArena(const_pointer_to_message));
1266 }
1267 
TEST(ArenaTest,UnsafeSetAllocatedOnArena)1268 TEST(ArenaTest, UnsafeSetAllocatedOnArena) {
1269   ::google::protobuf::Arena arena;
1270   TestAllTypes* message = Arena::CreateMessage<TestAllTypes>(&arena);
1271   EXPECT_FALSE(message->has_optional_string());
1272 
1273   string owned_string = "test with long enough content to heap-allocate";
1274   message->unsafe_arena_set_allocated_optional_string(&owned_string);
1275   EXPECT_TRUE(message->has_optional_string());
1276 
1277   message->unsafe_arena_set_allocated_optional_string(NULL);
1278   EXPECT_FALSE(message->has_optional_string());
1279 }
1280 
1281 // A helper utility class to only contain static hook functions, some
1282 // counters to be used to verify the counters have been called and a cookie
1283 // value to be verified.
1284 class ArenaHooksTestUtil {
1285  public:
on_init(::google::protobuf::Arena * arena)1286   static void* on_init(::google::protobuf::Arena* arena) {
1287     ++num_init;
1288     int* cookie = new int(kCookieValue);
1289     return static_cast<void*>(cookie);
1290   }
1291 
on_allocation(const std::type_info *,uint64 alloc_size,void * cookie)1292   static void on_allocation(const std::type_info* /*unused*/, uint64 alloc_size,
1293                             void* cookie) {
1294     ++num_allocations;
1295     int cookie_value = *static_cast<int*>(cookie);
1296     EXPECT_EQ(kCookieValue, cookie_value);
1297   }
1298 
on_reset(::google::protobuf::Arena * arena,void * cookie,uint64 space_used)1299   static void on_reset(::google::protobuf::Arena* arena, void* cookie,
1300                        uint64 space_used) {
1301     ++num_reset;
1302     int cookie_value = *static_cast<int*>(cookie);
1303     EXPECT_EQ(kCookieValue, cookie_value);
1304   }
1305 
on_destruction(::google::protobuf::Arena * arena,void * cookie,uint64 space_used)1306   static void on_destruction(::google::protobuf::Arena* arena, void* cookie,
1307                              uint64 space_used) {
1308     ++num_destruct;
1309     int cookie_value = *static_cast<int*>(cookie);
1310     EXPECT_EQ(kCookieValue, cookie_value);
1311     delete static_cast<int*>(cookie);
1312   }
1313 
1314   static const int kCookieValue = 999;
1315   static uint32 num_init;
1316   static uint32 num_allocations;
1317   static uint32 num_reset;
1318   static uint32 num_destruct;
1319 };
1320 uint32 ArenaHooksTestUtil::num_init = 0;
1321 uint32 ArenaHooksTestUtil::num_allocations = 0;
1322 uint32 ArenaHooksTestUtil::num_reset = 0;
1323 uint32 ArenaHooksTestUtil::num_destruct = 0;
1324 const int ArenaHooksTestUtil::kCookieValue;
1325 
1326 // Test the hooks are correctly called and that the cookie is passed.
TEST(ArenaTest,ArenaHooksSanity)1327 TEST(ArenaTest, ArenaHooksSanity) {
1328   ::google::protobuf::ArenaOptions options;
1329   options.on_arena_init = ArenaHooksTestUtil::on_init;
1330   options.on_arena_allocation = ArenaHooksTestUtil::on_allocation;
1331   options.on_arena_reset = ArenaHooksTestUtil::on_reset;
1332   options.on_arena_destruction = ArenaHooksTestUtil::on_destruction;
1333 
1334   // Scope for defining the arena
1335   {
1336     ::google::protobuf::Arena arena(options);
1337     EXPECT_EQ(1, ArenaHooksTestUtil::num_init);
1338     EXPECT_EQ(0, ArenaHooksTestUtil::num_allocations);
1339     ::google::protobuf::Arena::Create<uint64>(&arena);
1340     if (google::protobuf::internal::has_trivial_destructor<uint64>::value) {
1341       EXPECT_EQ(1, ArenaHooksTestUtil::num_allocations);
1342     } else {
1343       EXPECT_EQ(2, ArenaHooksTestUtil::num_allocations);
1344     }
1345     arena.Reset();
1346     arena.Reset();
1347     EXPECT_EQ(2, ArenaHooksTestUtil::num_reset);
1348   }
1349   EXPECT_EQ(3, ArenaHooksTestUtil::num_reset);
1350   EXPECT_EQ(1, ArenaHooksTestUtil::num_destruct);
1351 }
1352 
1353 }  // namespace protobuf
1354 }  // namespace google
1355