4 * (c) 2010 Martin Mares <mj@ucw.cz>
8 * Things that are not implemented:
11 * - exact behavior of accumulator/R1/R2 (the manual lacks details)
12 * - exact behavior of negative zero
13 * - I/O instructions for devices that are not emulated (paper tape
14 * reader and puncher, card reader and puncher, magnetic tape unit)
28 static int cpu_quota = -1;
29 static int print_quota = -1;
30 static void (*error_hook)(char *msg);
32 // Minsk-2 has 37-bit words in sign-magnitude representation (bit 36 = sign)
33 typedef unsigned long long int word;
35 #define WORD_MASK 01777777777777ULL
36 #define SIGN_MASK 01000000000000ULL
37 #define VAL_MASK 00777777777777ULL
39 static int wsign(word w)
41 return (w & SIGN_MASK) ? -1 : 1;
44 static word wabs(word w)
49 #define WF(w) (wsign(w) < 0 ? '-' : '+'), wabs(w)
51 static long long wtoll(word w)
59 static word wfromll(long long x)
61 word w = ((x < 0) ? -x : x) & VAL_MASK;
67 static double wtofrac(word w)
69 return (double)wtoll(w) / (double)(1ULL << 36);
72 static word wfromfrac(double d)
74 return wfromll((long long)(d * (double)(1ULL << 36)));
77 static int int_in_range(long long x)
79 return (x >= -(long long)VAL_MASK && x <= (long long)VAL_MASK);
82 static int frac_in_range(double d)
84 return (d > -1. && d < 1.);
87 static int wexp(word w)
90 return (w & 0100 ? -exp : exp);
93 static word wputexp(word w, int exp)
95 return ((w & ~(word)0177) | ((exp < 0) ? 0100 | (-exp) : exp));
98 static int wmanti(word w)
100 return ((w >> 8) & ((1 << 28) - 1));
103 static double wtofloat(word w)
105 double x = wmanti(w);
106 return ldexp(x, wexp(w) - 28);
109 static int float_in_range(double x)
112 return (x <= ldexp((1 << 28) - 1, 63 - 28));
115 static word wfromfloat(double x, int normalized)
124 double m = frexp(x, &exp);
125 word mm = (word) ldexp(m, 28);
130 if (normalized || exp < -91)
148 static word mem[4096];
150 static word rd(int addr)
152 word val = addr ? mem[addr] : 0;
154 printf("\tRD %04o = %c%012llo\n", addr, WF(val));
158 static void wr(int addr, word val)
160 assert(!(val & ~(WORD_MASK)));
162 printf("\tWR %04o = %c%012llo\n", addr, WF(val));
168 static void parse_error(char *msg)
171 error_hook("Parse error");
172 printf("Ошибка входа (стр. %d): %s\n", lino, msg);
176 static void parse_in(void)
181 while (fgets(line, sizeof(line), stdin))
184 char *eol = strchr(line, '\n');
186 parse_error("Строка слишком долгая");
190 if (!c[0] || c[0] == ';')
192 if (!strncmp(c, ";daji_zor_i_litva=", 18))
196 error_hook("Secret tracing switch flipped");
205 for (int i=0; i<4; i++)
209 if (*c >= '0' && *c <= '7')
210 addr = 8*addr + *c++ - '0';
212 parse_error("Плохая цифра");
217 parse_error("Адрес слишком долгий");
225 parse_error("Плохой знак");
227 for (int i=0; i<12; i++)
231 if (*c >= '0' && *c <= '7')
232 w = 8*w + *c++ - '0';
234 parse_error("Плохая цифра");
239 parse_error("Номер слишком долгий");
246 static word r1, r2, current_ins;
247 static int ip = 00050; // Standard program start location
250 static void stop(char *reason, char *notice)
254 printf("Машина остановлена -- %s\n", reason);
255 printf("СчАК:%04o См:%c%012llo Р1:%c%012llo Р2:%c%012llo\n", prev_ip, WF(acc), WF(r1), WF(r2));
259 static void over(void)
261 stop("Аварийный останов", "Overflow");
264 static void notimp(void)
267 stop("Устройство разбитое", "Not implemented");
270 static void noins(void)
273 stop("Эту команду не знаю", "Illegal instruction");
276 static uint16_t linebuf[128];
278 static uint16_t russian_chars[64] = {
279 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
280 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
281 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
282 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
283 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, // 4x
284 0x418, 0x419, 0x41a, 0x41b, 0x41c, 0x41d, 0x41e, 0x41f, // 5x
285 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, // 6x
286 0x428, 0x429, 0x42b, 0x42c, 0x42d, 0x42e, 0x42f, 0x2013 // 7x
289 static uint16_t latin_chars[64] = {
290 '0', '1', '2', '3', '4', '5', '6', '7', // 0x
291 '8', '9', '+', '-', '/', ',', '.', ' ', // 1x
292 0x2169, '^', '(', ')', 0x00d7, '=', ';', '[', // 2x
293 ']', '*', '`', '\'', 0x2260, '<', '>', ':', // 3x
294 'A', 'B', 'W', 'G', 'D', 'E', 'V', 'Z', // 4x
295 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 5x
296 'R', 'S', 'T', 'U', 'F', 'H', 'C', ' ', // 6x
297 ' ', ' ', 'Y', 'X', ' ', ' ', 'Q', 0x2013 // 7x
300 static void print_line(int r)
303 * Meaning of bits of r:
304 * 0 = perform line feed
310 if (print_quota > 0 && !--print_quota)
311 stop("Бумага дошла - нужно ехать в Сибирь про новую", "Out of paper");
312 for (int i=0; i<128; i++)
321 putchar(0xc0 | (ch >> 6));
322 putchar(0x80 | (ch & 0x3f));
326 putchar(0xe0 | (ch >> 12));
327 putchar(0x80 | ((ch >> 6) & 0x3f));
328 putchar(0x80 | (ch & 0x3f));
333 memset(linebuf, 0, sizeof(linebuf));
341 static void print_ins(int x, int y)
345 int r = (x >> 9) & 7;
358 case 0: // Decimal float
359 fmt = "+dddddddx+xbd";
361 case 1: // Octal number
362 fmt = "+oooooooooooo";
364 case 2: // Decimal fixed
367 case 3: // Decimal unsigned
371 case 4: // One Russian symbol
375 case 5: // Russian text
378 case 6: // One Latin symbol
382 default: // Latin text
399 ch = (yy & (1ULL << bit)) ? '-' : '+';
403 ch = '0' + ((yy >> bit) & 1);
407 ch = '0' + ((yy >> bit) & 7);
411 ch = '0' + ((yy >> bit) & 15);
417 ch = russian_chars[(yy >> bit) & 077];
421 ch = latin_chars[(yy >> bit) & 077];
429 if (ch == '0' || ch == ' ')
435 pos = (pos+1) & 0177;
440 static void run(void)
449 int op = (w >> 30) & 0177; // Operation code
450 int ax = (w >> 28) & 3; // Address extensions not supported
451 int ix = (w >> 24) & 15; // Indexing
452 int x = (w >> 12) & 07777; // Operands (original form)
454 int xi=x, yi=y; // (indexed form)
456 printf("@%04o %c%02o %02o %04o %04o\n",
458 (w & SIGN_MASK) ? '-' : '+',
459 (int)((w >> 30) & 077),
460 (int)((w >> 24) & 077),
468 xi = (xi + (int)((i >> 12) & 07777)) & 07777;
469 yi = (yi + (int)(i & 07777)) & 07777;
471 printf("\tIndexing -> %04o %04o\n", xi, yi);
476 if (cpu_quota > 0 && !--cpu_quota)
477 stop("Тайм-аут", "CPU quota exceeded");
479 /* Arithmetic operations */
482 long long aa, bb, cc;
486 auto void afetch(void);
496 auto void astore(word result);
497 void astore(word result)
504 auto void astore_int(long long x);
505 void astore_int(long long x)
507 if (!int_in_range(x))
512 auto void astore_frac(double f);
513 void astore_frac(double f)
515 if (!frac_in_range(f))
517 astore(wfromfrac(f));
520 auto void astore_float(double f);
521 void astore_float(double f)
523 if (!float_in_range(f))
525 astore(wfromfloat(f, 0));
534 case 004 ... 007: // XOR
538 case 010 ... 013: // FIX addition
540 astore_int(wtoll(a) + wtoll(b));
542 case 014 ... 017: // FP addition
544 astore_float(wtofloat(a) + wtofloat(b));
546 case 020 ... 023: // FIX subtraction
548 astore_int(wtoll(a) - wtoll(b));
550 case 024 ... 027: // FP subtraction
552 astore_float(wtofloat(a) - wtofloat(b));
554 case 030 ... 033: // FIX multiplication
556 astore_frac(wtofrac(a) * wtofrac(b));
558 case 034 ... 037: // FP multiplication
560 astore_float(wtofloat(a) * wtofloat(b));
562 case 040 ... 043: // FIX division
568 astore_frac(ad / bd);
570 case 044 ... 047: // FP division
574 if (!bd || wexp(b) < -63)
576 astore_float(ad / bd);
578 case 050 ... 053: // FIX subtraction of abs values
580 astore_int(wabs(a) - wabs(b));
582 case 054 ... 057: // FP subtraction of abs values
584 astore_float(fabs(wtofloat(a)) - fabs(wtofloat(b)));
586 case 060 ... 063: // Shift logical
589 if (i <= -37 || i >= 37)
592 astore((a << i) & WORD_MASK);
596 case 064 ... 067: // Shift arithmetical
600 if (i <= -36 || i >= 36)
603 cc = (aa << i) & VAL_MASK;
606 astore((a & SIGN_MASK) | wfromll(cc));
608 case 070 ... 073: // And
612 case 074 ... 077: // Or
620 stop("Останов машины", "Halted");
621 case 0103: // I/O magtape
623 case 0104: // Disable rounding
625 case 0105: // Enable rounding
627 case 0106: // Interrupt control
629 case 0107: // Reverse tape
632 wr(yi, r1 = acc = rd(xi));
634 case 0111: // Move negative
635 wr(yi, acc = (r1 = rd(xi)) ^ SIGN_MASK);
637 case 0112: // Move absolute value
638 wr(yi, acc = (r1 = rd(xi)) & VAL_MASK);
640 case 0113: // Read from keyboard
642 case 0114: // Copy sign
643 wr(yi, acc = rd(yi) ^ ((r1 = rd(xi)) & SIGN_MASK));
645 case 0115: // Read code from R1 (obscure)
647 case 0116: // Copy exponent
648 wr(yi, acc = wputexp(rd(yi), wexp(r1 = rd(xi))));
650 case 0117: // I/O teletype
656 aa = (a >> 24) & 017777;
659 b = rd(y); // (a mountain range near Prague)
660 acc = ((aa-1) << 24) |
661 (((((a >> 12) & 07777) + (b >> 12) & 07777) & 07777) << 12) |
662 (((a & 07777) + (b & 07777)) & 07777);
670 case 0131: // Jump to subroutine
671 wr(y, acc = ((030ULL << 30) | ((ip & 07777ULL) << 12)));
674 case 0132: // Jump if positive
680 case 0133: // Jump if overflow
681 // Since we always trap on overflow, this instruction always jumps to the 1st address
684 case 0134: // Jump if zero
690 case 0135: // Jump if key pressed
691 // No keys are ever pressed, so always jump to 2nd
694 case 0136: // Interrupt masking
696 case 0137: // Used only when reading from tape
698 case 0140 ... 0147: // I/O
700 case 0150 ... 0154: // I/O
702 case 0160 ... 0161: // I/O
704 case 0162: // Printing
709 case 0170: // FIX multiplication, bottom part
711 if (wtofrac(a) * wtofrac(b) >= .1/(1ULL << 32))
713 acc = wfromll(((unsigned long long)wabs(a) * (unsigned long long)wabs(b)) & VAL_MASK);
714 // XXX: What should be the sign? The book does not define that.
727 case 0172: // Add exponents
730 i = wexp(a) + wexp(b);
731 if (i < -63 || i > 63)
736 case 0173: // Sub exponents
739 i = wexp(b) - wexp(a);
740 if (i < -63 || i > 63)
745 case 0174: // Addition in one's complement
752 // XXX: The effect on the accumulator is undocumented, but likely to be as follows:
755 case 0175: // Normalization
760 wr((yi+1) & 07777, 0);
768 while (!(a & (SIGN_MASK >> 1)))
775 wr((yi+1) & 07777, i);
778 case 0176: // Population count
781 for (int i=0; i<36; i++)
784 // XXX: Guessing that acc gets a copy of the result
793 printf("\tACC:%c%012llo R1:%c%012llo R2:%c%012llo\n", WF(acc), WF(r1), WF(r2));
797 /*** Daemon interface ***/
803 #include <sys/signal.h>
804 #include <sys/wait.h>
805 #include <sys/poll.h>
806 #include <sys/socket.h>
807 #include <netinet/in.h>
808 #include <arpa/inet.h>
811 #define DTRACE(msg, args...) fprintf(stderr, msg "\n", ##args)
812 #define DLOG(msg, args...) fprintf(stderr, msg "\n", ##args)
814 #define DTRACE(msg, args...) do { } while(0)
815 #define DLOG(msg, args...) syslog(LOG_INFO, msg, ##args)
818 #define MAX_CONNECTIONS 50 // Per daemon
819 #define MAX_CONNS_PER_IP 1 // Per IP
820 #define MAX_TRACKERS 200 // IP address trackers
821 #define TBF_MAX 5 // Max number of tokens in the bucket
822 #define TBF_REFILL_PER_SEC 0.2 // Bucket refill rate (buckets/sec)
824 #define PID_FILE "/var/run/minsk.pid"
828 static void die(char *msg)
830 fprintf(stderr, "minsk: ");
831 fprintf(stderr, msg);
836 static char **spt_argv;
837 static char *spt_start, *spt_end;
839 static void setproctitle_init(int argc, char **argv)
842 char **env, **oldenv, *t;
846 /* Create a backup copy of environment */
849 for (i=0; oldenv[i]; i++)
850 len += strlen(oldenv[i]) + 1;
851 __environ = env = malloc(sizeof(char *)*(i+1));
853 if (!__environ || !t)
854 die("malloc failed");
855 for (i=0; oldenv[i]; i++)
858 len = strlen(oldenv[i]) + 1;
859 memcpy(t, oldenv[i], len);
864 /* Scan for consecutive free space */
865 spt_start = spt_end = argv[0];
866 for (i=0; i<argc; i++)
867 if (!i || spt_end+1 == argv[i])
868 spt_end = argv[i] + strlen(argv[i]);
869 for (i=0; oldenv[i]; i++)
870 if (spt_end+1 == oldenv[i])
871 spt_end = oldenv[i] + strlen(oldenv[i]);
875 setproctitle(const char *msg, ...)
882 if (spt_end > spt_start)
884 n = vsnprintf(buf, sizeof(buf), msg, args);
885 if (n >= (int) sizeof(buf) || n < 0)
886 sprintf(buf, "<too-long>");
887 n = spt_end - spt_start;
888 strncpy(spt_start, buf, n);
890 spt_argv[0] = spt_start;
896 static void sigchld_handler(int sig __attribute__((unused)))
900 static void sigalrm_handler(int sig __attribute__((unused)))
902 const char err[] = "--- Timed out. Time machine disconnected. ---\n";
903 write(1, err, sizeof(err));
904 DLOG("Connection timed out");
908 static void child_error_hook(char *err)
910 DLOG("Stopped: %s", err);
913 static void child(int sk2)
919 struct sigaction sact = {
920 .sa_handler = sigalrm_handler,
922 if (sigaction(SIGALRM, &sact, NULL) < 0)
923 die("sigaction: %m");
930 const char welcome[] = "+++ Welcome to our computer museum. +++\n+++ Our time machine will connect you to one of our exhibits. +++\n\n";
931 write(1, welcome, sizeof(welcome));
933 error_hook = child_error_hook;
943 struct tracker *tracker;
946 static struct conn connections[MAX_CONNECTIONS];
948 static struct conn *get_conn(struct in_addr *a)
950 for (int i=0; i<MAX_CONNECTIONS; i++)
952 struct conn *c = &connections[i];
955 memcpy(&c->addr, a, sizeof(struct in_addr));
962 static struct conn *pid_to_conn(pid_t pid)
964 for (int i=0; i<MAX_CONNECTIONS; i++)
966 struct conn *c = &connections[i];
973 static void put_conn(struct conn *c)
986 static struct tracker trackers[MAX_TRACKERS];
988 static int get_tracker(struct conn *c)
991 time_t now = time(NULL);
994 for (i=0; i<MAX_TRACKERS; i++)
997 if (!memcmp(&t->addr, &c->addr, sizeof(struct in_addr)))
1000 if (i < MAX_TRACKERS)
1002 if (now > t->last_access)
1004 t->tokens += (now - t->last_access) * (double) TBF_REFILL_PER_SEC;
1005 t->last_access = now;
1006 if (t->tokens > TBF_MAX)
1007 t->tokens = TBF_MAX;
1009 DTRACE("TBF: Using tracker %d (%.3f tokens)", i, t->tokens);
1014 for (int i=0; i<MAX_TRACKERS; i++)
1017 if (!t->active_conns && (min_i < 0 || t->last_access < trackers[min_i].last_access))
1022 DLOG("TBF: Out of trackers!");
1025 t = &trackers[min_i];
1027 DTRACE("TBF: Recycling tracker %d", min_i);
1029 DTRACE("TBF: Creating tracker %d", min_i);
1030 memset(t, 0, sizeof(*t));
1032 t->last_access = now;
1033 t->tokens = TBF_MAX;
1036 if (t->active_conns >= MAX_CONNS_PER_IP)
1038 DTRACE("TBF: Too many conns per IP");
1042 if (t->tokens >= 0.999)
1047 DTRACE("TBF: Passed (%d conns)", t->active_conns);
1052 DTRACE("TBF: Failed");
1058 static void put_tracker(struct conn *c)
1060 struct tracker *t = c->tracker;
1063 DLOG("put_tracker: no tracker?");
1067 if (t->active_conns <= 0)
1069 DLOG("put_tracker: no counter?");
1074 DTRACE("TBF: Put tracker (%d conns remain)", t->active_conns);
1077 static void run_as_daemon(int do_fork)
1079 int sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1084 if (setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
1085 die("setsockopt: %m");
1087 struct sockaddr_in sa = {
1088 .sin_family = AF_INET,
1089 .sin_port = ntohs(1969),
1090 .sin_addr.s_addr = INADDR_ANY,
1092 if (bind(sk, (struct sockaddr *) &sa, sizeof(sa)) < 0)
1094 if (listen(sk, 128) < 0)
1096 // if (fcntl(sk, F_SETFL, O_NONBLOCK) < 0)
1097 // die("fcntl: %m");
1106 FILE *f = fopen(PID_FILE, "w");
1109 fprintf(f, "%d\n", pid);
1116 setresgid(GID, GID, GID);
1117 setresuid(UID, UID, UID);
1121 struct sigaction sact = {
1122 .sa_handler = sigchld_handler,
1123 .sa_flags = SA_RESTART,
1125 if (sigaction(SIGCHLD, &sact, NULL) < 0)
1126 die("sigaction: %m");
1128 DLOG("Daemon ready");
1129 setproctitle("minsk: Listening");
1130 openlog("minsk", LOG_PID, LOG_LOCAL7);
1134 struct pollfd pfd[1] = {
1135 { .fd = sk, .events = POLLIN },
1138 int nfds = poll(pfd, 1, 60000);
1139 if (nfds < 0 && errno != EINTR)
1148 while ((pid = waitpid(-1, &status, WNOHANG)) > 0)
1150 if (!WIFEXITED(status) || WEXITSTATUS(status))
1151 DLOG("Process %d exited with strange status %x", pid, status);
1153 struct conn *conn = pid_to_conn(pid);
1156 DTRACE("Connection with PID %d exited", pid);
1161 DTRACE("PID %d exited, matching no connection", pid);
1164 if (!(pfd[0].revents & POLLIN))
1167 socklen_t salen = sizeof(sa);
1168 int sk2 = accept(sk, (struct sockaddr *) &sa, &salen);
1178 DTRACE("Got connection: fd=%d", sk2);
1180 struct conn *conn = get_conn(&sa.sin_addr);
1181 const char *reason = NULL;
1184 if (!get_tracker(conn))
1186 DLOG("Connection from %s dropped: Throttling", inet_ntoa(sa.sin_addr));
1189 reason = "--- Sorry, but you are sending too many requests. Please slow down. ---\n";
1194 DLOG("Connection from %s dropped: Too many connections", inet_ntoa(sa.sin_addr));
1195 reason = "--- Sorry, maximum number of connections exceeded. Please come later. ---\n";
1201 DLOG("fork failed: %m");
1210 DLOG("Accepted connection from %s", inet_ntoa(sa.sin_addr));
1211 setproctitle("minsk: %s", inet_ntoa(sa.sin_addr));
1216 DLOG("Sending error message to %s", inet_ntoa(sa.sin_addr));
1217 setproctitle("minsk: %s ERR", inet_ntoa(sa.sin_addr));
1218 write(sk2, reason, strlen(reason));
1223 DTRACE("Created process %d", pid);
1230 static void init_memory(void)
1232 // For the contest, we fill the whole memory with -00 00 0000 0000 (HALT),
1233 // not +00 00 0000 0000 (NOP). Otherwise, an empty program would reveal
1234 // the location of the password :)
1235 for (int i=0; i<4096; i++)
1236 mem[i] = 01000000000000ULL;
1238 // Store the password
1240 mem[pos++] = 0574060565373;
1241 mem[pos++] = 0371741405340;
1242 mem[pos++] = 0534051524017;
1245 int main(int argc, char **argv)
1251 setproctitle_init(argc, argv);
1252 if (!strcmp(argv[1], "--daemon"))
1254 else if (!strcmp(argv[1], "--net"))
1257 die("Usage: minsk [--daemon | --net]");