System call table

A system call passes through a system-call table: the kernel uses the call number to find the handler, after it checks that the number is valid.

What to build

Run a list of system calls through a four-entry table and count them.

Requirements

  • Call 0 (getpid) returns 1234 whatever its argument is. Call 1 (block_offset) returns arg * 512. Call 2 (twice) returns arg * 2. Call 3 (previous) returns arg - 1.
  • Any other call number is a bad call. Print number -> bad call and do not count it as a good call.
  • For a good call print number -> result. At the end print counts: c0 c1 c2 c3 (how many good calls of each number) and bad: B.

Input

The first line has q (1 ≤ q ≤ 40). Each of the next q lines has a call number (−5 to 9) and an argument (0 to 10000).

Output

One line per call as described, then the counts: line and the bad: line.

Constraints

The result always fits in an int.

Example

Input:

4
0 0
1 7
9 0
2 21

Output:

0 -> 1234
1 -> 3584
9 -> bad call
2 -> 42
counts: 1 1 1 0
bad: 1

Why it works

The number is only an index. A table of function pointers turns it into a call in one step, and the range check is what keeps a program from jumping to an address the kernel never meant to offer. Real kernels have a few hundred entries and check them the same way.

Examples

Example 1 · Input
4
0 0
1 7
9 0
2 21
Expected output
0 -> 1234
1 -> 3584
9 -> bad call
2 -> 42
counts: 1 1 1 0
bad: 1
Example 2 · Input
2
3 100
3 1
Expected output
3 -> 99
3 -> 0
counts: 0 0 0 2
bad: 0

Hints

Hint 1

Make an array of four function pointers, or use a switch. Check that the number is between 0 and 3 before you call.

Hint 2

Keep an array counts[4]. Add 1 to counts[number] only for good calls; count bad ones in a separate variable.

Hint 3

A bad number prints bad call and never reaches any function.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int sys_getpid(int arg) { (void)arg; return 1234; }
int sys_block_offset(int arg) { return arg * 512; }
int sys_twice(int arg) { return arg * 2; }
int sys_previous(int arg) { return arg - 1; }

int (*table[4])(int) = { sys_getpid, sys_block_offset, sys_twice, sys_previous };

int main(void) {
    int q, number, arg;
    int counts[4] = {0, 0, 0, 0}, bad = 0;
    scanf("%d", &q);
    for (int i = 0; i < q; i++) {
        scanf("%d %d", &number, &arg);
        if (number < 0 || number > 3) {
            printf("%d -> bad call\n", number);
            bad++;
        } else {
            counts[number]++;
            printf("%d -> %d\n", number, table[number](arg));
        }
    }
    printf("counts: %d %d %d %d\n", counts[0], counts[1], counts[2], counts[3]);
    printf("bad: %d\n", bad);
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: What an operating system does →