1 /*
2  * Copyright (C) 2020 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 
17 #include <fcntl.h>
18 #include <stdbool.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <sys/stat.h>
22 #include <sys/types.h>
23 #include <unistd.h>
24 
25 // This file provides a wrapper for open.
26 
27 extern "C" {
28 
29 int __real_open(const char* pathname, int flags, ...);
30 
needs_mode(int flags)31 static bool needs_mode(int flags) {
32   return ((flags & O_CREAT) == O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE);
33 }
34 
35 static const char* PROFRAW_START = "/data/misc/trace/";
is_coverage_trace(const char * pathname)36 static bool is_coverage_trace(const char* pathname) {
37   if (strncmp(pathname, PROFRAW_START, strlen(PROFRAW_START)) == 0) return true;
38   return false;
39 }
40 
__wrap_open(const char * pathname,int flags,...)41 __attribute__((weak)) int __wrap_open(const char* pathname, int flags, ...) {
42   if (!needs_mode(flags)) {
43     return __real_open(pathname, flags);
44   }
45 
46   va_list args;
47   va_start(args, flags);
48   mode_t mode = static_cast<mode_t>(va_arg(args, int));
49   va_end(args);
50 
51   int ret = __real_open(pathname, flags, mode);
52   if (ret != -1 && is_coverage_trace(pathname)) fchmod(ret, mode);
53   return ret;
54 }
55 }
56