2 * Copyright (C) 2017 Simon Fels <morphis@gravedo.de>
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.
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.
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/>.
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"
23 #include <boost/filesystem.hpp>
25 #include <linux/loop.h>
28 #include <sys/ioctl.h>
30 #include <system_error>
32 namespace fs = boost::filesystem;
35 const constexpr char *loop_control_path{"/dev/loop-control"};
36 const constexpr char *base_loop_path{"/dev/loop"};
41 std::shared_ptr<LoopDevice> LoopDeviceAllocator::new_device() {
42 const auto ctl_fd = ::open(loop_control_path, O_RDWR);
44 throw std::system_error{errno, std::system_category()};
46 DeferAction close_ctl_fd{[&]() { ::close(ctl_fd); }};
48 const auto device_nr = ::ioctl(ctl_fd, LOOP_CTL_GET_FREE);
50 throw std::system_error{errno, std::system_category()};
52 return LoopDevice::create(utils::string_format("%s%d", base_loop_path, device_nr));