06fefc21af16e732ee1ebe352fe2590ca0a899f9
[iec.git] / src / type3_AndroidCloud / anbox-master / src / anbox / common / loop_device_allocator.cpp
1 /*
2  * Copyright (C) 2017 Simon Fels <morphis@gravedo.de>
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 3, as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranties of
10  * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11  * PURPOSE.  See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  */
17
18 #include "anbox/common/loop_device_allocator.h"
19 #include "anbox/common/loop_device.h"
20 #include "anbox/defer_action.h"
21 #include "anbox/utils.h"
22
23 #include <boost/filesystem.hpp>
24
25 #include <linux/loop.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <sys/ioctl.h>
29
30 #include <system_error>
31
32 namespace fs = boost::filesystem;
33
34 namespace {
35 const constexpr char *loop_control_path{"/dev/loop-control"};
36 const constexpr char *base_loop_path{"/dev/loop"};
37 }
38
39 namespace anbox {
40 namespace common {
41 std::shared_ptr<LoopDevice> LoopDeviceAllocator::new_device() {
42   const auto ctl_fd = ::open(loop_control_path, O_RDWR);
43   if (ctl_fd < 0)
44     throw std::system_error{errno, std::system_category()};
45
46   DeferAction close_ctl_fd{[&]() { ::close(ctl_fd); }};
47
48   const auto device_nr = ::ioctl(ctl_fd, LOOP_CTL_GET_FREE);
49   if (device_nr < 0)
50     throw std::system_error{errno, std::system_category()};
51
52   return LoopDevice::create(utils::string_format("%s%d", base_loop_path, device_nr));
53 }
54 } // namespace common
55 } // namespace anbox