Bug Summary

File:src/usr.bin/units/units.c
Warning:line 569, column 12
Null pointer passed as 1st argument to string comparison function

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.4 -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name units.c -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model pic -pic-level 1 -pic-is-pie -mframe-pointer=all -relaxed-aliasing -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -target-feature +retpoline-indirect-calls -target-feature +retpoline-indirect-branches -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/usr.bin/units/obj -resource-dir /usr/local/llvm16/lib/clang/16 -internal-isystem /usr/local/llvm16/lib/clang/16/include -internal-externc-isystem /usr/include -O2 -fdebug-compilation-dir=/usr/src/usr.bin/units/obj -ferror-limit 19 -fwrapv -D_RET_PROTECTOR -ret-protector -fcf-protection=branch -fno-jump-tables -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/scan/2024-01-11-140451-98009-1 -x c /usr/src/usr.bin/units/units.c
1/* $OpenBSD: units.c,v 1.23 2022/12/26 18:52:10 florian Exp $ */
2/* $NetBSD: units.c,v 1.6 1996/04/06 06:01:03 thorpej Exp $ */
3
4/*
5 * units.c Copyright (c) 1993 by Adrian Mariano (adrian@cam.cornell.edu)
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. The name of the author may not be used to endorse or promote products
13 * derived from this software without specific prior written permission.
14 * Disclaimer: This software is provided by the author "as is". The author
15 * shall not be liable for any damages caused in any way by this software.
16 *
17 * I would appreciate (though I do not require) receiving a copy of any
18 * improvements you might make to this program.
19 */
20
21#include <ctype.h>
22#include <stdio.h>
23#include <string.h>
24#include <stdlib.h>
25#include <unistd.h>
26#include <err.h>
27
28#define UNITSFILE"/usr/share/misc/units.lib" "/usr/share/misc/units.lib"
29
30#define VERSION"1.0" "1.0"
31
32#define MAXUNITS1000 1000
33#define MAXPREFIXES100 100
34
35#define MAXSUBUNITS500 500
36
37#define PRIMITIVECHAR'!' '!'
38
39char *powerstring = "^";
40
41struct {
42 char *uname;
43 char *uval;
44} unittable[MAXUNITS1000];
45
46struct unittype {
47 char *numerator[MAXSUBUNITS500];
48 char *denominator[MAXSUBUNITS500];
49 double factor;
50};
51
52struct {
53 char *prefixname;
54 char *prefixval;
55} prefixtable[MAXPREFIXES100];
56
57
58char *NULLUNIT = "";
59
60int unitcount;
61int prefixcount;
62
63char *dupstr(char *);
64void readunits(char *);
65void initializeunit(struct unittype *);
66int addsubunit(char *[], char *);
67void showunit(struct unittype *);
68void zeroerror(void);
69int addunit(struct unittype *, char *, int);
70int compare(const void *, const void *);
71void sortunit(struct unittype *);
72void cancelunit(struct unittype *);
73char *lookupunit(char *);
74int reduceproduct(struct unittype *, int);
75int reduceunit(struct unittype *);
76int compareproducts(char **, char **);
77int compareunits(struct unittype *, struct unittype *);
78int completereduce(struct unittype *);
79void showanswer(struct unittype *, struct unittype *);
80void usage(void);
81
82char *
83dupstr(char *str)
84{
85 char *ret;
86
87 ret = strdup(str);
88 if (!ret) {
89 fprintf(stderr(&__sF[2]), "Memory allocation error\n");
90 exit(3);
91 }
92 return (ret);
93}
94
95
96void
97readunits(char *userfile)
98{
99 char line[512], *lineptr;
100 int len, linenum, i;
101 FILE *unitfile;
102
103 linenum = 0;
104
105 if (userfile) {
106 unitfile = fopen(userfile, "r");
107 if (!unitfile) {
108 fprintf(stderr(&__sF[2]), "Unable to open units file '%s'\n",
109 userfile);
110 exit(1);
111 }
112 } else {
113 unitfile = fopen(UNITSFILE"/usr/share/misc/units.lib", "r");
114 if (!unitfile) {
115 fprintf(stderr(&__sF[2]), "Can't find units file '%s'\n",
116 UNITSFILE"/usr/share/misc/units.lib");
117 exit(1);
118 }
119 }
120 while (!feof(unitfile)(!__isthreaded ? (((unitfile)->_flags & 0x0020) != 0) :
(feof)(unitfile))
) {
121 if (!fgets(line, sizeof(line), unitfile))
122 break;
123 linenum++;
124 lineptr = line;
125 if (*lineptr == '/')
126 continue;
127 lineptr += strspn(lineptr, " \n\t");
128 len = strcspn(lineptr, " \n\t");
129 lineptr[len] = 0;
130 if (!strlen(lineptr))
131 continue;
132 if (lineptr[strlen(lineptr) - 1] == '-') { /* it's a prefix */
133 if (prefixcount == MAXPREFIXES100) {
134 fprintf(stderr(&__sF[2]),
135 "Memory for prefixes exceeded in line %d\n",
136 linenum);
137 continue;
138 }
139
140 lineptr[strlen(lineptr) - 1] = 0;
141 for (i = 0; i < prefixcount; i++) {
142 if (!strcmp(prefixtable[i].prefixname, lineptr))
143 break;
144 }
145 if (i < prefixcount) {
146 fprintf(stderr(&__sF[2]), "Redefinition of prefix '%s' "
147 "on line %d ignored\n", lineptr, linenum);
148 continue; /* skip duplicate prefix */
149 }
150
151 prefixtable[prefixcount].prefixname = dupstr(lineptr);
152 lineptr += len + 1;
153 lineptr += strspn(lineptr, " \n\t");
154 len = strcspn(lineptr, "\n\t");
155 if (len == 0) {
156 fprintf(stderr(&__sF[2]), "Unexpected end of prefix on "
157 "line %d\n", linenum);
158 free(prefixtable[prefixcount].prefixname);
159 continue;
160 }
161 lineptr[len] = 0;
162 prefixtable[prefixcount++].prefixval = dupstr(lineptr);
163 } else { /* it's not a prefix */
164 if (unitcount == MAXUNITS1000) {
165 fprintf(stderr(&__sF[2]),
166 "Memory for units exceeded in line %d\n",
167 linenum);
168 continue;
169 }
170
171 for (i = 0; i < unitcount; i++) {
172 if (!strcmp(unittable[i].uname, lineptr))
173 break;
174 }
175 if (i < unitcount) {
176 fprintf(stderr(&__sF[2]), "Redefinition of unit '%s' "
177 "on line %d ignored\n", lineptr, linenum);
178 continue; /* skip duplicate unit */
179 }
180
181 unittable[unitcount].uname = dupstr(lineptr);
182 lineptr += len + 1;
183 lineptr += strspn(lineptr, " \n\t");
184 if (!strlen(lineptr)) {
185 fprintf(stderr(&__sF[2]), "Unexpected end of unit on "
186 "line %d\n", linenum);
187 free(unittable[unitcount].uname);
188 continue;
189 }
190 len = strcspn(lineptr, "\n\t");
191 lineptr[len] = 0;
192 unittable[unitcount++].uval = dupstr(lineptr);
193 }
194 }
195 fclose(unitfile);
196}
197
198void
199initializeunit(struct unittype *theunit)
200{
201 theunit->factor = 1.0;
202 theunit->numerator[0] = theunit->denominator[0] = NULL((void *)0);
203}
204
205
206int
207addsubunit(char *product[], char *toadd)
208{
209 char **ptr;
210
211 for (ptr = product; *ptr && *ptr != NULLUNIT; ptr++);
212 if (ptr >= product + MAXSUBUNITS500) {
213 fprintf(stderr(&__sF[2]), "Memory overflow in unit reduction\n");
214 return 1;
215 }
216 if (!*ptr)
217 *(ptr + 1) = 0;
218 *ptr = dupstr(toadd);
219 return 0;
220}
221
222
223void
224showunit(struct unittype *theunit)
225{
226 char **ptr;
227 int printedslash;
228 int counter = 1;
229
230 printf("\t%.8g", theunit->factor);
231 for (ptr = theunit->numerator; *ptr; ptr++) {
232 if (ptr > theunit->numerator && **ptr &&
233 !strcmp(*ptr, *(ptr - 1)))
234 counter++;
235 else {
236 if (counter > 1)
237 printf("%s%d", powerstring, counter);
238 if (**ptr)
239 printf(" %s", *ptr);
240 counter = 1;
241 }
242 }
243 if (counter > 1)
244 printf("%s%d", powerstring, counter);
245 counter = 1;
246 printedslash = 0;
247 for (ptr = theunit->denominator; *ptr; ptr++) {
248 if (ptr > theunit->denominator && **ptr &&
249 !strcmp(*ptr, *(ptr - 1)))
250 counter++;
251 else {
252 if (counter > 1)
253 printf("%s%d", powerstring, counter);
254 if (**ptr) {
255 if (!printedslash)
256 printf(" /");
257 printedslash = 1;
258 printf(" %s", *ptr);
259 }
260 counter = 1;
261 }
262 }
263 if (counter > 1)
264 printf("%s%d", powerstring, counter);
265 printf("\n");
266}
267
268
269void
270zeroerror(void)
271{
272 fprintf(stderr(&__sF[2]), "Unit reduces to zero\n");
273}
274
275/*
276 Adds the specified string to the unit.
277 Flip is 0 for adding normally, 1 for adding reciprocal.
278
279 Returns 0 for successful addition, nonzero on error.
280*/
281
282int
283addunit(struct unittype *theunit, char *toadd, int flip)
284{
285 char *scratch, *savescr;
286 char *item;
287 char *divider, *slash;
288 int doingtop;
289
290 savescr = scratch = dupstr(toadd);
291 for (slash = scratch + 1; *slash; slash++)
15
Loop condition is false. Execution continues on line 296
292 if (*slash == '-' &&
293 (tolower((unsigned char)*(slash - 1)) != 'e' ||
294 !strchr(".0123456789", *(slash + 1))))
295 *slash = ' ';
296 slash = strchr(scratch, '/');
297 if (slash)
16
Assuming 'slash' is null
17
Taking false branch
298 *slash = 0;
299 doingtop = 1;
300 do {
20
Loop condition is false. Exiting loop
301 item = strtok(scratch, " *\t\n/");
302 while (item) {
18
Loop condition is false. Execution continues on line 360
303 if (strchr("0123456789.", *item)) { /* item is a number */
304 double num;
305
306 divider = strchr(item, '|');
307 if (divider) {
308 *divider = 0;
309 num = atof(item);
310 if (!num) {
311 zeroerror();
312 free(savescr);
313 return 1;
314 }
315 if (doingtop ^ flip)
316 theunit->factor *= num;
317 else
318 theunit->factor /= num;
319 num = atof(divider + 1);
320 if (!num) {
321 zeroerror();
322 free(savescr);
323 return 1;
324 }
325 if (doingtop ^ flip)
326 theunit->factor /= num;
327 else
328 theunit->factor *= num;
329 } else {
330 num = atof(item);
331 if (!num) {
332 zeroerror();
333 free(savescr);
334 return 1;
335 }
336 if (doingtop ^ flip)
337 theunit->factor *= num;
338 else
339 theunit->factor /= num;
340
341 }
342 } else { /* item is not a number */
343 int repeat = 1;
344
345 if (strchr("23456789",
346 item[strlen(item) - 1])) {
347 repeat = item[strlen(item) - 1] - '0';
348 item[strlen(item) - 1] = 0;
349 }
350 for (; repeat; repeat--)
351 if (addsubunit(doingtop ^ flip
352 ? theunit->numerator
353 : theunit->denominator, item)) {
354 free(savescr);
355 return 1;
356 }
357 }
358 item = strtok(NULL((void *)0), " *\t/\n");
359 }
360 doingtop--;
361 if (slash
18.1
'slash' is null
) {
19
Taking false branch
362 scratch = slash + 1;
363 } else
364 doingtop--;
365 } while (doingtop >= 0);
366 free(savescr);
367 return 0;
368}
369
370
371int
372compare(const void *item1, const void *item2)
373{
374 return strcmp(*(char **) item1, *(char **) item2);
375}
376
377
378void
379sortunit(struct unittype *theunit)
380{
381 char **ptr;
382 int count;
383
384 for (count = 0, ptr = theunit->numerator; *ptr; ptr++, count++);
38
Loop condition is false. Execution continues on line 385
385 qsort(theunit->numerator, count, sizeof(char *), compare);
386 for (count = 0, ptr = theunit->denominator; *ptr; ptr++, count++);
39
Loop condition is false. Execution continues on line 387
387 qsort(theunit->denominator, count, sizeof(char *), compare);
40
Assigning value
388}
389
390
391void
392cancelunit(struct unittype *theunit)
393{
394 char **den, **num;
395 int comp;
396
397 den = theunit->denominator;
398 num = theunit->numerator;
399
400 while (*num && *den) {
43
Assuming pointer value is null
401 comp = strcmp(*den, *num);
402 if (!comp) {
403 *den++ = NULLUNIT;
404 *num++ = NULLUNIT;
405 } else if (comp < 0)
406 den++;
407 else
408 num++;
409 }
410}
411
412
413
414
415/*
416 Looks up the definition for the specified unit.
417 Returns a pointer to the definition or a null pointer
418 if the specified unit does not appear in the units table.
419*/
420
421static char buffer[500]; /* buffer for lookupunit answers with
422 prefixes */
423
424char *
425lookupunit(char *unit)
426{
427 size_t len;
428 int i;
429 char *copy;
430
431 for (i = 0; i < unitcount; i++) {
432 if (!strcmp(unittable[i].uname, unit))
433 return unittable[i].uval;
434 }
435
436 len = strlen(unit);
437 if (len == 0)
438 return NULL((void *)0);
439 if (unit[len - 1] == '^') {
440 copy = dupstr(unit);
441 copy[len - 1] = '\0';
442 for (i = 0; i < unitcount; i++) {
443 if (!strcmp(unittable[i].uname, copy)) {
444 strlcpy(buffer, copy, sizeof(buffer));
445 free(copy);
446 return buffer;
447 }
448 }
449 free(copy);
450 }
451 if (unit[len - 1] == 's') {
452 copy = dupstr(unit);
453 copy[len - 1] = '\0';
454 --len;
455 for (i = 0; i < unitcount; i++) {
456 if (!strcmp(unittable[i].uname, copy)) {
457 strlcpy(buffer, copy, sizeof(buffer));
458 free(copy);
459 return buffer;
460 }
461 }
462 if (len != 0 && copy[len - 1] == 'e') {
463 copy[len - 1] = 0;
464 for (i = 0; i < unitcount; i++) {
465 if (!strcmp(unittable[i].uname, copy)) {
466 strlcpy(buffer, copy, sizeof(buffer));
467 free(copy);
468 return buffer;
469 }
470 }
471 }
472 free(copy);
473 }
474 for (i = 0; i < prefixcount; i++) {
475 len = strlen(prefixtable[i].prefixname);
476 if (!strncmp(prefixtable[i].prefixname, unit, len)) {
477 if (!strlen(unit + len) || lookupunit(unit + len)) {
478 snprintf(buffer, sizeof(buffer), "%s %s",
479 prefixtable[i].prefixval, unit + len);
480 return buffer;
481 }
482 }
483 }
484 return NULL((void *)0);
485}
486
487
488
489/*
490 reduces a product of symbolic units to primitive units.
491 The three low bits are used to return flags:
492
493 bit 0 (1) set on if reductions were performed without error.
494 bit 1 (2) set on if no reductions are performed.
495 bit 2 (4) set on if an unknown unit is discovered.
496*/
497
498
499#define ERROR4 4
500
501int
502reduceproduct(struct unittype *theunit, int flip)
503{
504 char *toadd, **product;
505 int didsomething = 2;
506
507 if (flip
25.1
'flip' is 0
29.1
'flip' is 1
)
26
Taking false branch
30
Taking true branch
508 product = theunit->denominator;
509 else
510 product = theunit->numerator;
511
512 for (; *product; product++) {
27
Loop condition is false. Execution continues on line 533
31
Loop condition is false. Execution continues on line 533
513
514 for (;;) {
515 if (!strlen(*product))
516 break;
517 toadd = lookupunit(*product);
518 if (!toadd) {
519 printf("unknown unit '%s'\n", *product);
520 return ERROR4;
521 }
522 if (strchr(toadd, PRIMITIVECHAR'!'))
523 break;
524 didsomething = 1;
525 if (*product != NULLUNIT) {
526 free(*product);
527 *product = NULLUNIT;
528 }
529 if (addunit(theunit, toadd, flip))
530 return ERROR4;
531 }
532 }
533 return didsomething;
534}
535
536
537/*
538 Reduces numerator and denominator of the specified unit.
539 Returns 0 on success, or 1 on unknown unit error.
540*/
541
542int
543reduceunit(struct unittype *theunit)
544{
545 int ret;
546
547 ret = 1;
548 while (ret & 1) {
24
Loop condition is true. Entering loop body
34
Loop condition is false. Execution continues on line 553
549 ret = reduceproduct(theunit, 0) | reduceproduct(theunit, 1);
25
Calling 'reduceproduct'
28
Returning from 'reduceproduct'
29
Calling 'reduceproduct'
32
Returning from 'reduceproduct'
550 if (ret & 4)
33
Taking false branch
551 return 1;
552 }
553 return 0;
554}
555
556
557int
558compareproducts(char **one, char **two)
559{
560 while (*one || *two) {
561 if (!*one && *two != NULLUNIT)
49
Assuming the condition is false
562 return 1;
563 if (!*two && *one != NULLUNIT)
564 return 1;
565 if (*one == NULLUNIT)
50
Taking false branch
566 one++;
567 else if (*two == NULLUNIT)
51
Assuming the condition is false
52
Taking false branch
568 two++;
569 else if (strcmp(*one, *two))
53
Null pointer passed as 1st argument to string comparison function
570 return 1;
571 else
572 one++, two++;
573 }
574 return 0;
575}
576
577
578/* Return zero if units are compatible, nonzero otherwise */
579
580int
581compareunits(struct unittype *first, struct unittype *second)
582{
583 return compareproducts(first->numerator, second->numerator) ||
48
Calling 'compareproducts'
584 compareproducts(first->denominator, second->denominator);
585}
586
587
588int
589completereduce(struct unittype *unit)
590{
591 if (reduceunit(unit))
23
Calling 'reduceunit'
35
Returning from 'reduceunit'
36
Taking false branch
592 return 1;
593 sortunit(unit);
37
Calling 'sortunit'
41
Returning from 'sortunit'
594 cancelunit(unit);
42
Calling 'cancelunit'
44
Returning from 'cancelunit'
595 return 0;
596}
597
598
599void
600showanswer(struct unittype *have, struct unittype *want)
601{
602 if (compareunits(have, want)) {
47
Calling 'compareunits'
603 printf("conformability error\n");
604 showunit(have);
605 showunit(want);
606 } else
607 printf("\t* %.8g\n\t/ %.8g\n", have->factor / want->factor,
608 want->factor / have->factor);
609}
610
611
612void
613usage(void)
614{
615 fprintf(stderr(&__sF[2]),
616 "usage: units [-qv] [-f filename] [[count] from-unit to-unit]\n");
617 exit(3);
618}
619
620
621int
622main(int argc, char **argv)
623{
624
625 struct unittype have, want;
626 char havestr[81], wantstr[81];
627 int optchar;
628 int quiet = 0, units_read = 0;
629
630 extern char *optarg;
631 extern int optind;
632
633 if (pledge("stdio rpath", NULL((void *)0)) == -1)
1
Assuming the condition is false
2
Taking false branch
634 err(1, "pledge");
635
636 while ((optchar = getopt(argc, argv, "vqf:")) != -1) {
3
Assuming the condition is false
4
Loop condition is false. Execution continues on line 658
637 switch (optchar) {
638 case 'f':
639 units_read = 1;
640 readunits(*optarg == '\0' ? NULL((void *)0) : optarg);
641 break;
642 case 'q':
643 quiet = 1;
644 break;
645 case 'v':
646 fprintf(stderr(&__sF[2]),
647 "units version %s Copyright (c) 1993 by Adrian Mariano\n",
648 VERSION"1.0");
649 fprintf(stderr(&__sF[2]),
650 "This program may be freely distributed\n");
651 usage();
652 default:
653 usage();
654 break;
655 }
656 }
657
658 argc -= optind;
659 argv += optind;
660
661 if (argc != 3 && argc != 2 && argc != 0)
5
Assuming 'argc' is not equal to 3
6
Assuming 'argc' is equal to 2
662 usage();
663
664 if (!units_read
6.1
'units_read' is 0
)
7
Taking true branch
665 readunits(NULL((void *)0));
666
667 if (pledge("stdio", NULL((void *)0)) == -1)
8
Assuming the condition is false
9
Taking false branch
668 err(1, "pledge");
669
670 if (argc
9.1
'argc' is not equal to 3
== 3) {
10
Taking false branch
671 strlcpy(havestr, argv[0], sizeof(havestr));
672 strlcat(havestr, " ", sizeof(havestr));
673 strlcat(havestr, argv[1], sizeof(havestr));
674 argc--;
675 argv++;
676 argv[0] = havestr;
677 }
678
679 if (argc
10.1
'argc' is equal to 2
== 2) {
11
Taking true branch
680 strlcpy(havestr, argv[0], sizeof(havestr));
681 strlcpy(wantstr, argv[1], sizeof(wantstr));
682 initializeunit(&have);
12
Calling 'initializeunit'
13
Returning from 'initializeunit'
683 addunit(&have, havestr, 0);
14
Calling 'addunit'
21
Returning from 'addunit'
684 completereduce(&have);
22
Calling 'completereduce'
45
Returning from 'completereduce'
685 initializeunit(&want);
686 addunit(&want, wantstr, 0);
687 completereduce(&want);
688 showanswer(&have, &want);
46
Calling 'showanswer'
689 } else {
690 if (!quiet)
691 printf("%d units, %d prefixes\n", unitcount,
692 prefixcount);
693 for (;;) {
694 do {
695 initializeunit(&have);
696 if (!quiet)
697 printf("You have: ");
698 if (!fgets(havestr, sizeof(havestr), stdin(&__sF[0]))) {
699 if (!quiet)
700 putchar('\n')(!__isthreaded ? __sputc('\n', (&__sF[1])) : (putc)('\n',
(&__sF[1])))
;
701 exit(0);
702 }
703 } while (addunit(&have, havestr, 0) ||
704 completereduce(&have));
705 do {
706 initializeunit(&want);
707 if (!quiet)
708 printf("You want: ");
709 if (!fgets(wantstr, sizeof(wantstr), stdin(&__sF[0]))) {
710 if (!quiet)
711 putchar('\n')(!__isthreaded ? __sputc('\n', (&__sF[1])) : (putc)('\n',
(&__sF[1])))
;
712 exit(0);
713 }
714 } while (addunit(&want, wantstr, 0) ||
715 completereduce(&want));
716 showanswer(&have, &want);
717 }
718 }
719 return (0);
720}