1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini dumpkmap implementation for busybox
4  *
5  * Copyright (C) Arne Bernin <arne@matrix.loopback.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 //config:config DUMPKMAP
10 //config:	bool "dumpkmap (1.6 kb)"
11 //config:	default y
12 //config:	help
13 //config:	This program dumps the kernel's keyboard translation table to
14 //config:	stdout, in binary format. You can then use loadkmap to load it.
15 
16 //applet:IF_DUMPKMAP(APPLET_NOEXEC(dumpkmap, dumpkmap, BB_DIR_BIN, BB_SUID_DROP, dumpkmap))
17 /* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
18 
19 //kbuild:lib-$(CONFIG_DUMPKMAP) += dumpkmap.o
20 
21 //usage:#define dumpkmap_trivial_usage
22 //usage:       "> keymap"
23 //usage:#define dumpkmap_full_usage "\n\n"
24 //usage:       "Print a binary keyboard translation table to stdout"
25 //usage:
26 //usage:#define dumpkmap_example_usage
27 //usage:       "$ dumpkmap > keymap\n"
28 
29 #include "libbb.h"
30 #include "common_bufsiz.h"
31 
32 /* From <linux/kd.h> */
33 struct kbentry {
34 	unsigned char kb_table;
35 	unsigned char kb_index;
36 	unsigned short kb_value;
37 };
38 #define KDGKBENT 0x4B46  /* gets one entry in translation table */
39 
40 /* From <linux/keyboard.h> */
41 #define NR_KEYS 128
42 #define MAX_NR_KEYMAPS 256
43 
44 int dumpkmap_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
dumpkmap_main(int argc UNUSED_PARAM,char ** argv)45 int dumpkmap_main(int argc UNUSED_PARAM, char **argv)
46 {
47 	struct kbentry ke;
48 	int i, j, fd;
49 
50 	/* When user accidentally runs "dumpkmap FILE"
51 	 * instead of "dumpkmap >FILE", we'd dump binary stuff to tty.
52 	 * Let's prevent it:
53 	 */
54 	if (argv[1])
55 		bb_show_usage();
56 /*	bb_warn_ignoring_args(argv[1]);*/
57 
58 	fd = get_console_fd_or_die();
59 
60 #define flags bb_common_bufsiz1
61 	setup_common_bufsiz();
62 	/*                     0 1 2 3 4 5 6 7 8 9 a b c=12 */
63 	memcpy(flags, "bkeymap\1\1\1\0\1\1\1\0\1\1\1\0\1",
64 	/* Can use sizeof, or sizeof-1. sizeof is even, using that */
65 	/****/ sizeof("bkeymap\1\1\1\0\1\1\1\0\1\1\1\0\1")
66 	);
67 	write(STDOUT_FILENO, flags, 7 + MAX_NR_KEYMAPS);
68 #define flags7 (flags + 7)
69 
70 	for (i = 0; i < 13; i++) {
71 		if (flags7[i]) {
72 			for (j = 0; j < NR_KEYS; j++) {
73 				ke.kb_index = j;
74 				ke.kb_table = i;
75 				if (!ioctl_or_perror(fd, KDGKBENT, &ke,
76 						"ioctl(KDGKBENT{%d,%d}) failed",
77 						j, i)
78 				) {
79 					write(STDOUT_FILENO, &ke.kb_value, 2);
80 				}
81 			}
82 		}
83 	}
84 	if (ENABLE_FEATURE_CLEAN_UP) {
85 		close(fd);
86 	}
87 	return EXIT_SUCCESS;
88 }
89