1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "common/libs/utils/shared_fd_flag.h"
17 
18 #include <unistd.h>
19 
20 #include <functional>
21 #include <limits>
22 #include <memory>
23 #include <ostream>
24 #include <string>
25 
26 #include <android-base/logging.h>
27 #include <android-base/parseint.h>
28 
29 #include "common/libs/fs/shared_fd.h"
30 #include "common/libs/utils/flag_parser.h"
31 
32 namespace cuttlefish {
33 
Set(const FlagMatch & match,SharedFD & out)34 static Result<void> Set(const FlagMatch& match, SharedFD& out) {
35   int raw_fd;
36   CF_EXPECTF(android::base::ParseInt(match.value.c_str(), &raw_fd),
37              "Failed to parse value \"{}\" for fd flag \"{}\"", match.value,
38              match.key);
39   out = SharedFD::Dup(raw_fd);
40   if (out->IsOpen()) {
41     close(raw_fd);
42   }
43   return {};
44 }
45 
SharedFDFlag(SharedFD & out)46 Flag SharedFDFlag(SharedFD& out) {
47   return Flag().Setter([&](const FlagMatch& mat) { return Set(mat, out); });
48 }
SharedFDFlag(const std::string & name,SharedFD & out)49 Flag SharedFDFlag(const std::string& name, SharedFD& out) {
50   return GflagsCompatFlag(name).Setter(
51       [&out](const FlagMatch& mat) { return Set(mat, out); });
52 }
53 
54 }  // namespace cuttlefish
55