blob: 202ee2ebbd1d29ecc36a83f89e5f608191959398 [file] [log] [blame]
Andreas Gamped0aac252018-03-22 08:20:08 -07001/*
2**
3** Copyright 2015, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include "perfprofd_io.h"
19
20#include <fcntl.h>
21#include <unistd.h>
22
23#include <memory>
24
25#include <android-base/file.h>
26#include <android-base/logging.h>
27#include <android-base/unique_fd.h>
28
29#include "perfprofd_record.pb.h"
30
31namespace android {
32namespace perfprofd {
33
34bool SerializeProtobuf(PerfprofdRecord* encodedProfile,
35 const char* encoded_file_path) {
36 //
37 // Serialize protobuf to array
38 //
39 size_t size = encodedProfile->ByteSize();
40 std::unique_ptr<uint8_t[]> data(new uint8_t[size]);
41 encodedProfile->SerializeWithCachedSizesToArray(data.get());
42
43 //
44 // Open file and write encoded data to it
45 //
46 unlink(encoded_file_path); // Attempt to unlink for a clean slate.
47 constexpr int kFlags = O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC;
48 android::base::unique_fd fd(open(encoded_file_path, kFlags, 0664));
49 if (fd.get() == -1) {
50 PLOG(WARNING) << "Could not open " << encoded_file_path << " for serialization";
51 return false;
52 }
53 if (!android::base::WriteFully(fd.get(), data.get(), size)) {
54 PLOG(WARNING) << "Could not write to " << encoded_file_path;
55 return false;
56 }
57
58 return true;
59}
60
61} // namespace perfprofd
62} // namespace android