2 * Copyright (c) 2004-2005, 2007, 2009-2015
3 * Todd C. Miller <Todd.Miller@sudo.ws>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
20 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
24 * Adapted from the following code written by Emin Martinian:
25 * http://web.mit.edu/~emin/www/source_code/red_black_tree/index.html
27 * Copyright (c) 2001 Emin Martinian
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that neither the name of Emin
31 * Martinian nor the names of any contributors are be used to endorse or
32 * promote products derived from this software without specific prior
35 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
50 #include <sys/types.h>
58 static void rbrepair(struct rbtree *, struct rbnode *);
59 static void rotate_left(struct rbtree *, struct rbnode *);
60 static void rotate_right(struct rbtree *, struct rbnode *);
61 static void rbdestroy_int(struct rbtree *, struct rbnode *, void (*)(void *));
64 * Red-Black tree, see http://en.wikipedia.org/wiki/Red-black_tree
66 * A red-black tree is a binary search tree where each node has a color
67 * attribute, the value of which is either red or black. Essentially, it
68 * is just a convenient way to express a 2-3-4 binary search tree where
69 * the color indicates whether the node is part of a 3-node or a 4-node.
70 * In addition to the ordinary requirements imposed on binary search
71 * trees, we make the following additional requirements of any valid
73 * 1) Every node is either red or black.
74 * 2) The root is black.
75 * 3) All leaves are black.
76 * 4) Both children of each red node are black.
77 * 5) The paths from each leaf up to the root each contain the same
78 * number of black nodes.
82 * Create a red black tree struct using the specified compare routine.
83 * Allocates and returns the initialized (empty) tree or NULL if
84 * memory cannot be allocated.
87 rbcreate(int (*compar)(const void *, const void*))
90 debug_decl(rbcreate, SUDOERS_DEBUG_RBTREE)
92 if ((tree = malloc(sizeof(*tree))) == NULL) {
93 sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
94 "unable to allocate memory");
95 debug_return_ptr(NULL);
98 tree->compar = compar;
101 * We use a self-referencing sentinel node called nil to simplify the
102 * code by avoiding the need to check for NULL pointers.
104 tree->nil.left = tree->nil.right = tree->nil.parent = &tree->nil;
105 tree->nil.color = black;
106 tree->nil.data = NULL;
109 * Similarly, the fake root node keeps us from having to worry
110 * about splitting the root.
112 tree->root.left = tree->root.right = tree->root.parent = &tree->nil;
113 tree->root.color = black;
114 tree->root.data = NULL;
116 debug_return_ptr(tree);
120 * Perform a left rotation starting at node.
123 rotate_left(struct rbtree *tree, struct rbnode *node)
125 struct rbnode *child;
126 debug_decl(rotate_left, SUDOERS_DEBUG_RBTREE)
129 node->right = child->left;
131 if (child->left != rbnil(tree))
132 child->left->parent = node;
133 child->parent = node->parent;
135 if (node == node->parent->left)
136 node->parent->left = child;
138 node->parent->right = child;
140 node->parent = child;
146 * Perform a right rotation starting at node.
149 rotate_right(struct rbtree *tree, struct rbnode *node)
151 struct rbnode *child;
152 debug_decl(rotate_right, SUDOERS_DEBUG_RBTREE)
155 node->left = child->right;
157 if (child->right != rbnil(tree))
158 child->right->parent = node;
159 child->parent = node->parent;
161 if (node == node->parent->left)
162 node->parent->left = child;
164 node->parent->right = child;
166 node->parent = child;
172 * Insert data pointer into a redblack tree.
173 * Returns a 0 on success, 1 if a node matching "data" already exists
174 * (filling in "existing" if not NULL), or -1 on malloc() failure.
177 rbinsert(struct rbtree *tree, void *data, struct rbnode **existing)
179 struct rbnode *node = rbfirst(tree);
180 struct rbnode *parent = rbroot(tree);
182 debug_decl(rbinsert, SUDOERS_DEBUG_RBTREE)
184 /* Find correct insertion point. */
185 while (node != rbnil(tree)) {
187 if ((res = tree->compar(data, node->data)) == 0) {
188 if (existing != NULL)
192 node = res < 0 ? node->left : node->right;
195 node = malloc(sizeof(*node));
197 sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO,
198 "unable to allocate memory");
199 debug_return_int(-1);
202 node->left = node->right = rbnil(tree);
203 node->parent = parent;
204 if (parent == rbroot(tree) || tree->compar(data, parent->data) < 0)
207 parent->right = node;
211 * If the parent node is black we are all set, if it is red we have
212 * the following possible cases to deal with. We iterate through
213 * the rest of the tree to make sure none of the required properties
216 * 1) The uncle is red. We repaint both the parent and uncle black
217 * and repaint the grandparent node red.
219 * 2) The uncle is black and the new node is the right child of its
220 * parent, and the parent in turn is the left child of its parent.
221 * We do a left rotation to switch the roles of the parent and
222 * child, relying on further iterations to fixup the old parent.
224 * 3) The uncle is black and the new node is the left child of its
225 * parent, and the parent in turn is the left child of its parent.
226 * We switch the colors of the parent and grandparent and perform
227 * a right rotation around the grandparent. This makes the former
228 * parent the parent of the new node and the former grandparent.
230 * Note that because we use a sentinel for the root node we never
231 * need to worry about replacing the root.
233 while (node->parent->color == red) {
234 struct rbnode *uncle;
235 if (node->parent == node->parent->parent->left) {
236 uncle = node->parent->parent->right;
237 if (uncle->color == red) {
238 node->parent->color = black;
239 uncle->color = black;
240 node->parent->parent->color = red;
241 node = node->parent->parent;
242 } else /* if (uncle->color == black) */ {
243 if (node == node->parent->right) {
245 rotate_left(tree, node);
247 node->parent->color = black;
248 node->parent->parent->color = red;
249 rotate_right(tree, node->parent->parent);
251 } else { /* if (node->parent == node->parent->parent->right) */
252 uncle = node->parent->parent->left;
253 if (uncle->color == red) {
254 node->parent->color = black;
255 uncle->color = black;
256 node->parent->parent->color = red;
257 node = node->parent->parent;
258 } else /* if (uncle->color == black) */ {
259 if (node == node->parent->left) {
261 rotate_right(tree, node);
263 node->parent->color = black;
264 node->parent->parent->color = red;
265 rotate_left(tree, node->parent->parent);
269 rbfirst(tree)->color = black; /* first node is always black */
274 * Look for a node matching key in tree.
275 * Returns a pointer to the node if found, else NULL.
278 rbfind(struct rbtree *tree, void *key)
280 struct rbnode *node = rbfirst(tree);
282 debug_decl(rbfind, SUDOERS_DEBUG_RBTREE)
284 while (node != rbnil(tree)) {
285 if ((res = tree->compar(key, node->data)) == 0)
286 debug_return_ptr(node);
287 node = res < 0 ? node->left : node->right;
289 debug_return_ptr(NULL);
293 * Call func() for each node, passing it the node data and a cookie;
294 * If func() returns non-zero for a node, the traversal stops and the
295 * error value is returned. Returns 0 on successful traversal.
298 rbapply_node(struct rbtree *tree, struct rbnode *node,
299 int (*func)(void *, void *), void *cookie, enum rbtraversal order)
302 debug_decl(rbapply_node, SUDOERS_DEBUG_RBTREE)
304 if (node != rbnil(tree)) {
305 if (order == preorder)
306 if ((error = func(node->data, cookie)) != 0)
307 debug_return_int(error);
308 if ((error = rbapply_node(tree, node->left, func, cookie, order)) != 0)
309 debug_return_int(error);
310 if (order == inorder)
311 if ((error = func(node->data, cookie)) != 0)
312 debug_return_int(error);
313 if ((error = rbapply_node(tree, node->right, func, cookie, order)) != 0)
314 debug_return_int(error);
315 if (order == postorder)
316 if ((error = func(node->data, cookie)) != 0)
317 debug_return_int(error);
323 * Returns the successor of node, or nil if there is none.
325 static struct rbnode *
326 rbsuccessor(struct rbtree *tree, struct rbnode *node)
329 debug_decl(rbsuccessor, SUDOERS_DEBUG_RBTREE)
331 if ((succ = node->right) != rbnil(tree)) {
332 while (succ->left != rbnil(tree))
335 /* No right child, move up until we find it or hit the root */
336 for (succ = node->parent; node == succ->right; succ = succ->parent)
338 if (succ == rbroot(tree))
341 debug_return_ptr(succ);
345 * Recursive portion of rbdestroy().
348 rbdestroy_int(struct rbtree *tree, struct rbnode *node, void (*destroy)(void *))
350 debug_decl(rbdestroy_int, SUDOERS_DEBUG_RBTREE)
351 if (node != rbnil(tree)) {
352 rbdestroy_int(tree, node->left, destroy);
353 rbdestroy_int(tree, node->right, destroy);
362 * Destroy the specified tree, calling the destructor "destroy"
363 * for each node and then freeing the tree itself.
366 rbdestroy(struct rbtree *tree, void (*destroy)(void *))
368 debug_decl(rbdestroy, SUDOERS_DEBUG_RBTREE)
369 rbdestroy_int(tree, rbfirst(tree), destroy);
375 * Delete node 'z' from the tree and return its data pointer.
377 void *rbdelete(struct rbtree *tree, struct rbnode *z)
379 struct rbnode *x, *y;
380 void *data = z->data;
381 debug_decl(rbdelete, SUDOERS_DEBUG_RBTREE)
383 if (z->left == rbnil(tree) || z->right == rbnil(tree))
386 y = rbsuccessor(tree, z);
387 x = (y->left == rbnil(tree)) ? y->right : y->left;
389 if ((x->parent = y->parent) == rbroot(tree)) {
392 if (y == y->parent->left)
395 y->parent->right = x;
397 if (y->color == black)
402 y->parent = z->parent;
404 z->left->parent = z->right->parent = y;
405 if (z == z->parent->left)
408 z->parent->right = y;
412 debug_return_ptr(data);
416 * Repair the tree after a node has been deleted by rotating and repainting
417 * colors to restore the 4 properties inherent in red-black trees.
420 rbrepair(struct rbtree *tree, struct rbnode *node)
422 struct rbnode *sibling;
423 debug_decl(rbrepair, SUDOERS_DEBUG_RBTREE)
425 while (node->color == black && node != rbfirst(tree)) {
426 if (node == node->parent->left) {
427 sibling = node->parent->right;
428 if (sibling->color == red) {
429 sibling->color = black;
430 node->parent->color = red;
431 rotate_left(tree, node->parent);
432 sibling = node->parent->right;
434 if (sibling->right->color == black && sibling->left->color == black) {
435 sibling->color = red;
438 if (sibling->right->color == black) {
439 sibling->left->color = black;
440 sibling->color = red;
441 rotate_right(tree, sibling);
442 sibling = node->parent->right;
444 sibling->color = node->parent->color;
445 node->parent->color = black;
446 sibling->right->color = black;
447 rotate_left(tree, node->parent);
448 node = rbfirst(tree); /* exit loop */
450 } else { /* if (node == node->parent->right) */
451 sibling = node->parent->left;
452 if (sibling->color == red) {
453 sibling->color = black;
454 node->parent->color = red;
455 rotate_right(tree, node->parent);
456 sibling = node->parent->left;
458 if (sibling->right->color == black && sibling->left->color == black) {
459 sibling->color = red;
462 if (sibling->left->color == black) {
463 sibling->right->color = black;
464 sibling->color = red;
465 rotate_left(tree, sibling);
466 sibling = node->parent->left;
468 sibling->color = node->parent->color;
469 node->parent->color = black;
470 sibling->left->color = black;
471 rotate_right(tree, node->parent);
472 node = rbfirst(tree); /* exit loop */