]> git.ipfire.org Git - pakfire.git/commitdiff
cli: progressbar: Fix integer underflow
authorMichael Tremer <michael.tremer@ipfire.org>
Wed, 8 Jan 2025 16:16:42 +0000 (16:16 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Wed, 8 Jan 2025 16:16:42 +0000 (16:16 +0000)
It could happen that we required more space than had and then the
expandable part of the progressbar became negative.

Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/cli/lib/progressbar.c

index 54c84ce45edfef338b4598dccc9fdeeb2779b930..cb534ef9bcb7329d0536139badb92c28acbab2e8 100644 (file)
@@ -149,7 +149,7 @@ static int cli_progressbar_draw(struct cli_progressbar* p) {
        if (r)
                return r;
 
-       unsigned int cols_left = cols - p->num_widgets - 2;
+       int cols_left = cols - p->num_widgets - 2;
 
        // Count how many widgets we have processed
        unsigned int widgets = 0;
@@ -169,18 +169,21 @@ static int cli_progressbar_draw(struct cli_progressbar* p) {
                }
        }
 
-       // How many expandable widgets are left?
-       int num_expandables = p->num_widgets - widgets;
-
-       // How much space do we allocate to each of them?
-       int width = cols_left / num_expandables;
-
-       // Process all expandable widgets
-       STAILQ_FOREACH(widget, &p->widgets, nodes) {
-               if (widget->expandable) {
-                       r = widget->print(p, widget, width, widget->data);
-                       if (r < 0)
-                               return r;
+       // Print the expendable stuff only if there is space left
+       if (cols_left > 0) {
+               // How many expandable widgets are left?
+               int num_expandables = p->num_widgets - widgets;
+
+               // How much space do we allocate to each of them?
+               int width = cols_left / num_expandables;
+
+               // Process all expandable widgets
+               STAILQ_FOREACH(widget, &p->widgets, nodes) {
+                       if (widget->expandable) {
+                               r = widget->print(p, widget, width, widget->data);
+                               if (r < 0)
+                                       return r;
+                       }
                }
        }
 
@@ -350,6 +353,10 @@ static int cli_progressbar_add_percentage(struct cli_progressbar* p) {
 
 static ssize_t cli_progressbar_bar(struct cli_progressbar* p,
                struct cli_progressbar_widget* widget, unsigned int width, void* data) {
+       // This only works if we have at least one byte to fill
+       if (!width)
+               return -ENOBUFS;
+
        // Allocate or adjust the buffer
        widget->buffer = pakfire_realloc(widget->buffer, width + 1);