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