2 * SPDX-License-Identifier: ISC
4 * Copyright (c) 2004-2005, 2007, 2009-2015
5 * Todd C. Miller <Todd.Miller@sudo.ws>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
22 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
26 * Adapted from the following code written by Emin Martinian:
27 * http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html
29 * Copyright (c) 2001 Emin Martinian
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that neither the name of Emin
33 * Martinian nor the names of any contributors are be used to endorse or
34 * promote products derived from this software without specific prior
37 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
38 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
39 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
40 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
41 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
44 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
45 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
47 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
52 #include <sys/types.h>
60 static void rbrepair(struct rbtree *, struct rbnode *);
61 static void rotate_left(struct rbtree *, struct rbnode *);
62 static void rotate_right(struct rbtree *, struct rbnode *);
63 static void rbdestroy_int(struct rbtree *, struct rbnode *, void (*)(void *));
66 * Red-Black tree, see http://en.wikipedia.org/wiki/Red-black_tree
68 * A red-black tree is a binary search tree where each node has a color
69 * attribute, the value of which is either red or black. Essentially, it
70 * is just a convenient way to express a 2-3-4 binary search tree where
71 * the color indicates whether the node is part of a 3-node or a 4-node.
72 * In addition to the ordinary requirements imposed on binary search
73 * trees, we make the following additional requirements of any valid
75 * 1) Every node is either red or black.
76 * 2) The root is black.
77 * 3) All leaves are black.
78 * 4) Both children of each red node are black.
79 * 5) The paths from each leaf up to the root each contain the same
80 * number of black nodes.
84 * Create a red black tree struct using the specified compare routine.
85 * Allocates and returns the initialized (empty) tree or NULL if
86 * memory cannot be allocated.
89 rbcreate(int (*compar)(const void *, const void*))
92 debug_decl(rbcreate, SUDOERS_DEBUG_RBTREE)
94 if ((tree = malloc(sizeof(*tree))) == NULL) {
95 sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
96 "unable to allocate memory");
97 debug_return_ptr(NULL);
100 tree->compar = compar;
103 * We use a self-referencing sentinel node called nil to simplify the
104 * code by avoiding the need to check for NULL pointers.
106 tree->nil.left = tree->nil.right = tree->nil.parent = &tree->nil;
107 tree->nil.color = black;
108 tree->nil.data = NULL;
111 * Similarly, the fake root node keeps us from having to worry
112 * about splitting the root.
114 tree->root.left = tree->root.right = tree->root.parent = &tree->nil;
115 tree->root.color = black;
116 tree->root.data = NULL;
118 debug_return_ptr(tree);
122 * Perform a left rotation starting at node.
125 rotate_left(struct rbtree *tree, struct rbnode *node)
127 struct rbnode *child;
128 debug_decl(rotate_left, SUDOERS_DEBUG_RBTREE)
131 node->right = child->left;
133 if (child->left != rbnil(tree))
134 child->left->parent = node;
135 child->parent = node->parent;
137 if (node == node->parent->left)
138 node->parent->left = child;
140 node->parent->right = child;
142 node->parent = child;
148 * Perform a right rotation starting at node.
151 rotate_right(struct rbtree *tree, struct rbnode *node)
153 struct rbnode *child;
154 debug_decl(rotate_right, SUDOERS_DEBUG_RBTREE)
157 node->left = child->right;
159 if (child->right != rbnil(tree))
160 child->right->parent = node;
161 child->parent = node->parent;
163 if (node == node->parent->left)
164 node->parent->left = child;
166 node->parent->right = child;
168 node->parent = child;
174 * Insert data pointer into a redblack tree.
175 * Returns a 0 on success, 1 if a node matching "data" already exists
176 * (filling in "existing" if not NULL), or -1 on malloc() failure.
179 rbinsert(struct rbtree *tree, void *data, struct rbnode **existing)
181 struct rbnode *node = rbfirst(tree);
182 struct rbnode *parent = rbroot(tree);
184 debug_decl(rbinsert, SUDOERS_DEBUG_RBTREE)
186 /* Find correct insertion point. */
187 while (node != rbnil(tree)) {
189 if ((res = tree->compar(data, node->data)) == 0) {
190 if (existing != NULL)
194 node = res < 0 ? node->left : node->right;
197 node = malloc(sizeof(*node));
199 sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
200 "unable to allocate memory");
201 debug_return_int(-1);
204 node->left = node->right = rbnil(tree);
205 node->parent = parent;
206 if (parent == rbroot(tree) || tree->compar(data, parent->data) < 0)
209 parent->right = node;
213 * If the parent node is black we are all set, if it is red we have
214 * the following possible cases to deal with. We iterate through
215 * the rest of the tree to make sure none of the required properties
218 * 1) The uncle is red. We repaint both the parent and uncle black
219 * and repaint the grandparent node red.
221 * 2) The uncle is black and the new node is the right child of its
222 * parent, and the parent in turn is the left child of its parent.
223 * We do a left rotation to switch the roles of the parent and
224 * child, relying on further iterations to fixup the old parent.
226 * 3) The uncle is black and the new node is the left child of its
227 * parent, and the parent in turn is the left child of its parent.
228 * We switch the colors of the parent and grandparent and perform
229 * a right rotation around the grandparent. This makes the former
230 * parent the parent of the new node and the former grandparent.
232 * Note that because we use a sentinel for the root node we never
233 * need to worry about replacing the root.
235 while (node->parent->color == red) {
236 struct rbnode *uncle;
237 if (node->parent == node->parent->parent->left) {
238 uncle = node->parent->parent->right;
239 if (uncle->color == red) {
240 node->parent->color = black;
241 uncle->color = black;
242 node->parent->parent->color = red;
243 node = node->parent->parent;
244 } else /* if (uncle->color == black) */ {
245 if (node == node->parent->right) {
247 rotate_left(tree, node);
249 node->parent->color = black;
250 node->parent->parent->color = red;
251 rotate_right(tree, node->parent->parent);
253 } else { /* if (node->parent == node->parent->parent->right) */
254 uncle = node->parent->parent->left;
255 if (uncle->color == red) {
256 node->parent->color = black;
257 uncle->color = black;
258 node->parent->parent->color = red;
259 node = node->parent->parent;
260 } else /* if (uncle->color == black) */ {
261 if (node == node->parent->left) {
263 rotate_right(tree, node);
265 node->parent->color = black;
266 node->parent->parent->color = red;
267 rotate_left(tree, node->parent->parent);
271 rbfirst(tree)->color = black; /* first node is always black */
276 * Look for a node matching key in tree.
277 * Returns a pointer to the node if found, else NULL.
280 rbfind(struct rbtree *tree, void *key)
282 struct rbnode *node = rbfirst(tree);
284 debug_decl(rbfind, SUDOERS_DEBUG_RBTREE)
286 while (node != rbnil(tree)) {
287 if ((res = tree->compar(key, node->data)) == 0)
288 debug_return_ptr(node);
289 node = res < 0 ? node->left : node->right;
291 debug_return_ptr(NULL);
295 * Call func() for each node, passing it the node data and a cookie;
296 * If func() returns non-zero for a node, the traversal stops and the
297 * error value is returned. Returns 0 on successful traversal.
300 rbapply_node(struct rbtree *tree, struct rbnode *node,
301 int (*func)(void *, void *), void *cookie, enum rbtraversal order)
304 debug_decl(rbapply_node, SUDOERS_DEBUG_RBTREE)
306 if (node != rbnil(tree)) {
307 if (order == preorder)
308 if ((error = func(node->data, cookie)) != 0)
309 debug_return_int(error);
310 if ((error = rbapply_node(tree, node->left, func, cookie, order)) != 0)
311 debug_return_int(error);
312 if (order == inorder)
313 if ((error = func(node->data, cookie)) != 0)
314 debug_return_int(error);
315 if ((error = rbapply_node(tree, node->right, func, cookie, order)) != 0)
316 debug_return_int(error);
317 if (order == postorder)
318 if ((error = func(node->data, cookie)) != 0)
319 debug_return_int(error);
325 * Returns the successor of node, or nil if there is none.
327 static struct rbnode *
328 rbsuccessor(struct rbtree *tree, struct rbnode *node)
331 debug_decl(rbsuccessor, SUDOERS_DEBUG_RBTREE)
333 if ((succ = node->right) != rbnil(tree)) {
334 while (succ->left != rbnil(tree))
337 /* No right child, move up until we find it or hit the root */
338 for (succ = node->parent; node == succ->right; succ = succ->parent)
340 if (succ == rbroot(tree))
343 debug_return_ptr(succ);
347 * Recursive portion of rbdestroy().
350 rbdestroy_int(struct rbtree *tree, struct rbnode *node, void (*destroy)(void *))
352 debug_decl(rbdestroy_int, SUDOERS_DEBUG_RBTREE)
353 if (node != rbnil(tree)) {
354 rbdestroy_int(tree, node->left, destroy);
355 rbdestroy_int(tree, node->right, destroy);
364 * Destroy the specified tree, calling the destructor "destroy"
365 * for each node and then freeing the tree itself.
368 rbdestroy(struct rbtree *tree, void (*destroy)(void *))
370 debug_decl(rbdestroy, SUDOERS_DEBUG_RBTREE)
371 rbdestroy_int(tree, rbfirst(tree), destroy);
377 * Delete node 'z' from the tree and return its data pointer.
379 void *rbdelete(struct rbtree *tree, struct rbnode *z)
381 struct rbnode *x, *y;
382 void *data = z->data;
383 debug_decl(rbdelete, SUDOERS_DEBUG_RBTREE)
385 if (z->left == rbnil(tree) || z->right == rbnil(tree))
388 y = rbsuccessor(tree, z);
389 x = (y->left == rbnil(tree)) ? y->right : y->left;
391 if ((x->parent = y->parent) == rbroot(tree)) {
394 if (y == y->parent->left)
397 y->parent->right = x;
399 if (y->color == black)
404 y->parent = z->parent;
406 z->left->parent = z->right->parent = y;
407 if (z == z->parent->left)
410 z->parent->right = y;
414 debug_return_ptr(data);
418 * Repair the tree after a node has been deleted by rotating and repainting
419 * colors to restore the 4 properties inherent in red-black trees.
422 rbrepair(struct rbtree *tree, struct rbnode *node)
424 struct rbnode *sibling;
425 debug_decl(rbrepair, SUDOERS_DEBUG_RBTREE)
427 while (node->color == black && node != rbfirst(tree)) {
428 if (node == node->parent->left) {
429 sibling = node->parent->right;
430 if (sibling->color == red) {
431 sibling->color = black;
432 node->parent->color = red;
433 rotate_left(tree, node->parent);
434 sibling = node->parent->right;
436 if (sibling->right->color == black && sibling->left->color == black) {
437 sibling->color = red;
440 if (sibling->right->color == black) {
441 sibling->left->color = black;
442 sibling->color = red;
443 rotate_right(tree, sibling);
444 sibling = node->parent->right;
446 sibling->color = node->parent->color;
447 node->parent->color = black;
448 sibling->right->color = black;
449 rotate_left(tree, node->parent);
450 node = rbfirst(tree); /* exit loop */
452 } else { /* if (node == node->parent->right) */
453 sibling = node->parent->left;
454 if (sibling->color == red) {
455 sibling->color = black;
456 node->parent->color = red;
457 rotate_right(tree, node->parent);
458 sibling = node->parent->left;
460 if (sibling->right->color == black && sibling->left->color == black) {
461 sibling->color = red;
464 if (sibling->left->color == black) {
465 sibling->right->color = black;
466 sibling->color = red;
467 rotate_left(tree, sibling);
468 sibling = node->parent->left;
470 sibling->color = node->parent->color;
471 node->parent->color = black;
472 sibling->left->color = black;
473 rotate_right(tree, node->parent);
474 node = rbfirst(tree); /* exit loop */