• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     if (srcLen == 0) {
41         return false;
42     }
43     ISzAlloc alloc;
44     CXzUnpacker state;
45     alloc.Alloc = XzAlloc;
46     alloc.Free = XzFree;
47     XzUnpacker_Construct(&state, &alloc);
48     CrcGenerateTable();
49     Crc64GenerateTable();
50     size_t srcOff = 0;
51     size_t dstOff = 0;
52     std::vector<uint8_t> dst(srcLen, ' ');
53     ECoderStatus status = CODER_STATUS_NOT_FINISHED;
54     while (status == CODER_STATUS_NOT_FINISHED) {
55         dst.resize(dst.size() * EXPAND_FACTOR);
56         size_t srcRemain = srcLen - srcOff;
57         size_t dstRemain = dst.size() - dstOff;
58         int res = XzUnpacker_Code(&state,
59                                   reinterpret_cast<Byte*>(&dst[dstOff]), &dstRemain,
60                                   reinterpret_cast<const Byte*>(&src[srcOff]), &srcRemain,
61                                   true, CODER_FINISH_ANY, &status);
62         if (res != SZ_OK) {
63             XzUnpacker_Free(&state);
64             return false;
65         }
66         srcOff += srcRemain;
67         dstOff += dstRemain;
68     }
69     XzUnpacker_Free(&state);
70     if (!XzUnpacker_IsStreamWasFinished(&state)) {
71         return false;
72     }
73     dst.resize(dstOff);
74     *out = std::move(dst);
75     return true;
76 }
77 }   // namespace HiviewDFX
78 }   // namespace OHOS
79