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() : 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 int retval = 0;
38 header_.data_.segments += 1;
39 header_.data_.length += size;
40 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 return true;
43 }
44
Finish()45 bool TraceFileHelper::Finish()
46 {
47 int retval = 0;
48 retval = SHA256_Final(header_.data_.sha256, shaCtx_.get());
49 CHECK_TRUE(retval, false, "[%u] SHA256_Final FAILED!", header_.data_.segments);
50 return true;
51 }
52
Update(TraceFileHeader & header)53 bool TraceFileHelper::Update(TraceFileHeader& header)
54 {
55 CHECK_TRUE(Finish(), false, "Finish FAILED!");
56 if (memcpy_s(&header, sizeof(header), &header_, sizeof(header)) != 0) {
57 return false;
58 }
59 return true;
60 }
61
Validate(const TraceFileHeader & header)62 bool TraceFileHelper::Validate(const TraceFileHeader& header)
63 {
64 CHECK_TRUE(Finish(), false, "Finish FAILED!");
65 return memcmp(&header_, &header, sizeof(header_)) == 0;
66 return true;
67 }
68