1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3 * Copyright (C) 2021, VMware, Tzvetomir Stoyanov tz.stoyanov@gmail.com>
4 *
5 */
6 #include <stdlib.h>
7 #include <dlfcn.h>
8 #include <zlib.h>
9 #include <errno.h>
10
11 #include "trace-cmd-private.h"
12
13 #define __ZLIB_NAME "zlib"
14 #define __ZLIB_WEIGTH 10
15
zlib_compress(void * ctx,const void * in,int in_bytes,void * out,int out_bytes)16 static int zlib_compress(void *ctx, const void *in, int in_bytes, void *out, int out_bytes)
17 {
18 unsigned long obytes = out_bytes;
19 int ret;
20
21 ret = compress2((unsigned char *)out, &obytes,
22 (unsigned char *)in, (unsigned long)in_bytes, Z_BEST_COMPRESSION);
23 switch (ret) {
24 case Z_OK:
25 return obytes;
26 case Z_BUF_ERROR:
27 errno = -ENOBUFS;
28 break;
29 case Z_MEM_ERROR:
30 errno = -ENOMEM;
31 break;
32 case Z_STREAM_ERROR:
33 errno = -EINVAL;
34 break;
35 case Z_ERRNO:
36 break;
37 default:
38 errno = -EFAULT;
39 break;
40 }
41
42 return -1;
43 }
44
zlib_decompress(void * ctx,const void * in,int in_bytes,void * out,int out_bytes)45 static int zlib_decompress(void *ctx, const void *in, int in_bytes, void *out, int out_bytes)
46 {
47 unsigned long obytes = out_bytes;
48 int ret;
49
50 ret = uncompress((unsigned char *)out, &obytes,
51 (unsigned char *)in, (unsigned long)in_bytes);
52 switch (ret) {
53 case Z_OK:
54 return obytes;
55 case Z_BUF_ERROR:
56 errno = -ENOBUFS;
57 break;
58 case Z_MEM_ERROR:
59 errno = -ENOMEM;
60 break;
61 case Z_DATA_ERROR:
62 errno = -EINVAL;
63 break;
64 case Z_ERRNO:
65 break;
66 default:
67 errno = -EFAULT;
68 break;
69 }
70
71 return -1;
72 }
73
zlib_compress_bound(void * ctx,unsigned int in_bytes)74 static unsigned int zlib_compress_bound(void *ctx, unsigned int in_bytes)
75 {
76 return compressBound(in_bytes);
77 }
78
zlib_is_supported(const char * name,const char * version)79 static bool zlib_is_supported(const char *name, const char *version)
80 {
81 const char *zver;
82
83 if (!name)
84 return false;
85 if (strlen(name) != strlen(__ZLIB_NAME) || strcmp(name, __ZLIB_NAME))
86 return false;
87
88 if (!version)
89 return true;
90
91 zver = zlibVersion();
92 if (!zver)
93 return false;
94
95 /* Compare the major version number */
96 if (atoi(version) <= atoi(zver))
97 return true;
98
99 return false;
100 }
101
tracecmd_zlib_init(void)102 int tracecmd_zlib_init(void)
103 {
104 struct tracecmd_compression_proto proto;
105
106 memset(&proto, 0, sizeof(proto));
107 proto.name = __ZLIB_NAME;
108 proto.version = zlibVersion();
109 proto.weight = __ZLIB_WEIGTH;
110 proto.compress = zlib_compress;
111 proto.uncompress = zlib_decompress;
112 proto.is_supported = zlib_is_supported;
113 proto.compress_size = zlib_compress_bound;
114
115 return tracecmd_compress_proto_register(&proto);
116 }
117