xref: /freebsd/contrib/libder/libder/libder.c (revision 35c0a8c449fd2b7f75029ebed5e10852240f0865)
1 /*-
2  * Copyright (c) 2024 Kyle Evans <kevans@FreeBSD.org>
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6 
7 #include "libder_private.h"
8 
9 #include <stdlib.h>
10 #include <unistd.h>
11 
12 /*
13  * Sets up the context, returns NULL on error.
14  */
15 struct libder_ctx *
libder_open(void)16 libder_open(void)
17 {
18 	struct libder_ctx *ctx;
19 
20 	ctx = malloc(sizeof(*ctx));
21 	if (ctx == NULL)
22 		return (NULL);
23 
24 	/* Initialize */
25 	ctx->error = LDE_NONE;
26 	ctx->buffer_size = 0;
27 	ctx->verbose = 0;
28 	ctx->normalize = LIBDER_NORMALIZE_ALL;
29 	ctx->strict = true;
30 	ctx->abort = 0;
31 
32 	return (ctx);
33 }
34 
35 void
libder_abort(struct libder_ctx * ctx)36 libder_abort(struct libder_ctx *ctx)
37 {
38 
39 	ctx->abort = 1;
40 }
41 
42 LIBDER_PRIVATE size_t
libder_get_buffer_size(struct libder_ctx * ctx)43 libder_get_buffer_size(struct libder_ctx *ctx)
44 {
45 
46 	if (ctx->buffer_size == 0) {
47 		long psize;
48 
49 		psize = sysconf(_SC_PAGESIZE);
50 		if (psize <= 0)
51 			psize = 4096;
52 
53 		ctx->buffer_size = psize;
54 	}
55 
56 	return (ctx->buffer_size);
57 }
58 
59 uint64_t
libder_get_normalize(struct libder_ctx * ctx)60 libder_get_normalize(struct libder_ctx *ctx)
61 {
62 
63 	return (ctx->normalize);
64 }
65 
66 /*
67  * Set the normalization flags; returns the previous value.
68  */
69 uint64_t
libder_set_normalize(struct libder_ctx * ctx,uint64_t nmask)70 libder_set_normalize(struct libder_ctx *ctx, uint64_t nmask)
71 {
72 	uint64_t old = ctx->normalize;
73 
74 	ctx->normalize = (nmask & LIBDER_NORMALIZE_ALL);
75 	return (old);
76 }
77 
78 bool
libder_get_strict(struct libder_ctx * ctx)79 libder_get_strict(struct libder_ctx *ctx)
80 {
81 
82 	return (ctx->strict);
83 }
84 
85 bool
libder_set_strict(struct libder_ctx * ctx,bool strict)86 libder_set_strict(struct libder_ctx *ctx, bool strict)
87 {
88 	bool oval = ctx->strict;
89 
90 	ctx->strict = strict;
91 	return (oval);
92 }
93 
94 int
libder_get_verbose(struct libder_ctx * ctx)95 libder_get_verbose(struct libder_ctx *ctx)
96 {
97 
98 	return (ctx->verbose);
99 }
100 
101 int
libder_set_verbose(struct libder_ctx * ctx,int verbose)102 libder_set_verbose(struct libder_ctx *ctx, int verbose)
103 {
104 	int oval = ctx->verbose;
105 
106 	ctx->verbose = verbose;
107 	return (oval);
108 }
109 
110 void
libder_close(struct libder_ctx * ctx)111 libder_close(struct libder_ctx *ctx)
112 {
113 
114 	if (ctx == NULL)
115 		return;
116 
117 	free(ctx);
118 }
119 
120