PiDP-8/I Software

Changes On Branch release
Log In

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch release Excluding Merge-Ins

This is equivalent to a diff from 5ec88693ac to 73038fadf8

2021-02-15
07:59
Small tweaks to the release process doc. check-in: d28caab153 user: tangent tags: trunk
07:04
Merged yet more changes for v20210214 in Leaf check-in: 73038fadf8 user: tangent tags: release, v20210214
06:57
Reworked the logic in the new "bosi build nls" code so it copies any missing images from UV, rather than blindly copy all of them only when the first one is missing. This lets you re-run the script later, relying on it to fill in the gaps before starting on the expensive parts of the build. check-in: 5ec88693ac user: tangent tags: trunk
06:53
Fixed a misplaced curly brace in previous check-in: 59e778933e user: tangent tags: trunk
03:31
Merged still more trunk tweaks in check-in: 280c662a13 user: tangent tags: release, v20210214

Changes to doc/cc8-manual.md.

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
...
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
...
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
...
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
...
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
...
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
...
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774


775
776
777
778
779
780
781
...
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
....
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292

1293
1294





1295
1296
1297
1298
1299
1300
1301
....
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
....
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463

1464
1465
1466
1467
1468
1469
1470
1471

1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
....
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
....
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678

1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
....
1691
1692
1693
1694
1695
1696
1697


1698
1699
1700
1701
1702
1703
1704
....
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
system utilities that otherwise would have been written in assembly. A C
language compiler first appeared publicly in Version 2 Unix, released
later in 1972. Much of PDP-11 Unix remained written in assembly until
its developers decided to rewrite the operating system in C, for Version
4 Unix, released in 1973. That decision allowed Unix to be relatively
easily ported to a wholly different platform — the Interdata 8/32 — in
1978 by writing a new code generator for the C compiler, then
cross-compiling everything. That success in porting Unix led to C’s own
success first as a systems programming language, and then later as a
general-purpose programming language.

Although we are not likely to use CC8 to write a portable operating
system for the PDP-8, it is powerful enough to fill C’s original niche
in writing system utilities for a preexisting OS written in assembly.

................................................................................
[sms]:  http://so-much-stuff.com/pdp8/C/C.php


## Requirements

The CC8 system generally assumes the availability of:

*   [At least 16 kWords of core](#memory) at run time for programs
    compiled with CC8.  The [native OS/8 CC8 compiler passes](#ncpass)
    require 20 kWords to compile programs.

    CC8 provides no built-in way to use more memory than this, so you
    will probably have to resort to [inline assembly](#asm) or FORTRAN
    II library linkage to get access to more than 16 kWords of core.

................................................................................
            ...
        }

1.  **Recursion:** See [`FIB.C`][fib] for an example of this.

1.  **Simple arithmetic operators:** `+`, `-`, `*`, `/`, etc.

1.  **Bitwise operators:** `&`, `|`, `~` and `!`

1.  **Simple comparison operators:** False expressions evaluate as 0 and
    true as -1 in two’s complement form, meaning all 1's in binary form.
    See the list of limitations below for the operators excluded by our
    "simple" qualifier.

1.  **2-character operators:** `++`, `--`, `==`, `!=`,`>=`, `<=`, `&&`,
    and `||`. Note that `++` and `--` are postfix only, and
    that `&&` and `||` are [implemented as `&` and `|`](#2cbo).

1.  **Ternary operator:** The `?:` operator works as of May 2020; it may
    be nested.

1.  **Limited library:** See [below](#libc) for a list of library
    functions provided, including their known limitations relative to
    Standard C.

    There are many limitations in this library relative to Standard C or
    even K&R C, which are documented below.

1.  **Limited structuring constructs:** `if`, `while`, `for`, etc. are
    supported. There is a nesting limit of 10 which is rarely exceeded in 
    most applications. In addition, `switch` statements are now supported
    via a code re-write in the C pre-processor (cc.sv). See  [`FORTH.C`][forth]
    for an example.

[fib]:   /doc/trunk/src/os8/examples/fib.c
[forth]: /doc/trunk/src/os8/examples/forth.c


<a id="nlim" name="limitations"></a>
### Known Limitations of the OS/8 CC8 Compiler

The OS/8 version of CC8 supports a subset of the C dialect understood by
[the cross-compiler](#cross), and thus of K&R C:

1.  <a id="typeless"></a>The language is typeless in that everything is
    a 12 bit integer, and any variable/array can interpreted as `int`,
    `char` or pointer.  All variables and arrays must be declared as
    `int`. As with K&R C, the return type may be left off of a
    function's definition; it is implicitly `int` in all cases.

    It is not necessary to give argument types when declaring function
    arguments, but you must declare a return type with the OS/8 CC8
    compiler:

        int myfn(n) { /* do something with n */ }

    This declares a function taking an `int` called `n` and returning
    an `int`.
    
    Contrast the CC8 cross-compiler, which requires function argument
    types to be declared but not the return type, per K&R C rules:

        int myfn(n)
        int n;
        {
            /* do something with n, then _maybe_ return something */
        }

    The type int is mandatory for all functions.

    The cross-compiler supports `void` as an extension to K&R C. This type


    is converted to `int` in the pre-processor. Similarly, the type `char` is
    converted. These type may be used for readability purposes.

2.  There must be an `int main()`, and it must be the last function
    in the single input C file.

    Since OS/8 has no way to pass command line arguments to a program
    — at least, not in a way that is compatible with the Unix style
    command lines expected by C — the `main()` function is never
................................................................................
        (The native compiler emits startup code automatically, and it
        hard-codes the LIBC call table in the [final compiler
        pass](#ncpass), implemented in `p8.c`, so it doesn’t need
        `#include` to make these things work.)

    *   No conditional compilation: `#if`, `#ifdef`, `#else`, etc.

    *   [Inline assmembly](#asm) via `#asm` / `#endasm`. See
        [`FIB.C`][fib] for an example

5.  Variables are implicitly `static`, even when local.

6.  Arrays may only be single indexed. See `PS.C` for an example.

7.  The compiler does not yet understand how to assign a variable's
    initial value as part of its declaration. This:
................................................................................
        int i = 5;

    must instead be:

        int i;
        i = 5;

8.  <a name="2cbo"></a>`&&` and `||` work, but because they
    are internally converted to `&` and `|`, their precedence has
    changed, and they do not short-circuit as in a conforming C
    compiler.

    You can work around such differences with clever coding. For
    example, this code for a conforming C compiler:

        if (i != 0 || j == 5)

    should be rewritten for CC8 to avoid the precedence changes as:

        if (!(i == 0) || (j == 5))

    because a true result in each subexpression yields -1 per the
    previous point, which when bitwise OR'd together means you get -1 if
    either subexpression is true, which means the whole expression
    evaluates to true if either subexpression is true.

    If the code you were going to write was instead:
................................................................................
    Regular `while` loops work, as does `break`, so one workaround for a
    lack of `do/while` is:

        while (1) { /* do something useful */; if (cond) break; }

    We have no intention to fix this.

12. As of May 2020, `switch` is implemented via re-write to cascading
    `if`/`then` statements. There are a number of limitations to this
    approach that a CC8 user should be aware of.

    The primary one to keep in mind is that that if you use a
    memory-mutating expression in the `switch` clause with a conforming
    C compiler, it is evaluated just once at the start of the block, but
    in CC8, it is evaluated once for each generated `if` sub-expression
    that the code visits. That is, you should not say things like this
    in code meant to be compiled with the CC8 native compiler:

        switch (*p++) {...}

    Say instead:

        int temp = *p++;
        switch (temp) {....}

    Also, there **must** be a `default` case, and cases (including the
    default case) must be terminated with a `break`. CC8 does not allow
    for cases that fall through to the following case. The following
    code has at least three syntax errors:

        switch (x) {
            case 1:  foo();
            case 2:  bar();
            default: qux();
        }

13. `sizeof()` is not implemented.



<a id="warning"></a>
#### GOVERNMENT HEALTH WARNING

**You are hereby warned**: The native OS/8 compiler does not contain any
error checking whatsoever. If the source files contain an error or you
................................................................................

The bulk of the Standard C Library is not provided, including some
functions you’d think would go along nicely with those we do provide,
such as `feof()` or `fseek()`.  Keep in mind that the library is
currently restricted to [a single 4&nbsp;kWord field](#memory), and we
don’t want to lift that restriction. Since the current implementation
nearly fills that space, it is unlikely that we’ll add much more
functionality beyond the currently provided 33 LIBC functions plus [the
9 additional functions](#addfn). If we ever fix any of the limitations
we’ve identified below, consider it “gravy” rather than any kind of
obligation fulfilled.

Some of these missing functions are less useful in the CC8 world than in
more modern C environments. The low-memory nature of this world
encourages writing loops over [word strings](#wordstr) in terms of
pointer arithmetic and implicit zero testing (e.g. `while (*p++) { /*
use p */ }`) rather than make expensive calls to `strlen()`, so that
function isn’t provided.
................................................................................

[cppr]:    https://en.cppreference.com/w/c
[iot]:     /wiki?name=IOT+Device+Assignments
[libch]:   /doc/trunk/src/cc8/include/libc.h
[libcsrc]: /doc/trunk/src/cc8/os8/libc.c


### <a id="atoi"></a>`int atoi(s, *result)`

Takes a null-terminated ASCII character string pointer `s` and tries to
interpret it as a 12-bit PDP-8 two’s complement signed integer, storing
the value in `*result` and returning the number of bytes in `s`
consumed.

**Standard Violations:**

*   Instead of returning the converted integer, this function stores
    that value in `*result`.

*   Whereas `atoi()` in Standard C returns the converted value, in this
    function, `s[retval]` is the first invalid — non-sign, non-digit,
    non-space — character in the string, where `retval` is the return
    value.

*   Skips leading ASCII 32 (space) characters only, not those matched by
    [`isspace()`](#isspace), as the Standard requires.




### <a id="cupper"></a>`cupper(p)`

Implements this loop more efficiently:

    char* tmp = p;
................................................................................

*   There appears to be a bug in the current implementation that
    requires you to open the input file before opening an output file
    when you need both.  It may not be possible to fix this within the
    current limitations on the library, but if you come up with
    something, [we accept patches][hakp].

[hakp]: /doc/trunk/CONTRIBUTING.md#patches


### <a id="fprintf"></a>`fprintf(fmt, args...)`

Writes its arguments (`args`...) to the currently-opened output file
according to format string `fmt`.

................................................................................
    of characters written so far, not a negative value as the Standard
    requires.  In the case of `sprintf()`, this means the trailing NUL
    character will not be written!

*   There is no `snprintf()`, `vprintf()`, etc.


### <a id="scanf" name="fscanf"></a>`fscanf`, `scanf`, `sscanf`

Parse strings according to a `printf`-like format specification. `scanf`
gets the string from the interactive terminal, `fscanf` gets it from a

file opened with [`fopen()`](#fopen), and `sscanf` gets it from a
NUL-terminated C string already in core.






**DOCUMENTATION INCOMPLETE**


### <a id="strcat"></a>`strcat(dst, src)`

Concatenates one [0-terminated word string](#wordstr) to the end of
................................................................................
### <a id="xinit"></a>`xinit()`

Prints the CC8 compiler’s banner message. This is in LIBC only because
it’s called from several places within CC8 itself.

**Nonstandard.**


## <a id="addfn"></a>Additional Utility Routines

The functions that CC8 uses to manipulate the software stack are also
available to be called by end-user programs: `PUSH`, `POP`, `PUTSTK`,
`POPRET`, and `PCALL`. The page zero pointers for this stack are
initialized by code in `header.sb`, which is injected into your
program’s startup sequence during compilation.

In addition, there are a set of functions that may be used to provide
temporary storage in field 4, acting like a temporary binary file:

`void iinit(int address)`: Reset the file pointer to an arbitrary
address range 0-4095.

`void stri(int value)`: Store ‘value’ at the current address, and
increment the address pointer.

`int strl()`: Read the word at the current address, and do not increment
the address.

`int strd()`: Read the word at the current address, and increment the
address.

As field 4 is not used by OS/8, your program may use the entire field.
This library code does not check for overflow: going beyond address 4095
will simply wrap to address 0.



<a id="examples"></a>
## Trying the Examples

The standard PiDP-8/I OS/8 RK05 boot disk contains several example
C programs that the OS/8 version of CC8 is able to compile.

................................................................................
Pascal’s triangle without using factorials, which are a bit out of
range for 12 bits!

The other examples preinstalled are:

*   **<code>calc.c</code>** - A simple 4-function calculator program.

*   **<code>pd.c</code>** - Shows methods for doing double-precision
    (i.e. 24-bit) integer calculations.

*   **<code>hlb.c</code>** - Generates [Hilbert curves][hc] on a Tek4010
    series display using raw terminal codes. Therefore, you must be
    running a Tek4010 emulator when running this program, else you will
    get garbage on the display!

*   **<code>fib.c</code>** - Calculates the first 10 Fibonacci numbers.
    This implicitly demonstrates CC8's ability to handle recursive
    function calls.

*   **<code>basic.c</code>** - A simple Basic interpreter used to test
    a simple recursive expression processor.


*   **<code>forth.c</code>** - A simple Forth interpreter used to test
    switch statemments etc.

The two interpeters are quite complex, particularly the Forth
interpreter, which contains 300 lines of code and implements a number of
basic Forth functions. This example is intended to show what can be
crammed into 4k of core.



Another set of examples not preinstalled on the OS/8 disk are
`examples/pep001-*.c`, which are described [elsewhere][pce].

[hc]:  https://en.wikipedia.org/wiki/Hilbert_curve
[pce]: /wiki?name=PEP001.C


## <a id="exes"></a>Making Executables 

Executing `CCR.BI` loads, links, and runs your C program without
producing an executable file on disk.  You need only a small variation
................................................................................

**Field 1:** The user data field (UDF): globals, literals, and stack

**Field 2:** The program's executable code

**Field 3:** The LIBC library code

**Field 4:** (Optional) see the binary utilities above (stri...).

### <a id="os8res"></a>OS/8 Reservations

The uppermost page of fields 0 thru 2 hold the
[resident portion of OS/8][os8res] and therefore must not be touched by
a program built with CC8 while running under OS/8. For example, the
[OS/8 keyboard monitor][os8kbd] re-entry point is at 07600₈, [the output
................................................................................
[sbrk]: https://pubs.opengroup.org/onlinepubs/7908799/xsh/brk.html
[v6ux]: https://en.wikipedia.org/wiki/Version_6_Unix
[v7ux]: https://en.wikipedia.org/wiki/Version_7_Unix


### <a id="vonn"></a>There Are No Storage Type Distinctions

Literals are placed in the same field as globals and the call stack,
rather that inline within the generated executable code. This may cause
surprise size limitations of the user programs.


CC8 does it this way because the FORTRAN II / SABR system does allow any
initialisation of COMMON storage in field 1, so the literals have to be
stored in the user program page and then be copied into field 1 at
program initialization time.  Various pointers to these regions are
mainatined by the compiler.


### <a id="sover"></a>Stack Overflow

Since CC8 places the call stack immediately after the last literal
stored in core, a program with many globals and/or literals will have
less usable stack space than a program with fewer of each.
................................................................................

Neither version of CC8 generates code to detect stack overflow. If you
try to push too much onto the stack, it will simply begin overwriting
the page OS/8 is using at the top of field 1. If you manage to blow the
stack by more than a page without crashing the program or the computer
first, the [stack pointer will wrap around](#ptrwrap) and the stack will
begin overwriting the first page of field 1.




### <a id="flayout"></a>Field Layout, Concrete Example

The field layout given [at the start of this section](#memory) is not
fixed. The linking loader is free to use any layout it likes, consistent
with any constraints in the input binaries. You can use the `/M` option
................................................................................
|`DCAI` |3400 |same as `DCA I` in PAL8|
|`JMSI` |4400 |same as `JMS I` in PAL8|
|`JMPI` |5400 |same as `JMP I` in PAL8|
|`MQL`  |7421 |load MQ from AC, clear AC|
|`ACL`  |7701 |load AC from MQ (use `CLA SWP` to give inverse of `MQL`)|
|`MQA`  |7501 |OR MQ with AC, result in MQ|
|`SWP`  |7521 |swap AC and MQ|
|`DILX` |6053 |set VC8E X coordinate (used by [`dispxy()`](#dispxy))|
|`DILY` |6054 |set VC8E Y coordinate|
|`DIXY` |6054 |pulse VC8E at (X,Y) set by `DIXY`,`DILY`|
|`CDF0` |6201 |change DF to field 0|
|`CDF1` |6211 |change DF to field 1|
|`CAF0` |6203 |change both IF and DF to field 0|
|`RIF`  |6224 |read instruction field: OR IF with bits 6-8 of AC|
|`BSW`  |7002 |exchange the high and low 6 bits of AC|







|







 







|







 







|






|
<
<
<
<
<









|
|
<
<

<
|
>













|
|
<

|





|

|


|


<
<
|
>
>
|
<







 







|
<







 







|
|
|
|

|
|



|

|







 







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







|
<
|
|







 







|

|
|
|
<



<
<
<
<
<
<
<
<


>
>







 







|







 







|

|
<
>
|
<
>
>
>
>
>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







<
<
<
<
<
<
<
<




|
|
<
>
|
|
<
<
<
<
<
<
>




<







 







<







 







|
|
<

>
|
|
|
|
|







 







>
>







 







|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
..
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
...
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
...
420
421
422
423
424
425
426
427

428
429
430
431
432
433
434
...
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
...
488
489
490
491
492
493
494
495






























496
497
498
499
500
501
502
...
656
657
658
659
660
661
662
663

664
665
666
667
668
669
670
671
672
...
708
709
710
711
712
713
714
715
716
717
718
719

720
721
722








723
724
725
726
727
728
729
730
731
732
733
...
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
....
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243

1244
1245

1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
....
1347
1348
1349
1350
1351
1352
1353





























1354
1355
1356
1357
1358
1359
1360
....
1369
1370
1371
1372
1373
1374
1375








1376
1377
1378
1379
1380
1381

1382
1383
1384






1385
1386
1387
1388
1389

1390
1391
1392
1393
1394
1395
1396
....
1423
1424
1425
1426
1427
1428
1429

1430
1431
1432
1433
1434
1435
1436
....
1580
1581
1582
1583
1584
1585
1586
1587
1588

1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
....
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
....
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
system utilities that otherwise would have been written in assembly. A C
language compiler first appeared publicly in Version 2 Unix, released
later in 1972. Much of PDP-11 Unix remained written in assembly until
its developers decided to rewrite the operating system in C, for Version
4 Unix, released in 1973. That decision allowed Unix to be relatively
easily ported to a wholly different platform — the Interdata 8/32 — in
1978 by writing a new code generator for the C compiler, then
cross-compiling everything. That success in porting Unix lead to C’s own
success first as a systems programming language, and then later as a
general-purpose programming language.

Although we are not likely to use CC8 to write a portable operating
system for the PDP-8, it is powerful enough to fill C’s original niche
in writing system utilities for a preexisting OS written in assembly.

................................................................................
[sms]:  http://so-much-stuff.com/pdp8/C/C.php


## Requirements

The CC8 system generally assumes the availability of:

*   [At least 12&nbsp;kWords of core](#memory) at run time for programs
    compiled with CC8.  The [native OS/8 CC8 compiler passes](#ncpass)
    require 20&nbsp;kWords to compile programs.

    CC8 provides no built-in way to use more memory than this, so you
    will probably have to resort to [inline assembly](#asm) or FORTRAN
    II library linkage to get access to more than 16&nbsp;kWords of core.

................................................................................
            ...
        }

1.  **Recursion:** See [`FIB.C`][fib] for an example of this.

1.  **Simple arithmetic operators:** `+`, `-`, `*`, `/`, etc.

1.  **Bitwise operators:** `&`, &brvbar;, `~` and `!`

1.  **Simple comparison operators:** False expressions evaluate as 0 and
    true as -1 in two’s complement form, meaning all 1's in binary form.
    See the list of limitations below for the operators excluded by our
    "simple" qualifier.

1.  **A few 2-character operators:** `++`, `--` (postfix only) and `==`.






1.  **Limited library:** See [below](#libc) for a list of library
    functions provided, including their known limitations relative to
    Standard C.

    There are many limitations in this library relative to Standard C or
    even K&R C, which are documented below.

1.  **Limited structuring constructs:** `if`, `while`, `for`, etc. are
    supported, but they may not work as expected when deeply nested or
    in long `if/else if/...` chains.




[fib]: /doc/trunk/src/cc8/examples/fib.c


<a id="nlim" name="limitations"></a>
### Known Limitations of the OS/8 CC8 Compiler

The OS/8 version of CC8 supports a subset of the C dialect understood by
[the cross-compiler](#cross), and thus of K&R C:

1.  <a id="typeless"></a>The language is typeless in that everything is
    a 12 bit integer, and any variable/array can interpreted as `int`,
    `char` or pointer.  All variables and arrays must be declared as
    `int`. As with K&R C, the return type may be left off of a
    function's definition; it is implicitly `int` in all cases.

    Because the types are already known, it is not necessary to give
    types when declaring function arguments:


        myfn(n) { /* do something with n */ }

    This declares a function taking an `int` called `n` and returning
    an `int`.
    
    Contrast the CC8 cross-compiler, which requires function argument
    types to be declared, if not the return type, per K&R C rules:

        myfn(n)
        int n;
        {
            /* do something with n */
        }



    The cross-compiler supports `void` as an extension to K&R C, but the
    native compiler does not, and it is not yet smart enough to flag
    code including it with an error. It will simply generate bad code
    when you try to use `void`.


2.  There must be an `int main()`, and it must be the last function
    in the single input C file.

    Since OS/8 has no way to pass command line arguments to a program
    — at least, not in a way that is compatible with the Unix style
    command lines expected by C — the `main()` function is never
................................................................................
        (The native compiler emits startup code automatically, and it
        hard-codes the LIBC call table in the [final compiler
        pass](#ncpass), implemented in `p8.c`, so it doesn’t need
        `#include` to make these things work.)

    *   No conditional compilation: `#if`, `#ifdef`, `#else`, etc.

    *   [Inline assmembly](#asm) via `#asm`.


5.  Variables are implicitly `static`, even when local.

6.  Arrays may only be single indexed. See `PS.C` for an example.

7.  The compiler does not yet understand how to assign a variable's
    initial value as part of its declaration. This:
................................................................................
        int i = 5;

    must instead be:

        int i;
        i = 5;

8.  There is no `&&` nor &brvbar;&brvbar;, nor are there plans to add
    them in the future.  Neither is there support for complex relational
    operators like `>=` nor even `!=`.  Abandon all hope for complex
    assignment operators like `+=`.

    Most of this can be worked around through clever coding. For
    example, this:

        if (i != 0 || j == 5)

    could be rewritten to avoid both missing operators as:

        if (!(i == 0) | (j == 5))

    because a true result in each subexpression yields -1 per the
    previous point, which when bitwise OR'd together means you get -1 if
    either subexpression is true, which means the whole expression
    evaluates to true if either subexpression is true.

    If the code you were going to write was instead:
................................................................................
    Regular `while` loops work, as does `break`, so one workaround for a
    lack of `do/while` is:

        while (1) { /* do something useful */; if (cond) break; }

    We have no intention to fix this.

12. `switch` doesn't work.
































<a id="warning"></a>
#### GOVERNMENT HEALTH WARNING

**You are hereby warned**: The native OS/8 compiler does not contain any
error checking whatsoever. If the source files contain an error or you
................................................................................

The bulk of the Standard C Library is not provided, including some
functions you’d think would go along nicely with those we do provide,
such as `feof()` or `fseek()`.  Keep in mind that the library is
currently restricted to [a single 4&nbsp;kWord field](#memory), and we
don’t want to lift that restriction. Since the current implementation
nearly fills that space, it is unlikely that we’ll add much more
functionality beyond the currently provided 33 functions. If we ever fix

any of the limitations we’ve identified below, consider it “gravy”
rather than any kind of obligation fulfilled.

Some of these missing functions are less useful in the CC8 world than in
more modern C environments. The low-memory nature of this world
encourages writing loops over [word strings](#wordstr) in terms of
pointer arithmetic and implicit zero testing (e.g. `while (*p++) { /*
use p */ }`) rather than make expensive calls to `strlen()`, so that
function isn’t provided.
................................................................................

[cppr]:    https://en.cppreference.com/w/c
[iot]:     /wiki?name=IOT+Device+Assignments
[libch]:   /doc/trunk/src/cc8/include/libc.h
[libcsrc]: /doc/trunk/src/cc8/os8/libc.c


### <a id="atoi"></a>`atoi(s, outlen)`

Takes a null-terminated ASCII character string pointer `s` and returns a
12-bit PDP-8 two’s complement signed integer. The length of the numeric
string is returned in `*outlen`.


**Standard Violations:**









*   Skips leading ASCII 32 (space) characters only, not those matched by
    [`isspace()`](#isspace), as the Standard requires.

*   The `outlen` parameter is nonstandard.


### <a id="cupper"></a>`cupper(p)`

Implements this loop more efficiently:

    char* tmp = p;
................................................................................

*   There appears to be a bug in the current implementation that
    requires you to open the input file before opening an output file
    when you need both.  It may not be possible to fix this within the
    current limitations on the library, but if you come up with
    something, [we accept patches][hakp].

[hakp]: /doc/trunk/HACKERS.md#patches


### <a id="fprintf"></a>`fprintf(fmt, args...)`

Writes its arguments (`args`...) to the currently-opened output file
according to format string `fmt`.

................................................................................
    of characters written so far, not a negative value as the Standard
    requires.  In the case of `sprintf()`, this means the trailing NUL
    character will not be written!

*   There is no `snprintf()`, `vprintf()`, etc.


### <a id="sscanf"></a>`sscanf`

Reads formatted input from a file.


**Standard Violations:**


*   `[f]scanf()` is not provided. Call [`[f]gets()`](#gets) to get a
    string and then call `sscanf()` on it.

*   This list cannot possibly be complete.

**DOCUMENTATION INCOMPLETE**


### <a id="strcat"></a>`strcat(dst, src)`

Concatenates one [0-terminated word string](#wordstr) to the end of
................................................................................
### <a id="xinit"></a>`xinit()`

Prints the CC8 compiler’s banner message. This is in LIBC only because
it’s called from several places within CC8 itself.

**Nonstandard.**































<a id="examples"></a>
## Trying the Examples

The standard PiDP-8/I OS/8 RK05 boot disk contains several example
C programs that the OS/8 version of CC8 is able to compile.

................................................................................
Pascal’s triangle without using factorials, which are a bit out of
range for 12 bits!

The other examples preinstalled are:

*   **<code>calc.c</code>** - A simple 4-function calculator program.









*   **<code>fib.c</code>** - Calculates the first 10 Fibonacci numbers.
    This implicitly demonstrates CC8's ability to handle recursive
    function calls.

If you look in `src/cc8/examples`, you will find these same programs
plus `basic.c`, a simple BASIC language interpreter. This one is

not preinstalled because its complexity is currently beyond the
capability of the OS/8 version of CC8. To build it, you will have
to use [the cross-compiler](#cross), then assemble the resulting






`basic.sb` file under OS/8.

Another set of examples not preinstalled on the OS/8 disk are
`examples/pep001-*.c`, which are described [elsewhere][pce].


[pce]: /wiki?name=PEP001.C


## <a id="exes"></a>Making Executables 

Executing `CCR.BI` loads, links, and runs your C program without
producing an executable file on disk.  You need only a small variation
................................................................................

**Field 1:** The user data field (UDF): globals, literals, and stack

**Field 2:** The program's executable code

**Field 3:** The LIBC library code



### <a id="os8res"></a>OS/8 Reservations

The uppermost page of fields 0 thru 2 hold the
[resident portion of OS/8][os8res] and therefore must not be touched by
a program built with CC8 while running under OS/8. For example, the
[OS/8 keyboard monitor][os8kbd] re-entry point is at 07600₈, [the output
................................................................................
[sbrk]: https://pubs.opengroup.org/onlinepubs/7908799/xsh/brk.html
[v6ux]: https://en.wikipedia.org/wiki/Version_6_Unix
[v7ux]: https://en.wikipedia.org/wiki/Version_7_Unix


### <a id="vonn"></a>There Are No Storage Type Distinctions

It may surprise you to learn that literals are placed in the same field
as globals and the call stack.


Other C compilers place literals in among the executable code instead, a
fact that’s especially helpful on [Harvard architecture
microcontrollers][harch] with limited RAM. We don’t do it that way in
CC8 because literals are implemented in terms of the SABR `COMMN`
feature, which in turn is how OS/8 FORTRAN II implements `COMMON`. These
subsystems have no concept of “storage type” as in modern C compilers.


### <a id="sover"></a>Stack Overflow

Since CC8 places the call stack immediately after the last literal
stored in core, a program with many globals and/or literals will have
less usable stack space than a program with fewer of each.
................................................................................

Neither version of CC8 generates code to detect stack overflow. If you
try to push too much onto the stack, it will simply begin overwriting
the page OS/8 is using at the top of field 1. If you manage to blow the
stack by more than a page without crashing the program or the computer
first, the [stack pointer will wrap around](#ptrwrap) and the stack will
begin overwriting the first page of field 1.

[harch]: https://en.wikipedia.org/wiki/Harvard_architecture


### <a id="flayout"></a>Field Layout, Concrete Example

The field layout given [at the start of this section](#memory) is not
fixed. The linking loader is free to use any layout it likes, consistent
with any constraints in the input binaries. You can use the `/M` option
................................................................................
|`DCAI` |3400 |same as `DCA I` in PAL8|
|`JMSI` |4400 |same as `JMS I` in PAL8|
|`JMPI` |5400 |same as `JMP I` in PAL8|
|`MQL`  |7421 |load MQ from AC, clear AC|
|`ACL`  |7701 |load AC from MQ (use `CLA SWP` to give inverse of `MQL`)|
|`MQA`  |7501 |OR MQ with AC, result in MQ|
|`SWP`  |7521 |swap AC and MQ|
|`DILX` |6053 |set VC8E X coordinate (used by [`dispxy()`](#dispxy)|
|`DILY` |6054 |set VC8E Y coordinate|
|`DIXY` |6054 |pulse VC8E at (X,Y) set by `DIXY`,`DILY`|
|`CDF0` |6201 |change DF to field 0|
|`CDF1` |6211 |change DF to field 1|
|`CAF0` |6203 |change both IF and DF to field 0|
|`RIF`  |6224 |read instruction field: OR IF with bits 6-8 of AC|
|`BSW`  |7002 |exchange the high and low 6 bits of AC|

Changes to examples/pep001.bas.

1
2
3
4
5
6
7
8
9
10
11
12
1 REM Copyright (c) 2016 by Warren Young
2 REM Released under the terms of ../SIMH-LICENSE.md
3 REM ------------------------------------------------------------------
10 FOR I = 1 TO 999
20 A = I / 3 \ B = I / 5
30 IF INT(A) = A GOTO 60
40 IF INT(B) = B GOTO 60
50 GOTO 70
60 T = T + I
70 NEXT I
80 PRINT "TOTAL: "; T
90 END
<
<
<












1
2
3
4
5
6
7
8
9



10 FOR I = 1 TO 999
20 A = I / 3 \ B = I / 5
30 IF INT(A) = A GOTO 60
40 IF INT(B) = B GOTO 60
50 GOTO 70
60 T = T + I
70 NEXT I
80 PRINT "TOTAL: "; T
90 END

Added media/etos/etosv5b-demo.rk05.

cannot compute difference between binary files

Changes to src/pidp8i/gpio-common.c.in.

1
2
3
4
5
6
7
8
9
10
11
..
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
...
235
236
237
238
239
240
241
242
243
244
245

246











247
248
249
250
251
252
253
/*
 * gpio-common.c: functions common to both gpio.c and gpio-nls.c
 *
 * Copyright © 2015 Oscar Vermeulen, © 2016-2019 by Warren Young
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
................................................................................
 * by the other gpio-* modules, from the GPIO thread.
*/

#include "pidp8i.h"

#include <config.h>

#if defined(HAVE_BCM_HOST_H)
#   include <bcm_host.h>
#endif

#include <pthread.h>
#include <sys/file.h>
#include <sys/time.h>

#include <ctype.h>
#include <errno.h>
#include <signal.h>
................................................................................
        }
        pidp8i_gpio_present = 0;
    }
}


//// bcm_host_get_peripheral_address ///////////////////////////////////
// Provide fallback for non-Pi case to avoid a link error.

#if !defined(HAVE_BCM_HOST_H)
    static unsigned bcm_host_get_peripheral_address(void) { return 0; }

#endif













//// DOUBLE BUFFERED DISPLAY MANIPULATION FUNCTIONS ////////////////////

//// swap_displays ////////////////////////////////////////////////////
// Clear the current "paint-from" display, then exchange the double-
// buffered display pointers atomically, saving the current update-to



|







 







<
<
<
<







 







|

<
|
>
|
>
>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
..
34
35
36
37
38
39
40




41
42
43
44
45
46
47
...
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
/*
 * gpio-common.c: functions common to both gpio.c and gpio-nls.c
 *
 * Copyright © 2015 Oscar Vermeulen, © 2016-2018 by Warren Young
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
................................................................................
 * by the other gpio-* modules, from the GPIO thread.
*/

#include "pidp8i.h"

#include <config.h>





#include <pthread.h>
#include <sys/file.h>
#include <sys/time.h>

#include <ctype.h>
#include <errno.h>
#include <signal.h>
................................................................................
        }
        pidp8i_gpio_present = 0;
    }
}


//// bcm_host_get_peripheral_address ///////////////////////////////////
// Find Pi's GPIO base address


static unsigned bcm_host_get_peripheral_address(void)
{
    unsigned address = ~0;
    FILE *fp = fopen("/proc/device-tree/soc/ranges", "rb");
    if (fp)
    {   unsigned char buf[4];
        fseek(fp, 4, SEEK_SET);
        if (fread(buf, 1, sizeof buf, fp) == sizeof buf)
            address = buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3] << 0;
        fclose(fp);
    }

    return address == ~0 ? 0x20000000 : address;
}


//// DOUBLE BUFFERED DISPLAY MANIPULATION FUNCTIONS ////////////////////

//// swap_displays ////////////////////////////////////////////////////
// Clear the current "paint-from" display, then exchange the double-
// buffered display pointers atomically, saving the current update-to

Changes to tools/bosi.

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
#!/bin/bash
# bosi - The Binary OS Image creation/update script
#
# Copyright © 2016-2021 by Warren Young
# 
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS LISTED ABOVE BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
# THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# 
# Except as contained in this notice, the names of the authors above shall
# not be used in advertising or otherwise to promote the sale, use or
# other dealings in this Software without prior written authorization from
# those authors.


# Display the usage message
function usage() {
    cat <<USAGE
usage: $0 <verb> [tag]

    The available verbs are init, build, prepare, image, and finish.

    You may include a tag parameter with the 'image' and 'finish' verbs
    to override the default tag ('ils') used in image and zip file
    outputs.

    See RELEASE-PROCESS.md for more info.

USAGE
    exit 1
}

verb="$1"
tag="$2"
test -n "$verb" || usage


test -z "$tag" && tag=ils

nu=pidp8i
nh=/home/$nu
repo=pidp8i
dldir="$HOME/tangentsoft.com/dl"
os=buster-lite
img=$dldir/pidp8i-$(date +%Y.%m.%d)-$tag-$os.img

greadlink=$(type -p greadlink || type -p readlink)
this=$($greadlink -f $0)
topdir="$($greadlink -f "$(dirname "$this")"/..)"


# Give user a few seconds to read the final messages before rebooting or
# powering off.
function do_wait() {
    n=8
    cat <<MSG
    
$1 in $n seconds...


MSG
    sleep $n
}


# Initial steps
function do_init() {


    if [ "$USER" != "root" ]
    then
        echo "The init step has to be run as root.  The explanation is"
        echo "given in the section for 'init' in RELEASE-PROCESS.md."
        echo
        exit 1
    fi

    set -x

    apt-get update && apt-get -y upgrade || true
    apt-get -y install fossil python3-pip python3-pexpect python3-yaml || true

    test -f /usr/include/curses.h || apt-get -y install libncurses-dev

    if [ ! -e "$nh" ]
    then
        # First pass on a clean SD card: rename 'pi' user and group to
        # 'pidp8i' and rename its home directory to match.
        pkill -u pi
        usermod  -l $nu -d $nh -m pi 

        groupmod -n $nu pi


    fi

    reboot


}


# Clone repo and build the software under [new] pidp8i account

function do_build() {
    if [ "$USER" != "$nu" ]
    then
        echo "The build step has to be run as $nu."
        echo
        exit 1
    fi



    set -x


    if [ ! -d museum ]
    then
        mkdir -p museum $repo
        fossil clone -u https://tangentsoft.com/$repo museum/$repo.fossil
    fi

    cd $repo

    if [ -r ChangeLog.md ]
    then
        fossil revert           # just in case
        fossil update release
    else
        fossil open ~/museum/$repo.fossil release
        fossil set autosync pullonly
        ./configure
    fi

    # The NLS build can reuse the ILS build's OS/8 images, saving a huge
    # amount of build time.
    if [ "$tag" = "nls" ]
    then
        for f in '' '-dist' '-patched'
        do
            for g in ock v3d
            do
                src="${g}${f}.rk05"
                dst="bin/${g}${f}.rk05"
                test -r bin/v3d.rk05 || fossil uv export "$src" "$dst"
            done
        done
    fi

    tools/mmake
    bin/teco-pi-demo -b             # test and benchmark simulator
    sudo make install || true       # don't care about return code
    do_wait "Rebooting"
    sudo reboot
}


# This script prepares the OS's configuration to a clean first boot state.
function do_prepare() {
    if [ "$USER" != "$nu" ]
    then
        echo "The prepare step has to be run as $nu."
        echo
        exit 1
    fi

    set -x

    history -c ; rm -f ~/.bash_history


    pidp8i stop || true                         # avoid sim hogging CPU
    sudo systemctl enable ssh || true           # disabled by default
    sudo shred -u /etc/ssh/*key* || true        # allow multiple passes
    sudo dphys-swapfile uninstall || true
    sudo dd if=/dev/zero of=/junk bs=1M || true # it *will* error-out!
    sudo rm -f /junk



    cl=/boot/cmdline.txt
    if ! grep -Fq ' init=' $cl
    then
        sudo sed -i -e 's#$# init=/usr/lib/raspi-config/init_resize.sh#' $cl
    fi

    # Schedule an automatic shutdown using the existing sudo creds so
    # the next step can invalidate them without requiring a re-reset.
    /usr/sbin/shutdown -h +1

    # Must be last, else later "sudo" will fail on the expired password
    echo 'pidp8i:edsonDeCastro1968' | sudo chpasswd &&
        sudo passwd -e pidp8i
}







# This script images the OS SD card in a USB reader on a macOS box.




function do_image() {
    dev=UNKNOWN
    ps=UNKNOWN
    hb=no
    rp=UNKNOWN


    while read line
    do
        case $line in
            /dev/*)
                dev=$(echo $line | cut -f1 -d' ')
                ;;







            0:*)
                case $line in
                    *FDisk_partition_scheme*) ps=fdisk ;;
                    *) dev= ;;      # can't be the OS SD card
                esac
                ;;








            1:*)
                case $line in
                    *Windows_FAT_32\ boot*) hb=yes ;;
                    *) dev= ;;      # can't be the OS SD card
                esac
                ;;

            2:*)
                case $line in
                    *Linux*) rp=Linux ; break ;; # found it!
                    *) dev= ;;      # can't be the OS SD card
                esac
                ;;
        esac
    done < <(diskutil list)

    if [ -z "$dev" ]
    then
        cat <<MSG
Failed to find OS SD card!  I learned the following, though:



    SD /dev node:     $dev
    Partition scheme: $ps
    Has /boot:        $hb
    /root partition:  $rp


MSG




        exit 1
    fi

    echo
    echo "-------------------------------------------------------"
    diskutil info "$dev"
    echo "-------------------------------------------------------"
    echo
    read -p "Is that the OS SD card? [y/N]: " answer
    case $answer in
        [Yy]*) ;;
        *) exit 1
    esac

    rdev=${dev/disk/rdisk}              # speeds zeroing and re-imaging

    mf=/tmp/MANIFEST.txt
    readme=/tmp/README.md
    cp "$topdir/doc/OS-images.md" $readme

    set -x





    sudo diskutil unmountDisk $dev      # it auto-mounted
    time sudo dd if=$rdev bs=1m of=$img
    sum=($(shasum -a 256 "$img"))
    bytes=($(wc -c $img))

    cat > $mf <<MF
SHA-256 hash and size of ${sum[1]}:

Hash:  ${sum[0]}
Size:  ${bytes[0]}
MF

    imgdir="$(dirname "$img")"
    sed -i '' -e "s_$imgdir/__" "$mf"   # nix local paths in manifest
    unix2dos $mf                        # might be opened on Windows

    time zip -9j $img.zip $img $mf $readme
    rm -f $mf $readme

    # Now re-image the card, starting with a zeroed card to ensure a
    # clean test.  Ignore the end-of-device error from the zero step.
    sudo echo -n       # avoid counting sudo blocking time in next cmd
    time sudo dd if=/dev/zero of=$rdev bs=1m || true
    time sudo dd if=$img of=$rdev bs=1m
    diskutil unmountDisk $dev || true   # Paragon ExtFS might be installed



}


# Clean up after the above
function do_finish() {
    set -x

    trash $img
    cd $dldir/..
    make synch


















}


# Main routine
set -e
case "$verb" in
    in*) do_init ;;
    bu*) do_build ;;
    pr*) do_prepare ;;

    im*) do_image ;;
    fi*) do_finish ;;
    *)   usage ;;
esac
|

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
<
>
>
|





|

>


<


<
<
<
<
<
<
<
<
<
<
<
<
<
<


>
>
|
|
|
|
|
|
|

<
<
<
<
<
<
<
<
<
<
<
<
|
>
|
>
>
|

<
>
>



<
>
|
<
<
<
<
<
<
>
>

<
>

|
|
|
|
|

|

|
|
|
|
|
|
<
|
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
|



|
|
<
<
<
<
<
<
<
<
<
|
>

<
<
|
|
|
|
>
>
|
<
<
<
<
<

<
<
<

<
<
<
<
>
>
|
>
>
>
|
<
>
>
>
>
|
<
<
<
<
>

<
<
<
<
<
<
>
>
>
>
>
>
|
<
<
<
<
<
<
>
>
>
>
>
>
>
|
<
<
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
|
<
>
>

<
<
<
<
>

<
>
>
>
>
|
|
|
<
<
<
<
<
<
<
<
<
<

<

<
<
<
<
<
<
>
>
>
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
|
<

<
<
<
<
|
|
>
>
>





<
<
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|
|
|
>
|
|
|

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
#!/bin/bash -x
# bosi - The Binary OS Image creation/update script













































verb="$1"
object="$2"


tag=$(echo $verb | cut -f2 -d- -s)
test -z "$tag" && tag=all

nu=pidp8i
nh=/home/$nu
repo=pidp8i
dldir="$HOME/tangentsoft.com/dl"
os=jessie-lite
img=$dldir/pidp8i-$(date +%Y.%m.%d)-$tag-$os.img
rdisk=/dev/rdisk10
greadlink=$(type -p greadlink || type -p readlink)
this=$($greadlink -f $0)

















# Initial steps
function do_init() {
	if ! getent passwd $nu > /dev/null
	then
		if [ "$USER" != "root" ]
		then
			echo "The init step has to be run as root."
			echo "See RELEASE-PROCESS.md."
			echo
			exit 1
		fi













		usermod \
			-d $nh \
			-l $nu \
			-p $(openssl passwd -1 edsonDeCastro1968) \
			-m pi 
	fi


	sudo apt-get update && sudo apt-get -y upgrade || true
	do_fossil
}



# Fossil clone, build and install
function do_fossil() {






	test "$USER" = "root" && exec sudo -i -u $nu $nh/bosi fossil $object
	cd $HOME


	test -n "$(type -p fossil)" || sudo apt-get -y install fossil

	if [ ! -d museum ]
	then
		mkdir -p museum $repo
		fossil clone https://tangentsoft.com/$repo museum/$repo.fossil
	fi

	cd $repo

	if [ -r ChangeLog.md ]
	then
		fossil revert			# just in case
		fossil update $object
	else
		fossil open ~/museum/$repo.fossil $object

		./configure
	fi
















	make -j4

	sudo make install || true

	sudo reboot
}


# This script resets the OS's configuration to a clean first boot state.
function do_reset() {









	history -c ; rm -f ~/.bash_history
	test "$USER" = "root" || exec sudo $this reset



	shred -u /etc/ssh/*key*
	dphys-swapfile uninstall
	dd if=/dev/zero of=/junk bs=1M || true		# it *will* error-out!
	rm /junk
	passwd -e pidp8i
	( sleep 1 ; poweroff ) & exit
}














# Shrink the filesystem on the SD card we're about to image to just a
# bit bigger than required to hold its present contents.
#
# The extra 100 megs in the arithmetic below accounts for the /boot
# partition, since the `resizepart` command takes a partition end value,
# not a size value.
#

# We don't calculate the actual end of the /boot partition and use that
# value because we want a bit of slack space to buy time for an end user
# who neglects to expand the card image into the free space available on
# their SD card after first boot.
function do_shrink() {




	test "$USER" = "root" || exec sudo $this shrink $object







	umount /dev/sda2 || true	# might auto-mount, might not
	e2fsck -f /dev/sda2			# resize2fs demands it
	blocks=$(
		resize2fs -M /dev/sda2 2>&1 |
		grep 'blocks long' | 
		grep -wo '[0-9]\+'
	)






	if [ "$blocks" -gt 0 ]
	then
		parted /dev/sda resizepart 2 $(($blocks * 4096 + 10**8))b
		blocks=$(
			resize2fs /dev/sda2 2>&1 |
			grep 'blocks long' | 
			grep -wo '[0-9]\+'
		)


















		cat <<NEXT

Move the USB SD card reader to the desktop machine and resume the
process with





    bosi image $blocks


NEXT
	else
		echo "Failed to extract new filesystem size from resize2fs!"
		echo
		exit 1
	fi
}



















# This script images the SD card in a USB reader on a Mac OS X box.
function do_image() {
	if [ -n "$object" ]
	then
		sudo diskutil unmountDisk $rdisk		# it auto-mounted














		sudo dd if=$rdisk bs=4k count=$object of=$img
		zip -9j $img.zip $img






		sudo dd if=$img of=$rdisk bs=1m
		sudo diskutil unmountDisk $rdisk || true	# Paragon ExtFS might be installed
	else
		usage
	fi
}


# Clean up after the above
function do_finish() {


	rmtrash $img
	cd $dldir/..
	make synch
}


# Display the usage message
function usage() {
	cat <<USAGE
usage: $0 <verb[-tag]> [object]

    The available verbs are init, fossil, shrink, image, and finish.

    You may append a tag to the image and finish verbs (e.g. image-nls)
    to override the default tag ('all') used in image and zip file
    outputs.

    The object depends on the verb.  See RELEASE-PROCESS.md.

USAGE
	exit 1
}


# Main routine
set -e
case "$verb" in
	in*) do_init ;;
	fo*) do_fossil ;;
	re*) do_reset ;;
	sh*) do_shrink ;;
	im*) do_image ;;
	fi*) do_finish ;;
	*)   usage ;;
esac