1 /*
2  * Copyright (c) 2023 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 "dfx_xz_utils.h"
16 #include "dfx_trace_dlsym.h"
17 #include "7zCrc.h"
18 #include "Xz.h"
19 #include "XzCrc64.h"
20 #include <cstdlib>
21 
22 namespace OHOS {
23 namespace HiviewDFX {
24 
25 #define EXPAND_FACTOR 2
26 
XzAlloc(ISzAllocPtr,size_t size)27 static void* XzAlloc(ISzAllocPtr, size_t size)
28 {
29     return malloc(size);
30 }
31 
XzFree(ISzAllocPtr,void * address)32 static void XzFree(ISzAllocPtr, void *address)
33 {
34     free(address);
35 }
36 
XzDecompress(const uint8_t * src,size_t srcLen,std::shared_ptr<std::vector<uint8_t>> out)37 bool XzDecompress(const uint8_t *src, size_t srcLen, std::shared_ptr<std::vector<uint8_t>> out)
38 {
39     DFX_TRACE_SCOPED_DLSYM("XzDecompress");
40     ISzAlloc alloc;
41     CXzUnpacker state;
42     alloc.Alloc = XzAlloc;
43     alloc.Free = XzFree;
44     XzUnpacker_Construct(&state, &alloc);
45     CrcGenerateTable();
46     Crc64GenerateTable();
47     size_t srcOff = 0;
48     size_t dstOff = 0;
49     std::vector<uint8_t> dst(srcLen, ' ');
50     ECoderStatus status = CODER_STATUS_NOT_FINISHED;
51     while (status == CODER_STATUS_NOT_FINISHED) {
52         dst.resize(dst.size() * EXPAND_FACTOR);
53         size_t srcRemain = srcLen - srcOff;
54         size_t dstRemain = dst.size() - dstOff;
55         int res = XzUnpacker_Code(&state,
56                                   reinterpret_cast<Byte*>(&dst[dstOff]), &dstRemain,
57                                   reinterpret_cast<const Byte*>(&src[srcOff]), &srcRemain,
58                                   true, CODER_FINISH_ANY, &status);
59         if (res != SZ_OK) {
60             XzUnpacker_Free(&state);
61             return false;
62         }
63         srcOff += srcRemain;
64         dstOff += dstRemain;
65     }
66     XzUnpacker_Free(&state);
67     if (!XzUnpacker_IsStreamWasFinished(&state)) {
68         return false;
69     }
70     dst.resize(dstOff);
71     *out = std::move(dst);
72     return true;
73 }
74 }   // namespace HiviewDFX
75 }   // namespace OHOS
76