Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/*	$NetBSD: main.c,v 1.73 2022/05/29 21:02:37 rillig Exp $	*/

/*
 * Copyright (c) 1994
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__COPYRIGHT("@(#) Copyright (c) 1994\
 The Regents of the University of California.  All rights reserved.");
/*	@(#)main.c	8.4 (Berkeley) 5/4/95	*/
__RCSID("$NetBSD: main.c,v 1.73 2022/05/29 21:02:37 rillig Exp $");

#include <sys/stat.h>
#include <curses.h>
#include <err.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "gomoku.h"

enum input_source {
	USER,			/* get input from standard input */
	PROGRAM,		/* get input from program */
	INPUTF			/* get input from a file */
};

enum testing_mode {
	NORMAL_PLAY,
	USER_VS_USER,
	PROGRAM_VS_PROGRAM
};

bool	interactive = true;	/* true if interactive */
int	debug;			/* > 0 if debugging */
static enum testing_mode test = NORMAL_PLAY;
static char *prog;		/* name of program */
static char user[LOGIN_NAME_MAX]; /* name of player */
static FILE *debugfp;		/* file for debug output */
static FILE *inputfp;		/* file for debug input */

const char	pdir[4]		= "-\\|/";

struct	spotstr	board[BAREA];		/* info for board */
struct	combostr frames[FAREA];		/* storage for all frames */
struct	combostr *sortframes[2];	/* sorted list of non-empty frames */
u_char	overlap[FAREA * FAREA];		/* non-zero if frame [a][b] overlap;
					 * see init_overlap */
spot_index intersect[FAREA * FAREA];	/* frame [a][b] intersection */
struct game game;
const char *plyr[2] = { "???", "???" };	/* who's who */

static spot_index readinput(FILE *);
static void misclog(const char *, ...) __printflike(1, 2);
static void quit(void) __dead;
#if !defined(DEBUG)
static void quitsig(int) __dead;
#endif

static void
warn_if_exists(const char *fname)
{
	struct stat st;

	if (lstat(fname, &st) == 0) {
		int x, y;
		getyx(stdscr, y, x);
		addstr("  (already exists)");
		move(y, x);
	} else
		clrtoeol();
}

static void
save_game(void)
{
	char fname[PATH_MAX];
	FILE *fp;

	ask("Save file name? ");
	(void)get_line(fname, sizeof(fname), warn_if_exists);
	if ((fp = fopen(fname, "w")) == NULL) {
		misclog("cannot create save file");
		return;
	}
	for (unsigned int m = 0; m < game.nmoves; m++)
		fprintf(fp, "%s\n", stoc(game.moves[m]));
	fclose(fp);
}

static void
parse_args(int argc, char **argv)
{
	int ch;

	prog = strrchr(argv[0], '/');
	prog = prog != NULL ? prog + 1 : argv[0];

	while ((ch = getopt(argc, argv, "bcdD:u")) != -1) {
		switch (ch) {
		case 'b':	/* background */
			interactive = false;
			break;
		case 'c':
			test = PROGRAM_VS_PROGRAM;
			break;
		case 'd':
			debug++;
			break;
		case 'D':	/* log debug output to file */
			if ((debugfp = fopen(optarg, "w")) == NULL)
				err(1, "%s", optarg);
			break;
		case 'u':
			test = USER_VS_USER;
			break;
		default:
		usage:
			fprintf(stderr, "usage: %s [-bcdu] [-Dfile] [file]\n",
			    getprogname());
			exit(EXIT_FAILURE);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc > 1)
		goto usage;
	if (argc == 1 && (inputfp = fopen(*argv, "r")) == NULL)
		err(1, "%s", *argv);
}

static void
set_input_sources(enum input_source *input, player_color color)
{
	switch (test) {
	case NORMAL_PLAY:
		input[color] = USER;
		input[color != BLACK ? BLACK : WHITE] = PROGRAM;
		break;
	case USER_VS_USER:
		input[BLACK] = USER;
		input[WHITE] = USER;
		break;
	case PROGRAM_VS_PROGRAM:
		input[BLACK] = PROGRAM;
		input[WHITE] = PROGRAM;
		break;
	}
}

static int
ask_user_color(void)
{
	int color;

	mvprintw(BSZ + 3, 0, "Black moves first. ");
	ask("(B)lack or (W)hite? ");
	for (;;) {
		int ch = get_key(NULL);
		if (ch == 'b' || ch == 'B') {
			color = BLACK;
			break;
		}
		if (ch == 'w' || ch == 'W') {
			color = WHITE;
			break;
		}
		if (ch == 'q' || ch == 'Q')
			quit();

		beep();
		ask("Please choose (B)lack or (W)hite: ");
	}
	move(BSZ + 3, 0);
	clrtoeol();
	return color;
}

static int
read_color(void)
{
	char buf[128];

	get_line(buf, sizeof(buf), NULL);
	if (strcmp(buf, "black") == 0)
		return BLACK;
	if (strcmp(buf, "white") == 0)
		return WHITE;
	panic("Huh?  Expected `black' or `white', got `%s'\n", buf);
	/* NOTREACHED */
}

static spot_index
read_move(void)
{
again:
	if (interactive) {
		ask("Select move, (S)ave or (Q)uit.");
		spot_index s = get_coord();
		if (s == SAVE) {
			save_game();
			goto again;
		}
		if (s != RESIGN && board[s].s_occ != EMPTY) {
			beep();
			goto again;
		}
		return s;
	} else {
		char buf[128];
		if (!get_line(buf, sizeof(buf), NULL))
			return RESIGN;
		if (buf[0] == '\0')
			goto again;
		return ctos(buf);
	}
}

static void
declare_winner(int outcome, const enum input_source *input, player_color color)
{

	move(BSZ + 3, 0);
	switch (outcome) {
	case WIN:
		if (input[color] == PROGRAM)
			addstr("Ha ha, I won");
		else if (input[0] == USER && input[1] == USER)
			addstr("Well, you won (and lost)");
		else
			addstr("Rats! you won");
		break;
	case TIE:
		addstr("Wow! It's a tie");
		break;
	case ILLEGAL:
		addstr("Illegal move");
		break;
	}
	clrtoeol();
	bdisp();
}

struct outcome {
	int result;
	player_color winner;
};

static struct outcome
main_game_loop(enum input_source *input)
{
	spot_index curmove = 0;
	player_color color = BLACK;

again:
	switch (input[color]) {
	case INPUTF:
		curmove = readinput(inputfp);
		if (curmove != END_OF_INPUT)
			break;
		set_input_sources(input, color);
		plyr[BLACK] = input[BLACK] == USER ? user : prog;
		plyr[WHITE] = input[WHITE] == USER ? user : prog;
		bdwho();
		refresh();
		goto again;

	case USER:
		curmove = read_move();
		break;

	case PROGRAM:
		if (interactive)
			ask("Thinking...");
		curmove = pickmove(color);
		break;
	}

	if (interactive && curmove != ILLEGAL) {
		misclog("%3u%*s%-6s",
		    game.nmoves + 1, color == BLACK ? 2 : 9, "",
		    stoc(curmove));
	}

	int outcome;
	if ((outcome = makemove(color, curmove)) != MOVEOK)
		return (struct outcome){ outcome, color };

	if (interactive)
		bdisp();
	color = color != BLACK ? BLACK : WHITE;
	goto again;
}

int
main(int argc, char **argv)
{
	char *user_name;
	int color;
	enum input_source input[2];

	/* Revoke setgid privileges */
	setgid(getgid());

	setprogname(argv[0]);

	user_name = getlogin();
	strlcpy(user, user_name != NULL ? user_name : "you", sizeof(user));

	color = BLACK;

	parse_args(argc, argv);

	if (debug == 0)
		srandom((unsigned int)time(0));
	if (interactive)
		cursinit();		/* initialize curses */
again:
	init_board();			/* initialize board contents */

	if (interactive) {
		bdisp_init();		/* initialize display of board */
#ifdef DEBUG
		signal(SIGINT, whatsup);
#else
		signal(SIGINT, quitsig);
#endif

		if (inputfp == NULL && test == NORMAL_PLAY)
			color = ask_user_color();
	} else {
		setbuf(stdout, NULL);
		color = read_color();
	}

	if (inputfp != NULL) {
		input[BLACK] = INPUTF;
		input[WHITE] = INPUTF;
	} else {
		set_input_sources(input, color);
	}
	if (interactive) {
		plyr[BLACK] = input[BLACK] == USER ? user : prog;
		plyr[WHITE] = input[WHITE] == USER ? user : prog;
		bdwho();
		refresh();
	}

	struct outcome outcome = main_game_loop(input);

	if (interactive) {
		declare_winner(outcome.result, input, outcome.winner);
		if (outcome.result != RESIGN) {
		replay:
			ask("Play again? ");
			int ch = get_key("YyNnQqSs");
			if (ch == 'Y' || ch == 'y')
				goto again;
			if (ch == 'S' || ch == 's') {
				save_game();
				goto replay;
			}
		}
	}
	quit();
}

static spot_index
readinput(FILE *fp)
{
	int c;
	char buf[128];
	size_t pos;

	pos = 0;
	while ((c = getc(fp)) != EOF && c != '\n' && pos < sizeof(buf) - 1)
		buf[pos++] = c;
	buf[pos] = '\0';
	return c == EOF ? END_OF_INPUT : ctos(buf);
}

#ifdef DEBUG

static bool
skip_any(const char **pp, const char *s)
{
	while (strchr(s, **pp) != NULL)
		(*pp)++;
	return true;
}

static bool
parse_char_index(const char **pp, const char *s, unsigned int *out)
{
	const char *found = strchr(s, **pp);
	if (found != NULL)
		*out = (unsigned int)(found - s), (*pp)++;
	return found != NULL;
}

static bool
parse_direction(const char **pp, direction *out)
{
	unsigned int u;
	if (!parse_char_index(pp, "-\\|/", &u))
		return false;
	*out = (direction)u;
	return true;
}

static bool
parse_row(const char **pp, unsigned int *out)
{
	if (!('0' <= **pp && **pp <= '9'))
		return false;
	unsigned int u = *(*pp)++ - '0';
	if ('0' <= **pp && **pp <= '9')
		u = 10 * u + *(*pp)++ - '0';
	*out = u;
	return 1 <= u && u <= BSZ;
}

static bool
parse_spot(const char **pp, spot_index *out)
{
	unsigned row, col;
	if (!parse_char_index(pp, "abcdefghjklmnopqrst", &col) &&
	    !parse_char_index(pp, "ABCDEFGHJKLMNOPQRST", &col))
		return false;
	if (!parse_row(pp, &row))
		return false;
	*out = PT(col + 1, row);
	return true;
}

/*
 * Handle strange situations and ^C.
 */
/* ARGSUSED */
void
whatsup(int signum __unused)
{
	unsigned int n;
	player_color color;
	spot_index s, s1, s2;
	direction r1, r2;
	struct spotstr *sp;
	FILE *fp;
	const char *str;
	struct elist *ep;
	struct combostr *cbp;
	char input[128];
	char tmp[128];

	if (!interactive)
		quit();
top:
	ask("debug command: ");
	if (!get_line(input, sizeof(input), NULL))
		quit();
	switch (*input) {
	case '\0':
		goto top;
	case 'q':		/* conservative quit */
		quit();
		/* NOTREACHED */
	case 'd':		/* set debug level */
		debug = input[1] - '0';
		debuglog("Debug set to %d", debug);
		goto top;
	case 'c':
		ask("");
		return;
	case 'b':		/* back up a move */
		if (game.nmoves > 0) {
			game.nmoves--;
			board[game.moves[game.nmoves]].s_occ = EMPTY;
			bdisp();
		}
		goto top;
	case 's':		/* suggest a move */
		color = input[1] == 'b' ? BLACK : WHITE;
		debuglog("suggest %c %s", color == BLACK ? 'B' : 'W',
			stoc(pickmove(color)));
		goto top;
	case 'f':		/* go forward a move */
		board[game.moves[game.nmoves]].s_occ =
		    game.nmoves % 2 == 0 ? BLACK : WHITE;
		game.nmoves++;
		bdisp();
		goto top;
	case 'l':		/* print move history */
		if (input[1] == '\0') {
			for (unsigned int m = 0; m < game.nmoves; m++)
				debuglog("%s", stoc(game.moves[m]));
			goto top;
		}
		if ((fp = fopen(input + 1, "w")) == NULL)
			goto top;
		for (unsigned int m = 0; m < game.nmoves; m++) {
			fprintf(fp, "%s", stoc(game.moves[m]));
			if (++m < game.nmoves)
				fprintf(fp, " %s\n", stoc(game.moves[m]));
			else
				fputc('\n', fp);
		}
		bdump(fp);
		fclose(fp);
		goto top;
	case 'o':
		str = input + 1;
		if (skip_any(&str, " ") &&
		    parse_spot(&str, &s1) &&
		    parse_direction(&str, &r1) &&
		    skip_any(&str, ", ") &&
		    parse_spot(&str, &s2) &&
		    parse_direction(&str, &r2) &&
		    *str == '\0') {
			n = board[s1].s_frame[r1] * FAREA
			    + board[s2].s_frame[r2];
			debuglog("overlap %s%c,%s%c = %02x",
			    stoc(s1), pdir[r1], stoc(s2), pdir[r2],
			    overlap[n]);
		} else
			debuglog("usage: o <spot><dir> <spot><dir>");
		goto top;
	case 'p':
		sp = &board[s = ctos(input + 1)];
		debuglog("V %s %x/%d %d %x/%d %d %d %x", stoc(s),
			sp->s_combo[BLACK].s, sp->s_level[BLACK],
			sp->s_nforce[BLACK],
			sp->s_combo[WHITE].s, sp->s_level[WHITE],
			sp->s_nforce[WHITE], sp->s_wval, sp->s_flags);
		debuglog("FB %s %x %x %x %x", stoc(s),
			sp->s_fval[BLACK][0].s, sp->s_fval[BLACK][1].s,
			sp->s_fval[BLACK][2].s, sp->s_fval[BLACK][3].s);
		debuglog("FW %s %x %x %x %x", stoc(s),
			sp->s_fval[WHITE][0].s, sp->s_fval[WHITE][1].s,
			sp->s_fval[WHITE][2].s, sp->s_fval[WHITE][3].s);
		goto top;
	case 'e':	/* e [0-9] spot */
		str = input + 1;
		if (*str >= '0' && *str <= '9')
			n = *str++ - '0';
		else
			n = 0;
		sp = &board[ctos(str)];
		for (ep = sp->s_empty; ep != NULL; ep = ep->e_next) {
			cbp = ep->e_combo;
			if (n != 0) {
				if (cbp->c_nframes > n)
					continue;
				if (cbp->c_nframes != n)
					break;
			}
			printcombo(cbp, tmp, sizeof(tmp));
			debuglog("%s", tmp);
		}
		goto top;
	default:
		debuglog("Options are:");
		debuglog("q    - quit");
		debuglog("c    - continue");
		debuglog("d#   - set debug level to #");
		debuglog("p#   - print values at #");
		goto top;
	}
}
#endif /* DEBUG */

/*
 * Display debug info.
 */
void
debuglog(const char *fmt, ...)
{
	va_list ap;
	char buf[128];

	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);

	if (debugfp != NULL)
		fprintf(debugfp, "%s\n", buf);
	if (interactive)
		dislog(buf);
	else
		fprintf(stderr, "%s\n", buf);
}

static void
misclog(const char *fmt, ...)
{
	va_list ap;
	char buf[128];

	va_start(ap, fmt);
	vsnprintf(buf, sizeof(buf), fmt, ap);
	va_end(ap);

	if (debugfp != NULL)
		fprintf(debugfp, "%s\n", buf);
	if (interactive)
		dislog(buf);
	else
		printf("%s\n", buf);
}

static void
quit(void)
{
	if (interactive) {
		bdisp();		/* show final board */
		cursfini();
	}
	exit(0);
}

#if !defined(DEBUG)
static void
quitsig(int dummy __unused)
{
	quit();
}
#endif

/*
 * Die gracefully.
 */
void
panic(const char *fmt, ...)
{
	va_list ap;

	if (interactive) {
		bdisp();
		cursfini();
	}

	fprintf(stderr, "%s: ", prog);
	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);
	fprintf(stderr, "\n");

	fputs("I resign\n", stdout);
	exit(1);
}