Apply patch for [CVE-2012-2677][boost] ordered_malloc() overflow
[external/boost.git] / libs / interprocess / example / comp_doc_anonymous_upgradable_mutexB.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
12 //[doc_anonymous_upgradable_mutexB
13 #include <boost/interprocess/shared_memory_object.hpp>
14 #include <boost/interprocess/mapped_region.hpp>
15 #include <boost/interprocess/sync/scoped_lock.hpp>
16 #include "doc_upgradable_mutex_shared_data.hpp"
17 #include <iostream>
18 #include <cstdio>
19
20 using namespace boost::interprocess;
21
22 int main ()
23 {
24    //Remove shared memory on destruction
25    struct shm_remove
26    {
27       ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
28    } remover;
29
30    //Open the shared memory object.
31    shared_memory_object shm
32       (open_only                    //only create
33       ,"MySharedMemory"              //name
34       ,read_write  //read-write mode
35       );
36
37    //Map the whole shared memory in this process
38    mapped_region region
39       (shm                       //What to map
40       ,read_write //Map it as read-write
41       );
42
43    //Get the address of the mapped region
44    void * addr       = region.get_address();
45
46    //Construct the shared structure in memory
47    shared_data * data = static_cast<shared_data*>(addr);
48
49    //Write some logs
50    for(int i = 0; i < 100; ++i){
51       //Lock the upgradable_mutex
52       scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex);
53       std::sprintf(data->items[(data->current_line++) % shared_data::NumItems]
54                ,"%s_%d", "process_a", i);
55       if(i == (shared_data::NumItems-1))
56          data->end_b = true;
57       //Mutex is released here
58    }
59
60    //Wait until the other process ends
61    while(1){
62       scoped_lock<interprocess_upgradable_mutex> lock(data->upgradable_mutex);
63       if(data->end_a)
64          break;
65    }
66    return 0;
67 }
68 //]
69
70 #include <boost/interprocess/detail/config_end.hpp>