1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
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 "trace_file_helper.h"
16
17 #include <climits>
18 #include <cstring>
19 #include <openssl/sha.h>
20 #include <securec.h>
21 #include "logging.h"
22
TraceFileHelper()23 TraceFileHelper::TraceFileHelper()
24 : shaCtx_(std::make_shared<SHA256_CTX>())
25 {
26 SHA256_Init(shaCtx_.get());
27 }
28
~TraceFileHelper()29 TraceFileHelper::~TraceFileHelper()
30 {
31 }
32
AddSegment(const uint8_t data[],uint32_t size)33 bool TraceFileHelper::AddSegment(const uint8_t data[], uint32_t size)
34 {
35 if (size > std::numeric_limits<decltype(header_.data_.length_)>::max() - header_.data_.length_ - sizeof(size)) {
36 return false;
37 }
38 int retval = 0;
39 header_.data_.segments_ += 1;
40
41 header_.data_.length_ += size;
42 retval = SHA256_Update(shaCtx_.get(), data, size);
43 CHECK_TRUE(retval, false, "[%u] SHA256_Update FAILED, s:%u, d:%p!", header_.data_.segments_, size, data);
44 return true;
45 }
46
Finish()47 bool TraceFileHelper::Finish()
48 {
49 int retval = 0;
50 retval = SHA256_Final(header_.data_.sha256_, shaCtx_.get());
51 CHECK_TRUE(retval, false, "[%u] SHA256_Final FAILED!", header_.data_.segments_);
52 return true;
53 }
54
Update(TraceFileHeader & header)55 bool TraceFileHelper::Update(TraceFileHeader& header)
56 {
57 CHECK_TRUE(Finish(), false, "Finish FAILED!");
58 if (memcpy_s(&header, sizeof(header), &header_, sizeof(header)) != 0) {
59 return false;
60 }
61 return true;
62 }
63
Validate(const TraceFileHeader & header)64 bool TraceFileHelper::Validate(const TraceFileHeader& header)
65 {
66 CHECK_TRUE(Finish(), false, "Finish FAILED!");
67 return memcmp(&header_, &header, sizeof(header_)) == 0;
68 }
69