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 bool Set(const FlagMatch& match, SharedFD& out) {
35 int raw_fd;
36 if (!android::base::ParseInt(match.value.c_str(), &raw_fd)) {
37 LOG(ERROR) << "Failed to parse value \"" << match.value
38 << "\" for fd flag \"" << match.key << "\"";
39 return false;
40 }
41 out = SharedFD::Dup(raw_fd);
42 if (out->IsOpen()) {
43 close(raw_fd);
44 }
45 return true;
46 }
47
SharedFDFlag(SharedFD & out)48 Flag SharedFDFlag(SharedFD& out) {
49 return Flag().Setter([&](const FlagMatch& mat) { return Set(mat, out); });
50 }
SharedFDFlag(const std::string & name,SharedFD & out)51 Flag SharedFDFlag(const std::string& name, SharedFD& out) {
52 return GflagsCompatFlag(name).Setter(
53 [&out](const FlagMatch& mat) { return Set(mat, out); });
54 }
55
56 } // namespace cuttlefish
57