1 // Copyright (C) 2016 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <unistd.h>
16 
17 #include <map>
18 #include <sstream>
19 #include <string>
20 
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/strings.h>
24 
Usage(char * argv[])25 void Usage(char* argv[]) {
26     printf("Usage: %s <status field> <value> [<status field> <value>]*\n", argv[0]);
27     printf("E.g.: $ %s Uid \"1000 1000 1000 1000\"\n", argv[0]);
28 }
29 
main(int argc,char * argv[])30 int main(int argc, char* argv[]) {
31     if (argc < 3) {
32         Usage(argv);
33         LOG(FATAL) << "no status field requested";
34     }
35     if (argc % 2 == 0) {
36         // Since |argc| counts argv[0], if |argc| is odd, then the number of
37         // command-line arguments is even.
38         Usage(argv);
39         LOG(FATAL) << "need even number of command-line arguments";
40     }
41 
42     std::string status;
43     bool res = android::base::ReadFileToString("/proc/self/status", &status, true);
44     if (!res) {
45         PLOG(FATAL) << "could not read /proc/self/status";
46     }
47 
48     std::map<std::string, std::string> fields;
49     std::vector<std::string> lines = android::base::Split(status, "\n");
50     for (const auto& line : lines) {
51         std::vector<std::string> tokens = android::base::Split(line, ":");
52         if (tokens.size() >= 2) {
53             std::string field = tokens[0];
54             std::string value = android::base::Trim(tokens[1]);
55             if (field.length() > 0) {
56                 fields[field] = value;
57             }
58         }
59     }
60 
61     bool test_fails = false;
62     for (size_t i = 1; i < static_cast<size_t>(argc); i = i + 2) {
63         std::string expected_value = argv[i + 1];
64         auto f = fields.find(argv[i]);
65         if (f != fields.end()) {
66             if (f->second != expected_value) {
67                 LOG(ERROR) << "field '" << argv[i] << "' expected '" << expected_value
68                            << "', actual '" << f->second << "'";
69                 test_fails = true;
70             }
71         } else {
72             LOG(WARNING) << "could not find field '" << argv[i] << "'";
73         }
74     }
75 
76     return test_fails ? 1 : 0;
77 }
78