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.h"
19 #include "anbox/defer_action.h"
21 #include <system_error>
23 #include <linux/loop.h>
26 #include <sys/ioctl.h>
30 std::shared_ptr<LoopDevice> LoopDevice::create(const boost::filesystem::path &path) {
31 const auto fd = ::open(path.c_str(), O_RDWR);
33 throw std::system_error{errno, std::system_category()};
35 return std::shared_ptr<LoopDevice>(new LoopDevice(Fd{fd}, path));
38 LoopDevice::LoopDevice(Fd fd, const boost::filesystem::path &path) :
39 fd_{fd}, path_{path} {}
41 LoopDevice::~LoopDevice() {
45 ::ioctl(fd_, LOOP_CLR_FD);
49 bool LoopDevice::attach_file(const boost::filesystem::path &file_path) {
53 int file_fd = ::open(file_path.c_str(), O_RDONLY);
57 DeferAction close_file_fd{[&]() { ::close(file_fd); }};
59 if (::ioctl(fd_, LOOP_SET_FD, file_fd) < 0)