blob: 609f5039309a0c9c4314742110d4991cc152e4f1 [file] [log] [blame]
Sajjad Mirza94c68bc2019-08-15 01:02:351// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/common/coverage_utils.h"
6
7#include <memory>
8
9#include "base/base_paths.h"
10#include "base/environment.h"
11#include "base/files/file.h"
12#include "base/files/file_path.h"
13#include "base/files/file_util.h"
14#include "base/logging.h"
15#include "base/path_service.h"
16#include "base/rand_util.h"
17#include "base/strings/strcat.h"
Sajjad Mirza68de71d2019-09-12 00:21:1018#include "base/strings/string16.h"
Sajjad Mirza94c68bc2019-08-15 01:02:3519#include "base/strings/string_number_conversions.h"
Sajjad Mirza68de71d2019-09-12 00:21:1020#include "base/strings/utf_string_conversions.h"
Sajjad Mirza94c68bc2019-08-15 01:02:3521#include "base/threading/thread_restrictions.h"
Sajjad Mirza68de71d2019-09-12 00:21:1022#include "build/build_config.h"
Sajjad Mirza94c68bc2019-08-15 01:02:3523
24namespace content {
25
26base::File OpenCoverageFile() {
27 base::ScopedAllowBlockingForTesting allows_blocking;
28 std::unique_ptr<base::Environment> env(base::Environment::Create());
29 std::string prof_template;
30 base::FilePath path;
31 if (env->GetVar("LLVM_PROFILE_FILE", &prof_template)) {
Sajjad Mirza68de71d2019-09-12 00:21:1032#if defined(OS_WIN)
33 path = base::FilePath(base::UTF8ToUTF16(prof_template)).DirName();
34#else
Sajjad Mirza94c68bc2019-08-15 01:02:3535 path = base::FilePath(prof_template).DirName();
Sajjad Mirza68de71d2019-09-12 00:21:1036#endif
Sajjad Mirza94c68bc2019-08-15 01:02:3537 base::CreateDirectory(path);
38 } else {
39 base::PathService::Get(base::DIR_CURRENT, &path);
40 }
41
42 // sajjadm@ and liaoyuke@ experimentally determined that a size 4 pool works
43 // well for the coverage builder.
44 int pool_index = base::RandInt(0, 3);
45 std::string filename = base::StrCat(
46 {"child_pool-", base::NumberToString(pool_index), ".profraw"});
Sajjad Mirza68de71d2019-09-12 00:21:1047#if defined(OS_WIN)
48 path = path.Append(base::UTF8ToUTF16(filename));
49#else
Sajjad Mirza94c68bc2019-08-15 01:02:3550 path = path.Append(filename);
Sajjad Mirza68de71d2019-09-12 00:21:1051#endif
Sajjad Mirza94c68bc2019-08-15 01:02:3552 uint32_t flags = base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ |
53 base::File::FLAG_WRITE;
54
55 base::File file(path, flags);
56 if (!file.IsValid()) {
57 LOG(ERROR) << "Opening file: " << path << " failed with "
58 << file.error_details();
59 }
60
61 return file;
62}
63
64} // namespace content