Apply patch for [CVE-2012-2677][boost] ordered_malloc() overflow
[external/boost.git] / libs / interprocess / example / comp_doc_anonymous_mutexA.cpp
1 //////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // See http://www.boost.org/libs/interprocess for documentation.
8 //
9 //////////////////////////////////////////////////////////////////////////////
10 #include <boost/interprocess/detail/config_begin.hpp>
11 //[doc_anonymous_mutexA
12 #include <boost/interprocess/shared_memory_object.hpp>
13 #include <boost/interprocess/mapped_region.hpp>
14 #include <boost/interprocess/sync/scoped_lock.hpp>
15 #include "doc_anonymous_mutex_shared_data.hpp"
16 #include <iostream>
17 #include <cstdio>
18
19 using namespace boost::interprocess;
20
21 int main ()
22 {
23    try{
24       //Remove shared memory on construction and destruction
25       struct shm_remove
26       {
27          shm_remove() { shared_memory_object::remove("MySharedMemory"); }
28          ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
29       } remover;
30
31       //Create a shared memory object.
32       shared_memory_object shm
33          (create_only               //only create
34          ,"MySharedMemory"          //name
35          ,read_write   //read-write mode
36          );
37
38       //Set size
39       shm.truncate(sizeof(shared_memory_log));
40
41       //Map the whole shared memory in this process
42       mapped_region region
43          (shm                       //What to map
44          ,read_write   //Map it as read-write
45          );
46
47       //Get the address of the mapped region
48       void * addr       = region.get_address();
49
50       //Construct the shared structure in memory
51       shared_memory_log * data = new (addr) shared_memory_log;
52
53       //Write some logs
54       for(int i = 0; i < shared_memory_log::NumItems; ++i){
55          //Lock the mutex
56          scoped_lock<interprocess_mutex> lock(data->mutex);
57          std::sprintf(data->items[(data->current_line++) % shared_memory_log::NumItems]
58                   ,"%s_%d", "process_a", i);
59          if(i == (shared_memory_log::NumItems-1))
60             data->end_a = true;
61          //Mutex is released here
62       }
63
64       //Wait until the other process ends
65       while(1){
66          scoped_lock<interprocess_mutex> lock(data->mutex);
67          if(data->end_b)
68             break;
69       }
70    }
71    catch(interprocess_exception &ex){
72       std::cout << ex.what() << std::endl;
73       return 1;
74    }
75    return 0;
76 }
77 //]
78 #include <boost/interprocess/detail/config_end.hpp>