Use ASan and UBSan in debug builds.
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8 #include <editline/readline.h>
9
10 #include "advent.h"
11 #include "dungeon.h"
12
13 static void* xmalloc(size_t size)
14 {
15     void* ptr = malloc(size);
16     if (ptr == NULL) {
17         // LCOV_EXCL_START
18         // exclude from coverage analysis because we can't simulate an out of memory error in testing
19         fprintf(stderr, "Out of memory!\n");
20         exit(EXIT_FAILURE);
21         // LCOV_EXCL_STOP
22     }
23     return (ptr);
24 }
25
26 void packed_to_token(long packed, char token[TOKLEN + 1])
27 {
28     // The advent->ascii mapping.
29     const char advent_to_ascii[] = {
30         ' ', '!', '"', '#', '$', '%', '&', '\'',
31         '(', ')', '*', '+', ',', '-', '.', '/',
32         '0', '1', '2', '3', '4', '5', '6', '7',
33         '8', '9', ':', ';', '<', '=', '>', '?',
34         '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
35         'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
36         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
37         'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
38     };
39
40     // Unpack and map back to ASCII.
41     for (int i = 0; i < 5; ++i) {
42         char advent = (packed >> i * 6) & 63;
43         token[i] = advent_to_ascii[(int) advent];
44     }
45
46     // Ensure the last character is \0.
47     token[5] = '\0';
48
49     // Replace trailing whitespace with \0.
50     for (int i = 4; i >= 0; --i) {
51         if (token[i] == ' ' ||
52             token[i] == '\t')
53             token[i] = '\0';
54         else
55             break;
56     }
57 }
58
59 long token_to_packed(const char token[])
60 {
61     const char ascii_to_advent[] = {
62         63, 63, 63, 63, 63, 63, 63, 63,
63         63, 63, 63, 63, 63, 63, 63, 63,
64         63, 63, 63, 63, 63, 63, 63, 63,
65         63, 63, 63, 63, 63, 63, 63, 63,
66
67         0, 1, 2, 3, 4, 5, 6, 7,
68         8, 9, 10, 11, 12, 13, 14, 15,
69         16, 17, 18, 19, 20, 21, 22, 23,
70         24, 25, 26, 27, 28, 29, 30, 31,
71         32, 33, 34, 35, 36, 37, 38, 39,
72         40, 41, 42, 43, 44, 45, 46, 47,
73         48, 49, 50, 51, 52, 53, 54, 55,
74         56, 57, 58, 59, 60, 61, 62, 63,
75
76         63, 63, 63, 63, 63, 63, 63, 63,
77         63, 63, 63, 63, 63, 63, 63, 63,
78         63, 63, 63, 63, 63, 63, 63, 63,
79         63, 63, 63, 63, 63, 63, 63, 63,
80     };
81
82     size_t t_len = strlen(token);
83     if (t_len > TOKLEN)
84         t_len = TOKLEN;
85     long packed = 0;
86     for (size_t i = 0; i < t_len; ++i) {
87         char mapped = ascii_to_advent[(int) toupper(token[i])];
88         packed |= (mapped << (6 * i));
89     }
90     return (packed);
91 }
92
93 void tokenize(char* raw, struct command_t *cmd)
94 {
95     memset(cmd, '\0', sizeof(struct command_t));
96
97     /* Bound prefix on the %s would be needed to prevent buffer
98      * overflow.  but we shortstop this more simply by making each
99      * raw-input buffer as long as the enrire inout buffer. */
100     sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
101
102     // pack the substrings
103     cmd->wd1  = token_to_packed(cmd->raw1);
104     cmd->wd2  = token_to_packed(cmd->raw2);
105
106     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
107      * effect on raw tokens of packing them into sixbit characters, 5
108      * to a 32-bit word.  This is something the FORTRAN version did
109      * becuse archaic FORTRAN had no string types.  Don Wood's
110      * mechanical translation of 2.5 to C retained the packing and
111      * thus this misfeature.
112      *
113      * It's philosophically questionable whether this is the right
114      * thing to do even in oldstyle mode.  On one hand, the text
115      * mangling was not authorial intent, but a result of limitations
116      * in their tools. On the other, not simulating this misbehavior
117      * goes against the goal of making oldstyle as accurate as
118      * possible an emulation of the original UI.
119      */
120     if (settings.oldstyle) {
121         cmd->raw1[TOKLEN + TOKLEN] = cmd->raw2[TOKLEN + TOKLEN] = '\0';
122         for (size_t i = 0; i < strlen(cmd->raw1); i++)
123             cmd->raw1[i] = toupper(cmd->raw1[i]);
124         for (size_t i = 0; i < strlen(cmd->raw2); i++)
125             cmd->raw2[i] = toupper(cmd->raw2[i]);
126     }
127 }
128
129 /* Hide the fact that wods are corrently packed longs */
130
131 void wordclear(token_t *v)
132 {
133     *v = 0;
134 }
135
136 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
137
138 static void vspeak(const char* msg, bool blank, va_list ap)
139 {
140     // Do nothing if we got a null pointer.
141     if (msg == NULL)
142         return;
143
144     // Do nothing if we got an empty string.
145     if (strlen(msg) == 0)
146         return;
147
148     if (blank == true)
149         printf("\n");
150
151     int msglen = strlen(msg);
152
153     // Rendered string
154     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
155     char* rendered = xmalloc(size);
156     char* renderp = rendered;
157
158     // Handle format specifiers (including the custom %C, %L, %S) by
159     // adjusting the parameter accordingly, and replacing the
160     // specifier with %s.
161     long previous_arg = 0;
162     for (int i = 0; i < msglen; i++) {
163         if (msg[i] != '%') {
164             /* Ugh.  Least obtrusive way to deal with artifacts "on the floor"
165              * being dropped outside of both cave and building. */
166             if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
167                 strcpy(renderp, "ground");
168                 renderp += 6;
169                 i += 4;
170                 size -= 5;
171             } else {
172                 *renderp++ = msg[i];
173                 size--;
174             }
175         } else {
176             long arg = va_arg(ap, long);
177             if (arg == -1)
178                 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
179             i++;
180             // Integer specifier. In order to accommodate the fact
181             // that PARMS can have both legitimate integers *and*
182             // packed tokens, stringify everything. Future work may
183             // eliminate the need for this.
184             if (msg[i] == 'd') {
185                 int ret = snprintf(renderp, size, "%ld", arg);
186                 if (ret < size) {
187                     renderp += ret;
188                     size -= ret;
189                 }
190             }
191
192             // Unmodified string specifier.
193             if (msg[i] == 's') {
194                 packed_to_token(arg, renderp); /* unpack directly to destination */
195                 size_t len = strlen(renderp);
196                 renderp += len;
197                 size -= len;
198             }
199
200             // Singular/plural specifier.
201             if (msg[i] == 'S') {
202                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
203                     *renderp++ = 's';
204                     size--;
205                 }
206             }
207
208             /* Version specifier */
209             if (msg[i] == 'V') {
210                 strcpy(renderp, VERSION);
211                 size_t len = strlen(VERSION);
212                 renderp += len;
213                 size -= len;
214             }
215
216             previous_arg = arg;
217         }
218     }
219     *renderp = 0;
220
221     // Print the message.
222     printf("%s\n", rendered);
223
224     free(rendered);
225 }
226
227 void speak(const char* msg, ...)
228 {
229     va_list ap;
230     va_start(ap, msg);
231     vspeak(msg, true, ap);
232     va_end(ap);
233 }
234
235 void sspeak(const long msg, ...)
236 {
237     va_list ap;
238     va_start(ap, msg);
239     fputc('\n', stdout);
240     vprintf(arbitrary_messages[msg], ap);
241     fputc('\n', stdout);
242     va_end(ap);
243 }
244
245 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
246 /* Find the skip+1st message from msg and print it.  Modes are:
247  * feel = for inventory, what you can touch
248  * look = the long description for the state the object is in
249  * listen = the sound for the state the object is in
250  * study = text on the object. */
251 {
252     va_list ap;
253     va_start(ap, blank);
254     switch (mode) {
255     case touch:
256         vspeak(objects[msg].inventory, blank, ap);
257         break;
258     case look:
259         vspeak(objects[msg].descriptions[skip], blank, ap);
260         break;
261     case hear:
262         vspeak(objects[msg].sounds[skip], blank, ap);
263         break;
264     case study:
265         vspeak(objects[msg].texts[skip], blank, ap);
266         break;
267     case change:
268         vspeak(objects[msg].changes[skip], blank, ap);
269         break;
270     }
271     va_end(ap);
272 }
273
274 void rspeak(vocab_t i, ...)
275 /* Print the i-th "random" message (section 6 of database). */
276 {
277     va_list ap;
278     va_start(ap, i);
279     vspeak(arbitrary_messages[i], true, ap);
280     va_end(ap);
281 }
282
283 void echo_input(FILE* destination, const char* input_prompt, const char* input)
284 {
285     size_t len = strlen(input_prompt) + strlen(input) + 1;
286     char* prompt_and_input = (char*) xmalloc(len);
287     strcpy(prompt_and_input, input_prompt);
288     strcat(prompt_and_input, input);
289     fprintf(destination, "%s\n", prompt_and_input);
290     free(prompt_and_input);
291 }
292
293 int word_count(char* str)
294 {
295     char delims[] = " \t";
296     int count = 0;
297     int inblanks = true;
298
299     for (char *s = str; *s; s++)
300         if (inblanks) {
301             if (strchr(delims, *s) == 0) {
302                 ++count;
303                 inblanks = false;
304             }
305         } else {
306             if (strchr(delims, *s) != 0) {
307                 inblanks = true;
308             }
309         }
310
311     return (count);
312 }
313
314 char* get_input()
315 {
316     // Set up the prompt
317     char input_prompt[] = "> ";
318     if (!settings.prompt)
319         input_prompt[0] = '\0';
320
321     // Print a blank line
322     printf("\n");
323
324     char* input;
325     while (true) {
326         input = readline(input_prompt);
327
328         if (input == NULL) // Got EOF; return with it.
329             return (input);
330         if (input[0] == '#') { // Ignore comments.
331             free(input);
332             continue;
333         }
334         // We have a 'normal' line; leave the loop.
335         break;
336     }
337
338     // Strip trailing newlines from the input
339     input[strcspn(input, "\n")] = 0;
340
341     add_history(input);
342
343     if (!isatty(0))
344         echo_input(stdout, input_prompt, input);
345
346     if (settings.logfp)
347         echo_input(settings.logfp, "", input);
348
349     return (input);
350 }
351
352 bool silent_yes()
353 {
354     bool outcome = false;
355
356     for (;;) {
357         char* reply = get_input();
358         if (reply == NULL) {
359             // LCOV_EXCL_START
360             // Should be unreachable. Reply should never be NULL
361             free(reply);
362             exit(EXIT_SUCCESS);
363             // LCOV_EXCL_STOP
364         }
365         if (strlen(reply) == 0) {
366             free(reply);
367             rspeak(PLEASE_ANSWER);
368             continue;
369         }
370
371         char* firstword = (char*) xmalloc(strlen(reply) + 1);
372         sscanf(reply, "%s", firstword);
373
374         free(reply);
375
376         for (int i = 0; i < (int)strlen(firstword); ++i)
377             firstword[i] = tolower(firstword[i]);
378
379         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
380         int y = strncmp("y", firstword, sizeof("y") - 1);
381         int no = strncmp("no", firstword, sizeof("no") - 1);
382         int n = strncmp("n", firstword, sizeof("n") - 1);
383
384         free(firstword);
385
386         if (yes == 0 ||
387             y == 0) {
388             outcome = true;
389             break;
390         } else if (no == 0 ||
391                    n == 0) {
392             outcome = false;
393             break;
394         } else
395             rspeak(PLEASE_ANSWER);
396     }
397     return (outcome);
398 }
399
400
401 bool yes(const char* question, const char* yes_response, const char* no_response)
402 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
403  *  if no, print Z and return false. */
404 {
405     bool outcome = false;
406
407     for (;;) {
408         speak(question);
409
410         char* reply = get_input();
411         if (reply == NULL) {
412             // LCOV_EXCL_START
413             // Should be unreachable. Reply should never be NULL
414             free(reply);
415             exit(EXIT_SUCCESS);
416             // LCOV_EXCL_STOP
417         }
418
419         if (strlen(reply) == 0) {
420             free(reply);
421             rspeak(PLEASE_ANSWER);
422             continue;
423         }
424
425         char* firstword = (char*) xmalloc(strlen(reply) + 1);
426         sscanf(reply, "%s", firstword);
427
428         free(reply);
429
430         for (int i = 0; i < (int)strlen(firstword); ++i)
431             firstword[i] = tolower(firstword[i]);
432
433         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
434         int y = strncmp("y", firstword, sizeof("y") - 1);
435         int no = strncmp("no", firstword, sizeof("no") - 1);
436         int n = strncmp("n", firstword, sizeof("n") - 1);
437
438         free(firstword);
439
440         if (yes == 0 ||
441             y == 0) {
442             speak(yes_response);
443             outcome = true;
444             break;
445         } else if (no == 0 ||
446                    n == 0) {
447             speak(no_response);
448             outcome = false;
449             break;
450         } else
451             rspeak(PLEASE_ANSWER);
452
453     }
454
455     return (outcome);
456 }
457
458 /*  Data structure  routines */
459
460 int get_motion_vocab_id(const char* word)
461 // Return the first motion number that has 'word' as one of its words.
462 {
463     for (int i = 0; i < NMOTIONS; ++i) {
464         for (int j = 0; j < motions[i].words.n; ++j) {
465             if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
466                     strchr(ignore, word[0]) == NULL ||
467                     !settings.oldstyle))
468                 return (i);
469         }
470     }
471     // If execution reaches here, we didn't find the word.
472     return (WORD_NOT_FOUND);
473 }
474
475 int get_object_vocab_id(const char* word)
476 // Return the first object number that has 'word' as one of its words.
477 {
478     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
479         for (int j = 0; j < objects[i].words.n; ++j) {
480             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
481                 return (i);
482         }
483     }
484     // If execution reaches here, we didn't find the word.
485     return (WORD_NOT_FOUND);
486 }
487
488 int get_action_vocab_id(const char* word)
489 // Return the first motion number that has 'word' as one of its words.
490 {
491     for (int i = 0; i < NACTIONS; ++i) {
492         for (int j = 0; j < actions[i].words.n; ++j) {
493             if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
494                     strchr(ignore, word[0]) == NULL ||
495                     !settings.oldstyle))
496                 return (i);
497         }
498     }
499     // If execution reaches here, we didn't find the word.
500     return (WORD_NOT_FOUND);
501 }
502
503 int get_special_vocab_id(const char* word)
504 // Return the first special number that has 'word' as one of its words.
505 {
506     for (int i = 0; i < NSPECIALS; ++i) {
507         for (int j = 0; j < specials[i].words.n; ++j) {
508             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
509                 return (i);
510         }
511     }
512     // If execution reaches here, we didn't find the word.
513     return (WORD_NOT_FOUND);
514 }
515
516 void get_vocab_metadata(const char* word, long* id, enum wordtype* type)
517 {
518     /* Check for an empty string */
519     if (strncmp(word, "", sizeof("")) == 0) {
520         *id = WORD_EMPTY;
521         *type = NO_WORD_TYPE;
522         return;
523     }
524
525     long ref_num;
526
527     ref_num = get_motion_vocab_id(word);
528     if (ref_num != WORD_NOT_FOUND) {
529         *id = ref_num;
530         *type = MOTION;
531         return;
532     }
533
534     ref_num = get_object_vocab_id(word);
535     if (ref_num != WORD_NOT_FOUND) {
536         *id = ref_num;
537         *type = OBJECT;
538         return;
539     }
540
541     ref_num = get_action_vocab_id(word);
542     if (ref_num != WORD_NOT_FOUND) {
543         *id = ref_num;
544         *type = ACTION;
545         return;
546     }
547
548     ref_num = get_special_vocab_id(word);
549     if (ref_num != WORD_NOT_FOUND) {
550         *id = ref_num;
551         *type = SPECIAL;
552         return;
553     }
554
555     // Check for the reservoir magic word.
556     if (strcasecmp(word, game.zzword) == 0) {
557         *id = PART;
558         *type = ACTION;
559         return;
560     }
561
562     *id = WORD_NOT_FOUND;
563     *type = NO_WORD_TYPE;
564     return;
565 }
566
567 void juggle(obj_t object)
568 /*  Juggle an object by picking it up and putting it down again, the purpose
569  *  being to get the object to the front of the chain of things at its loc. */
570 {
571     loc_t i, j;
572
573     i = game.place[object];
574     j = game.fixed[object];
575     move(object, i);
576     move(object + NOBJECTS, j);
577 }
578
579 void move(obj_t object, loc_t where)
580 /*  Place any object anywhere by picking it up and dropping it.  May
581  *  already be toting, in which case the carry is a no-op.  Mustn't
582  *  pick up objects which are not at any loc, since carry wants to
583  *  remove objects from game.atloc chains. */
584 {
585     long from;
586
587     if (object > NOBJECTS)
588         from = game.fixed[object - NOBJECTS];
589     else
590         from = game.place[object];
591     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
592     if (from != LOC_NOWHERE && from != CARRIED)
593         carry(object, from);
594     drop(object, where);
595 }
596
597 long put(obj_t object, loc_t where, long pval)
598 /*  put() is the same as move(), except it returns a value used to set up the
599  *  negated game.prop values for the repository objects. */
600 {
601     move(object, where);
602     return STASHED(pval);
603 }
604
605 void carry(obj_t object, loc_t where)
606 /*  Start toting an object, removing it from the list of things at its former
607  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
608  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
609 {
610     long temp;
611
612     if (object <= NOBJECTS) {
613         if (game.place[object] == CARRIED)
614             return;
615         game.place[object] = CARRIED;
616         ++game.holdng;
617     }
618     if (game.atloc[where] == object) {
619         game.atloc[where] = game.link[object];
620         return;
621     }
622     temp = game.atloc[where];
623     while (game.link[temp] != object) {
624         temp = game.link[temp];
625     }
626     game.link[temp] = game.link[object];
627 }
628
629 void drop(obj_t object, loc_t where)
630 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
631  *  game.holdng if the object was being toted. */
632 {
633     if (object > NOBJECTS)
634         game.fixed[object - NOBJECTS] = where;
635     else {
636         if (game.place[object] == CARRIED)
637             --game.holdng;
638         game.place[object] = where;
639     }
640     if (where == LOC_NOWHERE ||
641         where == CARRIED)
642         return;
643     game.link[object] = game.atloc[where];
644     game.atloc[where] = object;
645 }
646
647 long atdwrf(loc_t where)
648 /*  Return the index of first dwarf at the given location, zero if no dwarf is
649  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
650  *  the pirate (6th dwarf). */
651 {
652     long at;
653
654     at = 0;
655     if (game.dflag < 2)
656         return (at);
657     at = -1;
658     for (long i = 1; i <= NDWARVES - 1; i++) {
659         if (game.dloc[i] == where)
660             return i;
661         if (game.dloc[i] != 0)
662             at = 0;
663     }
664     return (at);
665 }
666
667 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
668  *  randrange) */
669
670 long setbit(long bit)
671 /*  Returns 2**bit for use in constructing bit-masks. */
672 {
673     return (1L << bit);
674 }
675
676 bool tstbit(long mask, int bit)
677 /*  Returns true if the specified bit is set in the mask. */
678 {
679     return (mask & (1 << bit)) != 0;
680 }
681
682 void set_seed(long seedval)
683 /* Set the LCG seed */
684 {
685     game.lcg_x = (unsigned long) seedval % game.lcg_m;
686
687     // once seed is set, we need to generate the Z`ZZZ word
688     make_zzword(game.zzword);
689 }
690
691 unsigned long get_next_lcg_value(void)
692 /* Return the LCG's current value, and then iterate it. */
693 {
694     unsigned long old_x = game.lcg_x;
695     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
696     return old_x;
697 }
698
699 long randrange(long range)
700 /* Return a random integer from [0, range). */
701 {
702     return range * get_next_lcg_value() / game.lcg_m;
703 }
704
705 void make_zzword(char zzword[TOKLEN + 1])
706 {
707     for (int i = 0; i < 5; ++i) {
708         zzword[i] = 'A' + randrange(26);
709     }
710     zzword[1] = '\''; // force second char to apostrophe
711     zzword[5] = '\0';
712 }
713
714 // LCOV_EXCL_START
715 void bug(enum bugtype num, const char *error_string)
716 {
717     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
718     exit(EXIT_FAILURE);
719 }
720 // LCOV_EXCL_STOP
721
722 /* end */
723
724 void state_change(obj_t obj, long state)
725 /* Object must have a change-message list for this to be useful; only some do */
726 {
727     game.prop[obj] = state;
728     pspeak(obj, change, state, true);
729 }
730
731 /* end */