333 Commits

Author SHA1 Message Date
Ben Gras
2ec255bb5e fix from trunk: don't re-use mountpoints 2010-06-11 11:43:31 +00:00
Ben Gras
cd445fe22a assert conditions fix from trunk. 2010-06-09 12:56:44 +00:00
Ben Gras
64b1205e6c fix from trunk for assert(ptproc == newptproc) without vm_stop on shutdown. 2010-06-07 22:24:21 +00:00
Ben Gras
94881e6d4a make includes fix from trunk 2010-06-07 15:51:50 +00:00
Ben Gras
6677a8c8e0 mfs fix by tveerman from trunk. 2010-06-07 15:46:26 +00:00
Arun Thomas
255ad2ab37 Remove gcc-4.1.1 from packages list 2010-06-04 12:40:15 +00:00
Ben Gras
7dc782dd1a from trunk:
------------------------------------------------------------------------
r7154 | thruby | 2010-06-04 10:54:43 +0000 (Fri, 04 Jun 2010) | 1 line

Removed a buggy assert unintentionally commted in r7044
2010-06-04 11:06:44 +00:00
Ben Gras
e9eb2c4f8b 3.1.7 branch. 2010-06-03 11:33:56 +00:00
Cristiano Giuffrida
332842295a Always skip signals for PM itself when broadcasting. 2010-06-03 11:18:43 +00:00
Ben Gras
035c5a369c move drivers/random SHA implementation to libutil and header to <minix/sha2.h> 2010-06-02 22:58:29 +00:00
Kees van Reeuwijk
36e12d5bd8 Use endpoint_t for the destination of mini_send and _syscall, and the
source of mini_receive.

Also some small cleanup.
2010-06-02 21:51:32 +00:00
Gianluca Guida
0a42d36ac6 Fix ftp client's passive mode.
Before the ioctl the code zeroed the wrong variable.
2010-06-02 21:12:54 +00:00
Kees van Reeuwijk
ed0b81c25c Removed some unused variables and functions. 2010-06-02 19:41:38 +00:00
Erik van der Kouwe
fc29251444 setup: default root partition size is 64MB, reinstall keeps old root size 2010-06-02 17:07:10 +00:00
Tomas Hruby
463be393c2 Gracefull crash if FPU exception in kernel 2010-06-02 13:59:55 +00:00
Ben Gras
495970a17c boot monitor: introduce a 'reset' command that causes the cpu to
reset (triple fault).
2010-06-02 13:23:15 +00:00
Tomas Hruby
7bfa47476c Fixed stack trace if panic in stop_context() 2010-06-02 08:53:49 +00:00
Arun Thomas
ec27911a7f Ramdisk makefile update 2010-06-01 15:11:43 +00:00
Arun Thomas
2fd1f18803 Release script: Remove .d/.depend files from CD 2010-06-01 14:44:36 +00:00
Thomas Veerman
6bbcab3ec4 Clean up MFS a bit:
- Remove unused includes.
 - Add include guards to headers.
 - Use unsigned variables in case they're never going to hold a negative
   value. This causes GCC's complaints to disappear and should make flexelint
   a lot happier, too.
 - Make functions private when they're used only within a module.
 - Remove unused variables.
 - Add casts where appropriate.
2010-06-01 12:35:33 +00:00
Ben Gras
cc6fed4c51 packages: don't put oss on cd. 2010-06-01 11:11:35 +00:00
Arun Thomas
8579c59b3f Minor makefile changes for GCC 2010-06-01 09:41:31 +00:00
Tomas Hruby
40f440b8cd KCall methods do not depend on m_source and m_type fields
- substituted the use of the m_source message field by
  caller->p_endpoint in kernel calls. It is the same information, just
  passed more intuitively.
  
- the last dependency on m_type field is removed.
  
- do_unused() is substituted by a check for NULL.

- this pretty much removes the depency of kernel calls on the general
  message format. In the future this may be used to pass the kcall
  arguments in a different structure or registers (x86-64, ARM?) The
  kcall number may be passed in a register already.
2010-06-01 08:54:31 +00:00
Tomas Hruby
ebbd319ac0 do_safecopy split
- removes dependency of do_safecopy() on the m_type field of the kcall
  messages.

- instead of do_safecopy() figuring out what action is requested, the
  correct safecopy method is called right away.
2010-06-01 08:51:37 +00:00
Erik van der Kouwe
8bca982581 Remove those annoying $Id and $Revision tags 2010-05-31 20:00:08 +00:00
Thomas Veerman
5d78cefaf2 Clean up PFS 2010-05-28 09:39:18 +00:00
Erik van der Kouwe
8d06457241 Remove obsolete _fpu_present variable from crtso.S 2010-05-27 09:46:42 +00:00
Erik van der Kouwe
a31e9b0400 Oops, committed too much 2010-05-27 09:20:50 +00:00
Erik van der Kouwe
fc7438181b Avoid use of C++ reserved word class in headers (reported by Aki Goto, tracker item 375) 2010-05-27 09:18:49 +00:00
Erik van der Kouwe
43b589c1cc Avoid use of C++ reserved word class in headers (reported by Aki Goto, tracker item 375) 2010-05-27 08:48:53 +00:00
Arun Thomas
b48b037fbe Reorganize some directories
servers/hgfs/hgfs_server => servers/hgfs
servers/hgfs/libhgfs => lib/libhgfs
servers/rs/service => commands/service
drivers/memory/memory_driver => drivers/memory
drivers/memory/ramdisk => drivers/ramdisk
2010-05-26 22:49:57 +00:00
Arun Thomas
007104d60e GCC build fixes/updates
-Set stack sizes for boot image processes
-Increase RS stack size
-Reduce ramdisk size
-HARDWARE task should use kernel stack
-Minor asm tweaks for leading underscores
2010-05-26 18:45:55 +00:00
David van Moolenbroek
b16fc7e7bf different rtl8169 shutdown code 2010-05-26 11:22:06 +00:00
David van Moolenbroek
7f98ba962a make IS report masked IRQs properly 2010-05-26 08:44:50 +00:00
Tomas Hruby
24764ff47a Fixed ms-based scheduling for legacy timer 2010-05-26 08:20:29 +00:00
Tomas Hruby
a8111c5027 Various small scheduling related fixes 2010-05-26 07:16:39 +00:00
David van Moolenbroek
51ff10d7c0 reset alarm timer on PRIVCTL 2010-05-26 07:10:28 +00:00
Tomas Hruby
451a6890d6 scheduling - time quantum in miliseconds
- Currently the cpu time quantum is timer-ticks based. Thus the
  remaining quantum is decreased only if the processes is interrupted
  by a timer tick. As processes block a lot this typically does not
  happen for normal user processes. Also the quantum depends on the
  frequency of the timer.

- This change makes the quantum miliseconds based. Internally the
  miliseconds are translated into cpu cycles. Everytime userspace
  execution is interrupted by kernel the cycles just consumed by the
  current process are deducted from the remaining quantum.

- It makes the quantum system timer frequency independent.

- The boot processes quantum is loosely derived from the tick-based
  quantas and 60Hz timer and subject to future change

- the 64bit arithmetics is a little ugly, will be changes once we have
  compiler support for 64bit integers (soon)
2010-05-25 08:06:14 +00:00
Kees van Reeuwijk
ac14a989b3 Fixed some inconsistent strict typing declarations.
Better strict typing.
2010-05-25 07:23:24 +00:00
David van Moolenbroek
2a8961cdac fix int64.3 man page formatting 2010-05-24 21:10:37 +00:00
Erik van der Kouwe
1f11a57141 Oops, last commit included more than was intended 2010-05-20 08:07:47 +00:00
Erik van der Kouwe
5f15ec05b2 More system processes, this was not enough for the release script to run on some configurations 2010-05-20 08:05:07 +00:00
Erik van der Kouwe
456a125e00 Minor patch: increase size of root partition for minimal release, eve very small additions with -c made it fail 2010-05-19 20:11:22 +00:00
Arun Thomas
b0159ad168 Buildsystem changes for GCC
-Makefile updates
-Update mkdep
-Build fixes/warning cleanups for some programs
-Restore leading underscores on global syms in kernel asm files
-Increase ramdisk size
2010-05-19 13:24:15 +00:00
Ben Gras
bcdaf033b5 pm - fix sched interaction
For coredumping processes, PM forgets to inform SCHED that the
process has vanished, causing future fork()s to fail.
2010-05-19 13:22:29 +00:00
Erik van der Kouwe
77d5243f4a More sensible description for EPERM from http://www.opengroup.org/onlinepubs/000095399/basedefs/errno.h.html 2010-05-19 11:51:49 +00:00
Ben Gras
38ece51b25 charset cp1251 contributed by Roman Ignatov. 2010-05-19 11:34:47 +00:00
Ben Gras
987d3e6d85 packages: gcc-libs renamed, include gcc-4.4.3 2010-05-19 10:22:57 +00:00
Ben Gras
6d0e53c2ca use oxpcie only if enabled to avoid baud bottleneck of uart. 2010-05-19 10:18:46 +00:00
Ben Gras
9ba760e603 kernel: oxpcie serial card support.
ask to map in oxpcie i/o memory and support serial i/o for it in the
kernel. set oxpcie=<address> in boot monitor (retrieve address using
pci_debug=1 output). (no sanity checking is done on the address
currently.) disabled by default.

The change also contains some other minor cleanup (a new serial.h to set
register info common to UART and the OXPCIe card, in-kernel memory
mapping a little more structured and env_get() to get sysenv variables
without knowing about the params_buffer).
2010-05-19 10:00:02 +00:00
Tomas Hruby
dcc81d73e8 boot image - no need for entry point
- removes the initial_pc from struct boot_image. It is always set
  to 0 and RS uses a.out headers.
2010-05-18 13:51:46 +00:00
Tomas Hruby
b09bcf6779 Scheduling server (by Bjorn Swift)
In this second phase, scheduling is moved from PM to its own
scheduler (see r6557 for phase one). In the next phase we hope to a)
include useful information in the "out of quantum" message and b)
create some simple scheduling policy that makes use of that
information.

When the system starts up, PM will iterate over its process table and
ask SCHED to take over scheduling unprivileged processes. This is
done by sending a SCHEDULING_START message to SCHED. This message
includes the processes endpoint, the parent's endpoint and its nice
level. The scheduler adds this process to its schedproc table, issues
a schedctl, and returns its own endpoint to PM - as the endpoint of
the effective scheduler. When a process terminates, a SCHEDULING_STOP
message is sent to the scheduler.

The reason for this effective endpoint is for future compatibility.
Some day, we may have a scheduler that, instead of scheduling the
process itself, forwards the SCHEDULING_START message on to another
scheduler.

PM has information on who schedules whom. As such, scheduling
messages from user-land are sent through PM. An example is when
processes change their priority, using nice(). In that case, a
getsetpriority message is sent to PM, which then sends a
SCHEDULING_SET_NICE to the process's effective scheduler.

When a process is forked through PM, it inherits its parent's
scheduler, but is spawned with an empty quantum. As before, a request
to fork a process flows through VM before returning to PM, which then
wakes up the child process. This flow has been modified slightly so
that PM notifies the scheduler of the new process, before waking up
the child process. If the scheduler fails to take over scheduling,
the child process is torn down and the fork fails with an erroneous
value.

Process priority is entirely decided upon using nice levels. PM
stores a copy of each process's nice level and when a child is
forked, its parent's nice level is sent in the SCHEDULING_START
message. How this level is mapped to a priority queue is up to the
scheduler. It should be noted that the nice level is used to
determine the max_priority and the parent could have been in a lower
priority when it was spawned. To prevent a CPU intensive process from
hawking the CPU by continuously forking children that get scheduled
in the max_priority, the scheduler should determine in which queue
the parent is currently scheduled, and schedule the child in that
same queue.

Other fixes: The USER_Q in kernel/proc.h was incorrectly defined as
NR_SCHED_QUEUES/2. That results in a "off by one" error when
converting priority->nice->priority for nice=0. This also had the
side effect that if someone were to set the MAX_USER_Q to something
else than 0, then USER_Q would be off.
2010-05-18 13:39:04 +00:00
Tomas Hruby
b90c2d7026 rename of mode/context switching functions
- this patch only renames schedcheck() to switch_to_user(),
  cycles_accounting_stop() to context_stop() and restart() to
  +restore_user_context()

- the motivation is that since the introduction of schedcheck() it has
  been abused for many things. It deserves a better name.  It should
  express the fact that from the moment we call the function we are in
  the process of switching to user.

- cycles_accounting_stop() was originally a single purpose function.
  As this function is called at were convenient places it is used in
  for other things too, e.g. (un)locking the kernel. Thus it deserves
  a better name too.

- using the old name, restart() does not call schedcheck(), however
  calls to restart are replaced by calls to schedcheck()
  [switch_to_user] and it calls restart() [restore_user_context]
2010-05-18 13:00:39 +00:00
David van Moolenbroek
9ba65d2ea8 This patch switches the MINIX3 ethernet driver stack from a port-based
model to an instance-based model. Each ethernet driver instance is now
responsible for exactly one network interface card. The port field in
/etc/inet.conf now acts as an instance field instead.

This patch also updates the data link protocol. This update:
- eliminates the concept of ports entirely;
- eliminates DL_GETNAME entirely;
- standardizes on using m_source for IPC and DL_ENDPT for safecopies;
- removes error codes from TASK/STAT replies, as they were unused;
- removes a number of other old or unused fields;
- names and renames a few other fields.

All ethernet drivers have been changed to:
- conform to the new protocol, and exactly that;
- take on an instance number based on a given "instance" argument;
- skip that number of PCI devices in probe iterations;
- use config tables and environment variables based on that number;
- no longer be limited to a predefined maximum of cards in any way;
- get rid of any leftover non-safecopy support and other ancient junk;
- have a correct banner protocol figure, or none at all.

Other changes:
* Inet.conf is now taken to be line-based, and supports #-comments.
  No existing installations are expected to be affected by this.
* A new, select-based asynchio library replaces the old one.
  Kindly contributed by Kees J. Bot.
* Inet now supports use of select() on IP devices.
  Combined, the last two changes together speed up dhcpd
  considerably in the presence of multiple interfaces.
* A small bug has been fixed in nonamed.
2010-05-17 22:22:53 +00:00
Erik van der Kouwe
f5bce90216 Add -M release.sh option to write out a symbol map, either to /usr/src on the image (without -m) or to the tools directory (with -m) 2010-05-17 16:52:48 +00:00
Erik van der Kouwe
7570df267f Full 64-bit multitplication and division added to u64 library 2010-05-17 16:44:26 +00:00
Arun Thomas
5fa734b708 Awk build tweaks
-Make yacc invocation "less chatty to stderr" (again)
-Generate proctab.c (again)
2010-05-13 19:29:42 +00:00
Arun Thomas
869a181025 Buildsystem tweaks
Set build output verbosity level down to 1.
Make the 'install' target depend on the 'all' and 'depend' targets.
2010-05-13 13:26:27 +00:00
Arun Thomas
8630337c80 Fix permissions for halt, reboot, and shutdown 2010-05-13 12:05:53 +00:00
Erik van der Kouwe
6244867b11 xargs does not support the -f flag 2010-05-12 19:17:17 +00:00
Arun Thomas
5706670029 Convert boot/ and commands/ over to bsdmake 2010-05-12 16:28:54 +00:00
David van Moolenbroek
ce386974bc DS: base number of data entries on NR_SYS_PROCS 2010-05-12 13:21:15 +00:00
Ben Gras
bfc9c5c3a8 kernel: small ammendment to pagefault-in-kernel panic 2010-05-12 08:56:11 +00:00
Ben Gras
c5c25e7abc kernel/vm: change pde table info from single buffer to explicit per-process.
makes code in kernel more readable, and allows better sanity checking on
using the pde info.
2010-05-12 08:31:05 +00:00
Cristiano Giuffrida
23204787d5 - Fixed a bug when running out of priv structures.
- Tell VM about VM calls for every new service instance.
2010-05-11 20:49:42 +00:00
Ben Gras
7c5e1d1b29 kernel - don't print info about scheduled process if pagefault happened in kernel. 2010-05-11 15:14:10 +00:00
David van Moolenbroek
713454aca7 fix multiport support in ethernet drivers 2010-05-10 20:19:55 +00:00
Erik van der Kouwe
b7bf2733d6 Intermediate boot verbosity level EXTRA (2), MAX moved to 3 2010-05-10 18:07:59 +00:00
Erik van der Kouwe
d4188dcd5c New options for release script: -m to make tiny image, ZIP to set compressor 2010-05-10 18:02:15 +00:00
Tomas Hruby
d3e991a7b6 PM signal handling check too strict
- this panic may be unnecessarily triggered if PM gets the delayed
  stop signal from kernel before it gets reply from VFS to the UNPAUSE
  call.

- after this change PM does not proceed to delivering the signal until
  the reply from VFS is received. Perhaps PM could deliver the signal
  straight away as it knows that the process does not run. Possibly
 i dangerous.

- the signal is deliverd immediately after the UNPAUSE reply as the
  pending signals are always checked at the moment.
2010-05-10 14:27:22 +00:00
Tomas Hruby
5c63cac05a Removed defines not used since r6844. 2010-05-10 13:29:04 +00:00
Tomas Hruby
6e25ad8b0a Use of all NIL_* defines converted to NULL 2010-05-10 13:26:00 +00:00
Ben Gras
a1636b85b7 kernel: new DEBUG_RACE option. try to provoke race conditions between processes.
it does this by 
  - making all processes interruptible by running out of quantum
  - giving all processes a single tick of quantum
  - picking a random runnable process instead of in order, and
    from a single pool of runnable processes (no priorities)

This together with very high HZ values currently provokes some race conditions
seen earlier only when running with SMP.
2010-05-08 18:00:03 +00:00
Ben Gras
d5a0af826a vm: use arch_map2str to print pagefault info, to properly display code addrs 2010-05-08 17:25:54 +00:00
Ben Gras
72335b7642 kernel: print spurious interrupt message with increasing interval. 2010-05-08 17:21:37 +00:00
Tomas Hruby
7c334e2670 RS - fixed timeouts
- rs does not assume hz==60

- rs adjusts its timeout ticks by the system clock frequency

- drivers have time to reply if hz is set too high (e.g. 1000+) for
  instance when debugging
2010-05-07 18:12:16 +00:00
Tomas Hruby
ae9222a72b pci synchronous start up
- fixes a race between rs and pci
2010-05-07 16:23:07 +00:00
Tomas Hruby
4f962b4798 A small mini_receive() cleanup
- this patch substitutes *xpp for sender to increase readability of
  mini_receive().

- makes sure that the dequeued sender has p_q_link == NULL and that
  this condition holds when enqueuing the sender again. 

- it is a sanity check to make sure that the new sender is not
  enqueued already. Before this change the dequeued sender's p_q_link
  may not be NULL and it was only set to NULL when enqueued again.
2010-05-07 11:22:49 +00:00
Ben Gras
b8eddf00d8 kernel: don't try to lookup ANY in debug output. 2010-05-06 22:39:11 +00:00
Ben Gras
0194fe55dc kernel: increase some per-process privilege limits. 2010-05-06 22:21:08 +00:00
Cristiano Giuffrida
5a98cd3e92 Fix Inet initialization race. 2010-05-06 22:18:21 +00:00
Thomas Veerman
0aceb25535 Small cleanup of dead and/or redundant code. 2010-05-06 09:32:40 +00:00
Ben Gras
b6bb75963b vm: remove leftover diag print 2010-05-05 15:26:48 +00:00
Ben Gras
86e1b9d770 fsctl.h doesn't exist. 2010-05-05 11:49:41 +00:00
Ben Gras
f78d8e74fd secondary cache feature in vm.
A new call to vm lets processes yield a part of their memory to vm,
together with an id, getting newly allocated memory in return. vm is
allowed to forget about it if it runs out of memory. processes can ask
for it back using the same id. (These two operations are normally
combined in a single call.)

It can be used as a as-big-as-memory-will-allow block cache for
filesystems, which is how mfs now uses it.
2010-05-05 11:35:04 +00:00
Kees van Reeuwijk
51d46f8e46 Let memory allocation be aligned on 8-byte boundaries. 2010-05-04 21:02:44 +00:00
Ben Gras
09958abda8 tty: don't use custom kputc; this fixes tty printf()s. 2010-05-04 09:26:01 +00:00
Ben Gras
75b2153b9a awk Makefile: make yacc less chatty to stderr. 2010-05-04 09:23:31 +00:00
Ben Gras
ca86603cd6 libc: malloc: don't enable SLOWDEBUG by default 2010-05-03 22:54:51 +00:00
Ben Gras
029e809780 driver.h: increase max no. of open minors. 2010-05-03 19:43:54 +00:00
Erik van der Kouwe
1137ba9b32 Extra assertions on free if SLOWDEBUG is enabled: check whether the block exists and has not been freed before 2010-05-03 19:42:08 +00:00
Erik van der Kouwe
4b34ff6903 Add syslib function to obtain CPU frequency 2010-05-03 19:41:04 +00:00
Tomas Hruby
ec56479675 deadlock() - more info
- deadlock() is more verbose in case of a detected deadlock. First, it
  lists all processses in the deadlock group. Then it prints the proc
  extra info, not only  stack trace and register dump
2010-05-03 17:38:54 +00:00
Tomas Hruby
57a88ce708 debugging - printing processes on serial
- this patch moves the former printslot() from arch_system.c to
  debug.c and reimplements it slightly. The output is not changed,
  however, the process information is printed in a separate function
  print_proc() in debug.c as such a function is also handy in other
  situations and should be publicly available when debugging.
2010-05-03 17:37:18 +00:00
Thomas Veerman
4ae9c03147 - Add test52 to test FPU context switching
- Make test/run count how many tests it's going to perform instead of having to
  manually update it ourselves.
2010-05-03 15:12:39 +00:00
Kees van Reeuwijk
cfd28b671a Put the munmap and munmap_text trampolines in a separate .S file, so that they can be overridden independenly of mmap. 2010-04-29 20:12:56 +00:00
Kees van Reeuwijk
a2a0562a9c Make mdb compile in other places than just /usr/src. 2010-04-29 20:05:01 +00:00
Ben Gras
99a13341bd cpufeature() - rename _SSEx and correct logic in cpufeature() in lib 2010-04-29 19:08:49 +00:00
Erik van der Kouwe
3bf54e9b2b Allow loading images > 16M 2010-04-29 15:14:07 +00:00
Ben Gras
4e837dcfb3 kernel: more diagnostics for privctl ENOMEM conditions. 2010-04-29 08:50:52 +00:00
Ben Gras
4ac5eb7832 rs: stacktrace if system process exits early. 2010-04-29 08:50:17 +00:00
Cristiano Giuffrida
83ef7119f6 Don't panic when out of priv structures. 2010-04-28 20:41:23 +00:00
Erik van der Kouwe
93f3bf5bda Fix wrong word 2010-04-28 20:37:08 +00:00
Ben Gras
603ed23ebd at_wini: remove unnecessary quirks debug message 2010-04-28 14:19:40 +00:00
Ben Gras
50335291ae kernel: fpu_init: only enable OSXMMEXCPT in CR4 on at least SSE1 machines.
Found and debugged by totalinux at yandex.ru and Evgeniy Ivanov, thanks!
2010-04-28 13:51:02 +00:00
Ben Gras
c37401f23f kernel: fpu init to separate function; also move fpu init down
moving the fpu code causes exceptions raised by it to be trapped
neatly instead of causing a triple fault, before the IDT is initialized.
2010-04-28 13:25:29 +00:00
Thomas Veerman
f9317dc039 Scan all processes for that might be blocked on a lock 2010-04-28 11:54:22 +00:00
Ben Gras
b65ebdffac at_wini: more general system to allow devices that behave like ata controllers.
(let silicon image sata controller that is pci class 1, subclass 0x80,
but works as a sata controller, work as such.)
2010-04-28 11:52:28 +00:00
Ben Gras
72e866db48 pci: don't do sanity check for missing pci bus, the check can misfire. 2010-04-28 11:51:13 +00:00
Ben Gras
5d870f020d tty: try more often to get the config byte. 2010-04-28 11:50:54 +00:00
Erik van der Kouwe
d17590fcf4 Avoid sbrk (in favour of malloc) in RS where possible 2010-04-28 08:35:54 +00:00
Erik van der Kouwe
84d404aba3 Fix types in debug register functions 2010-04-28 08:35:05 +00:00
Erik van der Kouwe
8e918c407a Enable malloc assertions 2010-04-28 08:34:19 +00:00
Erik van der Kouwe
1b7de33a68 Add timeout for test 7 to indicate which test (if any) hangs 2010-04-28 08:33:23 +00:00
Tomas Hruby
b528d52ea8 pagefault() is private 2010-04-27 20:30:33 +00:00
Ben Gras
d11b88cfc5 mtree: no more /lib and /lib/i386. 2010-04-27 13:44:48 +00:00
Erik van der Kouwe
a033e6fcae Add missing newline at end of file 2010-04-27 13:30:46 +00:00
Erik van der Kouwe
4bddc57477 Remove debug printfs in breakpoints.c, they should never have been there 2010-04-27 12:25:04 +00:00
Cristiano Giuffrida
0164957abb Unified crash recovery and live update.
RS CHANGES:
- Crash recovery is now implemented like live update. Two instances are kept
side by side and the dead version is live updated into the new one. The endpoint
doesn't change and the failure is not exposed (by default) to other system
services.
- The new instance can be created reactively (when a crash is detected) or
proactively. In the latter case, RS can be instructed to keep a replica of
the system service to perform a hot swap when the service fails. The flag
SF_USE_REPL is set in that case.
- The new flag SF_USE_REPL is supported for services in the boot image and
dynamically started services through the RS interface (i.e. -p option in the
service utility).
- Fixed a free unallocated memory bug for core system services.
2010-04-27 11:17:30 +00:00
Tomas Hruby
30798fc3e1 Removed unused prototype 2010-04-26 23:39:05 +00:00
Tomas Hruby
f51eea4b32 Changed pagefault delivery to VM
this patch changes the way pagefaults are delivered to VM. It adopts
the same model as the out-of-quantum messages sent by kernel to a
scheduler.

- everytime a userspace pagefault occurs, kernel creates a message
  which is sent to VM on behalf of the faulting process

- the process is blocked on delivery to VM in the standard IPC code
  instead of waiting in a spacial in-kernel queue (stack) and is not
  runnable until VM tell kernel that the pagefault is resolved and is
  free to clear the RTS_PAGEFAULT flag.

- VM does not need call kernel and poll the pagefault information
  which saves many (1/2?) calls and kernel calls that return "no more
  data"

- VM notification by kernel does not need to use signals

- each entry in proc table is by 12 bytes smaller (~3k save)
2010-04-26 23:21:26 +00:00
Ben Gras
a131085a5b cd boot workaround for bioses that didn't want to boot >4 image sectors.
boot is a normal binary with a.out again. use 'cdbootblock,' a CDBOOT
variant of bootblock, both from bootblock.s, as the first boot image
that then loads boot, exactly like the bootblock loads boot when booting
from harddisk. the sector numbers (2048 byte iso sectors) are patched in
by writeisofs, like installboot does for bootblock. bootblock unchanged.
2010-04-26 22:07:21 +00:00
Ben Gras
94edf4fa12 vfs: start at vmnt[0] to sync mounted filesystems, not vmnt[1]. 2010-04-26 17:12:34 +00:00
Ben Gras
86e8eff905 remove intr_disabled() as interrupts are always disabled in the kernel now. 2010-04-26 15:32:42 +00:00
Tomas Hruby
1718924b10 Fixed printf warning in the filter driver 2010-04-26 14:44:20 +00:00
Cristiano Giuffrida
0f353411d7 Set IPC status code only for RECEIVE 2010-04-26 14:43:59 +00:00
Kees van Reeuwijk
5b0efc542f Remove a redundant getdomainname() implementation. 2010-04-26 12:43:43 +00:00
David van Moolenbroek
aacbfc41cc intercept puts() in libsys, for gcc 2010-04-23 20:23:33 +00:00
David van Moolenbroek
ee3b5fb5ea fix make(1) error output 2010-04-23 12:04:48 +00:00
Kees van Reeuwijk
74177b215d Also remove awk.old from makefile. 2010-04-22 14:18:35 +00:00
Kees van Reeuwijk
e24ed988d6 Fix some compilation errors with the gcc compiler, fix some recent warnings. 2010-04-22 13:59:34 +00:00
Kees van Reeuwijk
55129194a3 Remove obsolete implementation of awk. 2010-04-22 13:41:35 +00:00
Kees van Reeuwijk
d106968d77 Remove useless symbol declarations from headers, make symbols local where possible, add some explicit initialization to global variables. 2010-04-22 07:49:40 +00:00
Kees van Reeuwijk
87a9a2ecef More accurate make rule. 2010-04-21 14:41:20 +00:00
Kees van Reeuwijk
86a23c1fbd Remove U16_t and most other similar types. Rewrite functions to ansi-style
declaration if necessary.
2010-04-21 11:05:22 +00:00
Kees van Reeuwijk
8a304627a3 Forgot to add two new files to SVN. 2010-04-20 07:17:03 +00:00
Kees van Reeuwijk
e85f78a20b Add some support for wchar_t. 2010-04-19 15:20:24 +00:00
Kees van Reeuwijk
b412fb7ad5 Code cleanup: remove unused #include, variables and code, 2010-04-15 18:49:36 +00:00
David van Moolenbroek
cfb108afc7 fix mfs/isofs signal handling 2010-04-15 16:10:28 +00:00
Erik van der Kouwe
5230a36c2e Add scancode reading capability to TTY 2010-04-15 07:08:04 +00:00
Erik van der Kouwe
7de730afe4 Add scancode reading capability to TTY 2010-04-15 06:55:42 +00:00
Erik van der Kouwe
32f43d7571 Add scancode reading capability to TTY 2010-04-15 06:55:32 +00:00
Kees van Reeuwijk
8005ac2c64 Add timerisclear() macro. 2010-04-14 17:51:39 +00:00
David van Moolenbroek
05f8a5c550 unbreak _open for gcc-compiled programs 2010-04-14 11:07:49 +00:00
Erik van der Kouwe
8b459cfbb3 Provide information on lethal signals (stacktrace and signo) 2010-04-14 09:06:34 +00:00
Kees van Reeuwijk
fa3adedf63 Remove some duplicate declarations in headers.
Explicitly declare some functions as returning void.
2010-04-13 15:22:38 +00:00
Ben Gras
e0792d72d7 vm: util.S not used currently; leave it out. 2010-04-13 15:02:32 +00:00
Ben Gras
5c17d5e02f vm: include no-caching bits in PTF_ALLFLAGS for flags sanity check. 2010-04-13 11:08:08 +00:00
Ben Gras
1f1f8d2207 vm: don't force physical addresses to be nonzero. 2010-04-13 11:01:40 +00:00
Kees van Reeuwijk
bc314bda91 Remove the types Dev_t, _mnx_Gui, _mnx_Uid, and similar.
Use ANSI-style function declarations where necessary.
2010-04-13 10:58:41 +00:00
Tomas Hruby
86378ff645 PM remembers what it should schedule
- while PM implements fork also for RS it needs to remember what to
  schedule and what not. PM_SCHEDULED flag serves this purpose.

- PM only schedules processes that are descendaints of init, i.e. normal
  user processes

- after a process is forked PM schedules for the first time only
  processes that have PM_SCHEDULED set. The others are handled iether
  by kernel or some other scheduler
2010-04-13 10:45:08 +00:00
Ben Gras
5f7c37bb84 vm: remove assert, map in of phys addr 0 is legit sometimes. 2010-04-13 10:39:46 +00:00
Erik van der Kouwe
32713a6b5a Fix date in UPDATING 2010-04-12 17:56:07 +00:00
Ben Gras
27fc7ab1f3 vm: use assert() instead of vm_assert(); remove vm_assert(). 2010-04-12 12:37:28 +00:00
Ben Gras
c78250332d let vm use physically fragmented memory for allocations.
map_copy_ph_block is replaced by map_clone_ph_block, which can
replace a single physical block by multiple physical blocks.

also,
 . merge map_mem.c with region.c, as they manipulate the same
   data structures
 . NOTRUNNABLE removed as sanity check
 . use direct functions for ALLOC_MEM and FREE_MEM again
 . add some checks to shared memory mapping code
 . fix for data structure integrity when using shared memory
 . fix sanity checks
2010-04-12 11:25:24 +00:00
Ben Gras
76fbf21026 ipc server: don't print as many errors, to make ipc test less noisy. 2010-04-12 11:06:15 +00:00
Cristiano Giuffrida
66a8efba53 Fixed escape warning. 2010-04-12 08:39:59 +00:00
Tomas Hruby
9b599bac1d Quantum in fork
- This patch removes the time slice split between parent and child in
  fork.

- The time slice of the parent remains unchanged and the child does
  not have any.

- If the process has a scheduler, the scheduler must assign the
  quantum and priority of the new process and let it run.

- If the child does not inherit a scheduler, it is scheduled by the
  dummy default kernel policy. (servers, drivers, etc.)

- In theory, the scheduler can change the quantum even of the parent
  process and implement any policy for splitting the quantum as
  neither the parent nor the child are runnable.  Sending the
  out-of_quantum message on behalf of the processes may look like the
  right solution, however, the scheduler would probably handle the
  message before the whole fork protocol is finished. This way the
  scheduler has absolute control when the process should become
  runnable.
2010-04-10 15:27:38 +00:00
Tomas Hruby
1a31d158ad Restructure and simplyfycation of the scheduling code in PM a little bit.
- It introduces schedule_process() which makes a kernel call to set
  the scheduling parameters of a process. It is used in the next patch.
2010-04-10 15:24:49 +00:00
Tomas Hruby
512058ca98 This tiny cleanup makes the naming a variables in createpde() more clear. 2010-04-10 15:22:41 +00:00
Tomas Hruby
9fdb773cdb A simpler test whether to use kernel's default scheduling
- this is a small addition to the userspace scheduling.
  proc_kernel_scheduler() tests whether to use the default scheduling
  policy in kernel. It is true if the process' scheduler is NULL _or_
  self. Currently none of the tests was complete.
2010-04-10 15:19:25 +00:00
Tomas Hruby
485a037563 do_schedule() cleanup
- it is not neccessary to test whether the scheduler is a system
  process as the process already head permissions to make this call.

- it is better to test whether the scheduler has permission to make
  changes to this process before testing whether the values are valid.
2010-04-10 15:17:09 +00:00
Cristiano Giuffrida
65ef539739 Driver mapping refactory.
VFS CHANGES:
- dmap table no longer statically initialized in VFS
- Dropped FSSIGNON svrctl call no longer used by INET

INET CHANGES:
- INET announces its presence to VFS just like any other driver

RS CHANGES:
- The boot image dev table contains all the data to initialize VFS' dmap table
- RS interface supports asynchronous up and update operations now
- RS interface extended to support driver style and flags
2010-04-09 21:56:44 +00:00
Ben Gras
c1bfcc9119 port of netbsd's tr 2010-04-08 15:08:31 +00:00
Ben Gras
1164052eea netbsd's original tr/extern.h as tr.h 2010-04-08 15:06:43 +00:00
Ben Gras
836a0957fb original netbsd's tr(1) 2010-04-08 15:04:57 +00:00
Ben Gras
c28e35bd3e no minix tr 2010-04-08 15:04:05 +00:00
Cristiano Giuffrida
98d1cf7064 Fixed gcc -Wall warnings. 2010-04-08 15:02:32 +00:00
Ben Gras
1c8c8aa4d8 isblank() implementation. 2010-04-08 15:00:25 +00:00
Cristiano Giuffrida
48c6bb79f4 Driver refactory for live update and crash recovery.
SYSLIB CHANGES:
- DS calls to publish / retrieve labels consider endpoints instead of u32_t.

VFS CHANGES:
- mapdriver() only adds an entry in the dmap table in VFS.
- dev_up() is only executed upon reception of a driver up event.

INET CHANGES:
- INET no longer searches for existing drivers instances at startup.
- A newtwork driver is (re)initialized upon reception of a driver up event.
- Networking startup is now race-free by design. No need to waste 5 seconds
at startup any more.

DRIVER CHANGES:
- Every driver publishes driver up events when starting for the first time or
in case of restart when recovery actions must be taken in the upper layers.
- Driver up events are published by drivers through DS. 
- For regular drivers, VFS is normally the only subscriber, but not necessarily.
For instance, when the filter driver is in use, it must subscribe to driver
up events to initiate recovery.
- For network drivers, inet is the only subscriber for now.
- Every VFS driver is statically linked with libdriver, every network driver
is statically linked with libnetdriver.

DRIVER LIBRARIES CHANGES:
- Libdriver is extended to provide generic receive() and ds_publish() interfaces
for VFS drivers.
- driver_receive() is a wrapper for sef_receive() also used in driver_task()
to discard spurious messages that were meant to be delivered to a previous
version of the driver.
- driver_receive_mq() is the same as driver_receive() but integrates support
for queued messages.
- driver_announce() publishes a driver up event for VFS drivers and marks
the driver as initialized and expecting a DEV_OPEN message.
- Libnetdriver is introduced to provide similar receive() and ds_publish()
interfaces for network drivers (netdriver_announce() and netdriver_receive()).
- Network drivers all support live update with no state transfer now.

KERNEL CHANGES:
- Added kernel call statectl for state management. Used by driver_announce() to
unblock eventual callers sendrecing to the driver.
2010-04-08 13:41:35 +00:00
Ben Gras
2fd5eb2569 ipc test improvements
. rename testshm.sh to test.sh so all test scripts are called test.sh
 . delete msg* tests as msg* functionality isn't implemented
 . add ipc/test.sh that runs all test.sh scripts in the subdirs
2010-04-08 13:11:37 +00:00
Ben Gras
78806e1b2e more stack for boot 2010-04-08 12:18:57 +00:00
Kees van Reeuwijk
c114df82ec Rename all uses of U8_t to u8_t and remove U8_t, remove unused I8_t,
Remove all uses of U16_t and U32_t in pci-related code.
If necessary to avoid problems, change functions to ansi-style declaration.
2010-04-07 13:35:56 +00:00
Tomas Hruby
25f2145956 Fixed a panic message
- exceptions cannot occur in kernel tasks as we don't have kernel
  tasks anymore
2010-04-07 12:50:43 +00:00
Kees van Reeuwijk
94a81c840a Removed unused variables, added const where possible. 2010-04-07 11:25:51 +00:00
Tomas Hruby
c39eb33b74 A fixed prototype in dec21140A.c 2010-04-07 07:50:44 +00:00
Tomas Hruby
b464da5d73 do_nice.c
- this file is not used and should have been remove in r6557
2010-04-06 13:44:03 +00:00
Tomas Hruby
987b87e2ad Small fixes
- do_sync_ipc() is private

- fixed typo in a comment
2010-04-06 11:29:31 +00:00
Tomas Hruby
a774cc832f do_ipc() rearrangements
this patch does not add or change any functionality of do_ipc(), it
only makes things a little cleaner (hopefully).

Until now do_ipc() was responsible for handling all ipc calls. The
catch is that SENDA is fairly different which results in some ugly
code like this typecasting and variables naming which does not make
much sense for SENDA and makes the code hard to read.

result = mini_senda(caller_ptr, (asynmsg_t *)m_ptr, (size_t)src_dst_e);

As it is called directly from assembly, the new do_ipc() takes as
input values of 3 registers in reg_t variables (it used to be 4,
however, bit_map wasn't used so I removed it), does the checks common
to all ipc calls and call the appropriate handler either for
do_sync_ipc() (all except SENDA) or mini_senda() (for SENDA) while
typecasting the reg_t values correctly. As a result, handling SENDA
differences in do_sync_ipc() is no more needed. Also the code that
uses msg_size variable is improved a little bit.

arch_do_syscall() is simplified too.
2010-04-06 11:24:26 +00:00
Tomas Hruby
b0d37b81c4 RTS_SYS_LOCK and do_runctl()
- No need for RTS_SYS_LOCK as there are no tasks anymore.
2010-04-06 11:18:04 +00:00
Tomas Hruby
cdd6743e88 do_vtimer()
- removed comment which is not true anymore as we don't have any
  tasks. No need to take any special measures.
2010-04-06 11:16:14 +00:00
Arun Thomas
4ed3a0cf3a Convert kernel over to bsdmake 2010-04-01 22:22:33 +00:00
Kees van Reeuwijk
0a04f49d2b Fixed some incorrect uses of printf-like functions. 2010-04-01 14:30:36 +00:00
Kees van Reeuwijk
fc7dced1fa Fix printfs with too few or too many parms, remove unused vars, fix incorrect flag tests, other code cleanup. 2010-04-01 13:25:05 +00:00
Kees van Reeuwijk
c3f649557e Lots of const correctness, other cleanup. 2010-04-01 12:51:31 +00:00
Ben Gras
9fd4c2a20d introduce the fsckopts sysenv, options passed to fsck by /etc/rc.
setting 'fsckopts=-a' makes it much easier to work on a minix machine
remotely and reboot after a crash.
2010-03-31 15:06:53 +00:00
Ben Gras
de93803ab0 only print 'PCI: ignoring bad value ...' once per boot. 2010-03-31 12:29:30 +00:00
Cristiano Giuffrida
d8b42a755d Move kernel signal SIGKNDELAY to system signal SIGSNDELAY and fix broken ptrace. 2010-03-31 08:55:12 +00:00
Thomas Veerman
4d686f1616 Move allocation of temporary inodes for cloned character special devices from
MFS to PFS.
2010-03-30 15:00:09 +00:00
Kees van Reeuwijk
4865e3f4f9 More use of endpoint_t. Other code cleanup. 2010-03-30 14:07:15 +00:00
Lorenzo Cavallaro
2ff73172b4 Fixed missing __UNCONST macro definition in previous patch. 2010-03-30 13:08:14 +00:00
Lorenzo Cavallaro
8dfc7699a6 cdecl calling convention requires to push arguments on the stack in a
reverse order to easily support variadic arguments. Thus, instead of
using the proper stdarg.h macros (that nowadays are
compiler-dependent), it may be tempting to directly take the address of
the last argument and considering it as the start of an array. This is
a shortcut that avoid looping to get all the arguments as the CPU
already pushed them on the stack before the call to the function.

Unfortunately, such an assumption is strictly compiler-dependent and
compilers are free to move the last argument on the stack, as a local
variable, and return the address of the location where the argument was
stored, if asked for. This will break things as the rest of the array's
argument are stored elsewhere (typically, a couple of words above the
location where the argument was stored).

This patch fixes the issue by allowing ACK to take the shortcut and
enabling gcc/llvm-gcc to follow the right way.
2010-03-30 09:36:46 +00:00
Tomas Hruby
63e2d73d1b Fixed brackets in bitmap macros 2010-03-30 08:34:33 +00:00
Ben Gras
f2b87f5fb7 don't print SYSTEM stacktrace on exceptions as it's not scheduled any more. 2010-03-29 15:32:19 +00:00
Tomas Hruby
62203ec287 NOREC_ENTER and NOREC_RETURN checks removed
- the reasons for these checks no longer exist

- these check are problematic on SMP
2010-03-29 11:43:10 +00:00
Ben Gras
bc0e36f402 fix null deref; vmnt->mounted_on is NULL legitimately for root.
changed check+panic to assert().

added assert().
2010-03-29 11:39:54 +00:00
Tomas Hruby
5b52c5aa02 A reliable way for userspace to check if a msg is from kernel
- IPC_FLG_MSG_FROM_KERNEL status flag is returned to userspace if the
  receive was satisfied by s message which was sent by the kernel on
  behalf of a process. This perfectly reliale information.

- MF_SENDING_FROM_KERNEL flag added to processes to be able to set
  IPC_FLG_MSG_FROM_KERNEL when finishing receive if the receiver
  wasn't ready to receive immediately.

- PM is changed to use this information to confirm that the scheduling
  messages are indeed from the kernel and not faked by a process.

  PM uses sef_receive_status()

- get_work() is removed from PM to make the changes simpler
2010-03-29 11:25:01 +00:00
Tomas Hruby
2521cc6bdf Slightly faster IPC
- there are cycles wasted in the IPC call due to a fairly compliacted
  way of copying messages from userland to kernel. Sometimes this
  complicated way (generic though) is used even for copying within the
  kernel address space, sometimes it is used for copying in case _no_
  copying is necessary. The goal of this patch is to improve this a
  little bit.

- the places where a copy is from user to kernel use the
  copy_msg_from_user() kernel-kernel copies are turned into
  assignments and BuildNotifyMessage uses the delivery buffers to
  avoid copying.

- copy_msg_from_user() was introduced when removing the system task
  and is about 2/3 faster then using the current mechanism
  (phys_copy). It also avoids the PHYS_COPY_CATCH macro. Assignment is
  also faster and no copy is the fastest ;-) so perhaps there will be
  some hardly noticable performance gain besides the clean up.
2010-03-29 11:16:37 +00:00
Tomas Hruby
b4cf88a04f Userspace scheduling
- cotributed by Bjorn Swift

- In this first phase, scheduling is moved from the kernel to the PM
  server. The next steps are to a) moving scheduling to its own server
  and b) include useful information in the "out of quantum" message,
  so that the scheduler can make use of this information.

- The kernel process table now keeps record of who is responsible for
  scheduling each process (p_scheduler). When this pointer is NULL,
  the process will be scheduled by the kernel. If such a process runs
  out of quantum, the kernel will simply renew its quantum an requeue
  it.

- When PM loads, it will take over scheduling of all running
  processes, except system processes, using sys_schedctl().
  Essentially, this only results in taking over init. As children
  inherit a scheduler from their parent, user space programs forked by
  init will inherit PM (for now) as their scheduler.

 - Once a process has been assigned a scheduler, and runs out of
   quantum, its RTS_NO_QUANTUM flag will be set and the process
   dequeued. The kernel will send a message to the scheduler, on the
   process' behalf, informing the scheduler that it has run out of
   quantum. The scheduler can take what ever action it pleases, based
   on its policy, and then reschedule the process using the
   sys_schedule() system call.

- Balance queues does not work as before. While the old in-kernel
  function used to renew the quantum of processes in the highest
  priority run queue, the user-space implementation only acts on
  processes that have been bumped down to a lower priority queue.
  This approach reacts slower to changes than the old one, but saves
  us sending a sys_schedule message for each process every time we
  balance the queues. Currently, when processes are moved up a
  priority queue, their quantum is also renewed, but this can be
  fiddled with.

- do_nice has been removed from kernel. PM answers to get- and
  setpriority calls, updates it's own nice variable as well as the
  max_run_queue. This will be refactored once scheduling is moved to a
  separate server. We will probably have PM update it's local nice
  value and then send a message to whoever is scheduling the process.

- changes to fix an issue in do_fork() where processes could run out
  of quantum but bypassing the code path that handles it correctly.
  The future plan is to remove the policy from do_fork() and implement
  it in userspace too.
2010-03-29 11:07:20 +00:00
Tomas Hruby
a3ffc0f7ad Removed NIL_SYS_PROC and NIL_PROC
- NIL_PROC replaced by simple NULLs
2010-03-28 09:54:32 +00:00
Kees van Reeuwijk
98493805fd Lots of const correctness. 2010-03-27 14:31:00 +00:00
Cristiano Giuffrida
9192dbecc9 Preserve the order of IPC messages between two parties.
Currently a sequence of messages between a sender A and a receiver B of the
form: A.asynsend(M1, B); A.send(M2, B) may result in the receiver receiving
M1 first and then M2 or viceversa. This patch makes sure that the original
order M1, M2 is always preserved.

Note that the order of a hypotetical sequence A.asynsend(M1, B);
A.asynsend(M2, B) is already guaranteed by the implementation of
asynsend by design. Other senda-based wrappers can define their own
semantics.
2010-03-27 00:09:22 +00:00
Tomas Hruby
8e5a82fd49 Comment in proc.h
- This comment is not correct as the pproc_addr array does not exist.
2010-03-26 13:19:04 +00:00
Tomas Hruby
1dd6f5573a Direction flag
- ack assumes that the direction flag in eflags is clear when
  assigning two structures. It is implemented by a call to a built-in
  function which is like memcpy but needs the flag to be clear
  otherwise rubish is copied. This patch fixes the kernel entries.
2010-03-26 12:29:52 +00:00
Lorenzo Cavallaro
a16308efdb cdecl calling convention expects the callee to pop the hidden pointer on
struct return. For example, GCC and LLVM comply with this (tested on IA32).

ACK doesn't seem to follow this convention and expects the caller to clean up
the stack. Compiling hand-written ACK-compliant assembly code (returning a 
struct) with GCC or LLVM used to break things (4-bytes misaligned stack).

The patch fixes this problem.
2010-03-24 17:25:17 +00:00
Arun Thomas
5fd3f34273 Minor docs/UPDATING fix 2010-03-24 13:41:38 +00:00
Arun Thomas
14ca3ea017 Sort docs/UPDATING entries reverse chronologically 2010-03-24 10:13:19 +00:00
Arun Thomas
0ea82663e0 Fix crtso building with GCC 2010-03-24 10:11:17 +00:00
Kees van Reeuwijk
407316e451 More const correctness.
Removed prototype for unimplemented getpgid() function.
Removed a value return from a void function.
2010-03-23 14:25:09 +00:00
Tomas Hruby
a6957b7847 Fixed prototype in cat 2010-03-23 13:36:16 +00:00
Tomas Hruby
8451a86f0a Interrupts hadling while idle
- When the cpu halts, the interrupts are enable so the cpu may be
  woken up. When the interrupt handler returns but another interrupt
  is available it is also serviced immediately. This is not a problem
  per-se. It only slightly breaks time accounting as idle accounted is
  for the kernel time in the interrupt handler.
  
  
-  As the big kernel lock is lock/unlocked in the smp branch in the
   time acounting functions as they are called exactly at the places
   we need to take the lock) this leads to a deadlock.

- we make sure that once the interrupt handler returns from the nested
  trap, the interrupts are disabled. This means that only one
  interrupt is serviced after idle is interrupted.

- this requires the loop in apic timer calibration to keep reenabling
  the interrupts. I admit it is a little bit hackish (one line),
  however, this code is a stupid corner case at the boot time.
  Hopefully it does not matter too much.
2010-03-23 13:35:01 +00:00
Cristiano Giuffrida
bde2109b7c IPC status code for receive().
IPC changes:
- receive() is changed to take an additional parameter, which is a pointer to
a status code.
- The status code is filled in by the kernel to provide additional information
to the caller. For now, the kernel only fills in the IPC call used by the
sender.

Syslib changes:
- sef_receive() has been split into sef_receive() (with the original semantics)
and sef_receive_status() which exposes the status code to userland.
- Ideally, every sys process should gradually switch to sef_receive_status()
and use is_ipc_notify() as a dependable way to check for notify.
- SEF has been modified to use is_ipc_notify() and demonstrate how to use the
new status code.
2010-03-23 00:09:11 +00:00
Cristiano Giuffrida
45db6482e8 Prioritized NOTIFY messages for reliable asynchonrous delivery of system events. 2010-03-22 23:44:55 +00:00
Cristiano Giuffrida
ef95bf1bb9 Print stacktrace when a system service fails or when a core dump has to be generated for a user process. 2010-03-22 22:46:29 +00:00
Arun Thomas
436d6012a3 Convert drivers/ and servers/ over to bsdmake
-Move libdriver to lib/
-Install all boot image services on filesystem to aid restartability
2010-03-22 21:25:22 +00:00
Kees van Reeuwijk
c33102ea6b Miscellaneous code cleanup. 2010-03-22 20:43:06 +00:00
Ben Gras
4b2310a7ee only print 1 every 1000 spurious interrupts (per interrupt). 2010-03-22 13:55:51 +00:00
Tomas Hruby
12ef495cac atomicity fix when enabling paging
- before enabling paging VM asks kernel to resize its segments. This
  may cause kernel to segfault if APIC is used and an interrupt
  happens between this and paging enabled. As these are 2 separate
  vmctl calls it is not atomic. This patch fixes this problem. VM does
  not ask kernel to resize the segments in a separate call anymore.
  The new segments limit is part of the "enable paging" call. It
  generalizes this call in such a way that more information can be
  passed as need be or the information may be completely different if
  another architecture requires this.
2010-03-22 07:42:52 +00:00
Tomas Hruby
a5094f7d7f Kernel dumps its registers when exception
- if an exception occurs in kernel and this exception is not handled
  in an sane way and the kernel crashes, it also dumps what was loaded
  in the general purpose registers exactly at the time of the
  exception to help to debug the problem
2010-03-20 14:59:18 +00:00
Erik van der Kouwe
b42c66ed10 this patch adds access to the debug breakpoints to
the kernel. They are not used atm, but having them in trunk allows them
to be easily used when needed. To set a breakpoint that triggers when
the variable foo is written to (the most common use case), one calls:

breakpoint_set(vir2phys((vir_bytes) &foo), 0,
  BREAKPOINT_FLAG_MODE_GLOBAL |
  BREAKPOINT_FLAG_RW_WRITE |
  BREAKPOINT_FLAG_LEN_4);

It can later be disabled using:

breakpoint_set(vir2phys((vir_bytes) &foo), 0,
  BREAKPOINT_FLAG_MODE_OFF);

There are some limitations:

- There are at most four breakpoints (hardware limit); the index of the
  breakpoint (0-3) is specified as the second parameter of
  breakpoint_set.

- The breakpoint exception in the kernel is not handled and causes a
  panic; it would be reasonably easy to change this by inspecing DR6,
  printing a message, disabling the breakpoint and continuing. However,
  in my experience even just a panic can be very useful.

- Breakpoints can be set only in the part of the address space that is
  in every page table. It is useful for the kernel, but to use this for
  user processes would require saving and restoring the debug registers
  as part of the context switch. Although the CPU provides support for
  local breakpoints (I implemened this as BREAKPOINT_FLAG_LOCAL) they
  only work if task switching is used.
2010-03-19 19:15:20 +00:00
Erik van der Kouwe
19ff96081c Specify missing return type 2010-03-19 19:07:00 +00:00
Ben Gras
ec30f25d0c VM: fix kernel mappings for children of non-paged parents. 2010-03-18 17:17:31 +00:00
Tomas Hruby
61348227a7 docs/UPDATING correction 2010-03-18 17:00:32 +00:00
Tomas Hruby
a0602c06a3 Fixed kernel stack comment 2010-03-18 16:18:22 +00:00
Ben Gras
e595328986 remove 3 awk files - don't have generated files in svn. 2010-03-18 14:15:48 +00:00
Ben Gras
f250bfaa13 change messy CREATEPDE macro to clean little function.
forget about the dirtypde bitmap and WIPEPDE/DONEPDE macros too.

check if mapping happens to already be in place, and if so, don't
reload cr3 (on the account of that mapping, that is).

don't reload cr3 unconditionally.
2010-03-18 13:35:41 +00:00
Erik van der Kouwe
c3e73f0793 Provide a warning is a kernel call has been denied, to ease system.conf debugging 2010-03-17 18:23:51 +00:00
Kees van Reeuwijk
4683d6b713 Let awk.old install its awk as /usr/bin/awk.old.
Add one-true-awk as the new awk that installs to /usr/bin/awk.
2010-03-17 16:16:52 +00:00
Kees van Reeuwijk
365495b530 Moved current awk sources to awk.old. 2010-03-17 16:11:48 +00:00
Kees van Reeuwijk
4432f197c1 Add a define for NSIG. 2010-03-17 13:43:34 +00:00
Cristiano Giuffrida
cb176df60f New RS and new signal handling for system processes.
UPDATING INFO:
20100317:
        /usr/src/etc/system.conf updated to ignore default kernel calls: copy
        it (or merge it) to /etc/system.conf.
        The hello driver (/dev/hello) added to the distribution:
        # cd /usr/src/commands/scripts && make clean install
        # cd /dev && MAKEDEV hello

KERNEL CHANGES:
- Generic signal handling support. The kernel no longer assumes PM as a signal
manager for every process. The signal manager of a given process can now be
specified in its privilege slot. When a signal has to be delivered, the kernel
performs the lookup and forwards the signal to the appropriate signal manager.
PM is the default signal manager for user processes, RS is the default signal
manager for system processes. To enable ptrace()ing for system processes, it
is sufficient to change the default signal manager to PM. This will temporarily
disable crash recovery, though.
- sys_exit() is now split into sys_exit() (i.e. exit() for system processes,
which generates a self-termination signal), and sys_clear() (i.e. used by PM
to ask the kernel to clear a process slot when a process exits).
- Added a new kernel call (i.e. sys_update()) to swap two process slots and
implement live update.

PM CHANGES:
- Posix signal handling is no longer allowed for system processes. System
signals are split into two fixed categories: termination and non-termination
signals. When a non-termination signaled is processed, PM transforms the signal
into an IPC message and delivers the message to the system process. When a
termination signal is processed, PM terminates the process.
- PM no longer assumes itself as the signal manager for system processes. It now
makes sure that every system signal goes through the kernel before being
actually processes. The kernel will then dispatch the signal to the appropriate
signal manager which may or may not be PM.

SYSLIB CHANGES:
- Simplified SEF init and LU callbacks.
- Added additional predefined SEF callbacks to debug crash recovery and
live update.
- Fixed a temporary ack in the SEF init protocol. SEF init reply is now
completely synchronous.
- Added SEF signal event type to provide a uniform interface for system
processes to deal with signals. A sef_cb_signal_handler() callback is
available for system processes to handle every received signal. A
sef_cb_signal_manager() callback is used by signal managers to process
system signals on behalf of the kernel.
- Fixed a few bugs with memory mapping and DS.

VM CHANGES:
- Page faults and memory requests coming from the kernel are now implemented
using signals.
- Added a new VM call to swap two process slots and implement live update.
- The call is used by RS at update time and in turn invokes the kernel call
sys_update().

RS CHANGES:
- RS has been reworked with a better functional decomposition.
- Better kernel call masks. com.h now defines the set of very basic kernel calls
every system service is allowed to use. This makes system.conf simpler and
easier to maintain. In addition, this guarantees a higher level of isolation
for system libraries that use one or more kernel calls internally (e.g. printf).
- RS is the default signal manager for system processes. By default, RS
intercepts every signal delivered to every system process. This makes crash
recovery possible before bringing PM and friends in the loop.
- RS now supports fast rollback when something goes wrong while initializing
the new version during a live update.
- Live update is now implemented by keeping the two versions side-by-side and
swapping the process slots when the old version is ready to update.
- Crash recovery is now implemented by keeping the two versions side-by-side
and cleaning up the old version only when the recovery process is complete.

DS CHANGES:
- Fixed a bug when the process doing ds_publish() or ds_delete() is not known
by DS.
- Fixed the completely broken support for strings. String publishing is now
implemented in the system library and simply wraps publishing of memory ranges.
Ideally, we should adopt a similar approach for other data types as well.
- Test suite fixed.

DRIVER CHANGES:
- The hello driver has been added to the Minix distribution to demonstrate basic
live update and crash recovery functionalities.
- Other drivers have been adapted to conform the new SEF interface.
2010-03-17 01:15:29 +00:00
David van Moolenbroek
7685e98304 typo 2010-03-16 16:21:28 +00:00
Cristiano Giuffrida
83d1f45578 Fixed a bug in interrupt handling code when removing a handler in case of
a shared IRQ.
2010-03-16 10:20:36 +00:00
Erik van der Kouwe
2ba76cfec6 Minor correction in UPDATING 2010-03-16 08:16:13 +00:00
Arun Thomas
9944688d2b Convert man/ over to new make 2010-03-16 00:15:43 +00:00
Kees van Reeuwijk
d89e33fc92 Suppressed some warnings in the WIFSIGNALED macro. 2010-03-15 18:33:29 +00:00
Thomas Veerman
1749530ec1 Fix bug item #405: missing # in front of comment 2010-03-15 10:42:51 +00:00
Thomas Veerman
bef0e3eb63 - Add support for the ucontext system calls (getcontext, setcontext,
swapcontext, and makecontext).
- Fix VM to not erroneously think the stack segment and data segment have
  collided when a user-space thread invokes brk().
- Add test51 to test ucontext functionality.
- Add man pages for ucontext system calls.
2010-03-12 15:58:41 +00:00
Kees van Reeuwijk
3efbb8f133 Let the commands/simple/tr.c understand about '\t', '\r', and '\n'. 2010-03-12 09:58:44 +00:00
Kees van Reeuwijk
23e97af1b4 Add an UNUSED annotation, and use it in libsys. 2010-03-11 14:23:33 +00:00
Erik van der Kouwe
da25ecf758 Work around KVM unreal mode bug by avoiding unreal mode 2010-03-10 15:32:31 +00:00
Kees van Reeuwijk
5df6b80093 Clean up code in preparation for using gcc warnings. 2010-03-10 13:19:27 +00:00
Ben Gras
0937d6c367 re-establish kernel assert()s.
use the regular <assert.h> assert() instead of vmassert() in
kernel. throw out some #if 0 code. fix a few assert() conditions.
enable by default.
2010-03-10 13:00:05 +00:00
Kees van Reeuwijk
88ac328e6b Add prototypes for a bunch of time-related functions. Surprisingly,
they were in the implementation, but not in the header files.
2010-03-09 22:10:58 +00:00
Kees van Reeuwijk
a34d34bc1f Add a set of declarations to math.h. Since we don't actually have
implementations for these functions, we lean on GNU builtin functions
for using them, so these declarations are also conditional on using
a GNU compiler.
2010-03-09 22:05:20 +00:00
Dirk Vogt
44231405cf fix newsigset/oldsigset references 2010-03-09 20:46:26 +00:00
Kees van Reeuwijk
cf95efbad1 Prevent the use of an unitialized variable for block size in CRC calculation. 2010-03-09 16:21:41 +00:00
Arun Thomas
4206784d82 Flex: Fix install(1) invocation in build 2010-03-09 09:43:53 +00:00
Arun Thomas
1f9ce647cf Move archtypes.h, fpu.h, and stackframe.h
Move archtypes.h to include/ dir, since several servers require it. Move
fpu.h and stackframe.h to arch-specific header directory. Make source
files and makefiles aware of the new header locations.
2010-03-09 09:41:14 +00:00
David van Moolenbroek
27d53256e4 VFS fixes:
- do not use uninitialized req_breadwrite results upon failure
- improve ".." ELEAVEMOUNT correctness check
2010-03-08 22:05:27 +00:00
Kees van Reeuwijk
91655261a1 Also run fixincludes in gcc 4.4.3 2010-03-08 14:51:00 +00:00
Ben Gras
4f063f2925 fix for wrong arg to va_end() in panic() (thanks tveerman) 2010-03-08 14:36:55 +00:00
Arun Thomas
2a8fabf4ad Include directory reorg and makefile updates.
-Convert the include directory over to using bsdmake
 syntax
-Update/add mkfiles
-Modify install(1) so that it can create symlinks
-Update makefiles to use new install(1) options
-Rename /usr/include/ibm to /usr/include/i386
-Create /usr/include/machine symlink to arch header files
-Move vm_i386.h to its new home in the /usr/include/i386
-Update source files to #include the header files at their
 new homes.
-Add new gnu-includes target for building GCC headers
2010-03-08 11:04:59 +00:00
Tomas Hruby
ecf1a36d48 Fix for FPU broken by r6131
- cycles accounting must be called earlier, firstly not to clobber the %ebx
  register, secondly to be correctly called in both branches.
2010-03-05 22:23:03 +00:00
Ben Gras
35a108b911 panic() cleanup.
this change
   - makes panic() variadic, doing full printf() formatting -
     no more NO_NUM, and no more separate printf() statements
     needed to print extra info (or something in hex) before panicing
   - unifies panic() - same panic() name and usage for everyone -
     vm, kernel and rest have different names/syntax currently
     in order to implement their own luxuries, but no longer
   - throws out the 1st argument, to make source less noisy.
     the panic() in syslib retrieves the server name from the kernel
     so it should be clear enough who is panicing; e.g.
         panic("sigaction failed: %d", errno);
     looks like:
         at_wini(73130): panic: sigaction failed: 0
         syslib:panic.c: stacktrace: 0x74dc 0x2025 0x100a
   - throws out report() - printf() is more convenient and powerful
   - harmonizes/fixes the use of panic() - there were a few places
     that used printf-style formatting (didn't work) and newlines
     (messes up the formatting) in panic()
   - throws out a few per-server panic() functions
   - cleans up a tie-in of tty with panic()

merging printf() and panic() statements to be done incrementally.
2010-03-05 15:05:11 +00:00
Kees van Reeuwijk
851dc95566 Move cp_grant_id_t to a more central header file, and uses it more
extensively.
Fix casts that cast the grand id field of some messages to the wrong
type.
2010-03-04 16:15:26 +00:00
Ben Gras
adf0b6fb26 No more E{SRC,DST}DIED errno's, replaced by EDEADSRCDST.
The callers don't care about the difference and had to check 3 error
codes instead of one.
2010-03-03 15:47:16 +00:00
Ben Gras
eedff09bfd top manpage update 2010-03-03 15:46:20 +00:00
Ben Gras
72fc754948 new feature for top - display chain of blocked processes for every
blocked process.
2010-03-03 15:45:43 +00:00
Ben Gras
e6cb76a2e2 no more kprintf - kernel uses libsys printf now, only kputc is special
to the kernel.
2010-03-03 15:45:01 +00:00
Ben Gras
18924ea563 New P_BLOCKEDON for kernel - a macro that encodes the "who is this
process waiting for" logic, which is duplicated a few times in the
kernel. (For a new feature for top.)

Introducing it and throwing out ESRCDIED and EDSTDIED (replaced by
EDEADSRCDST - so we don't have to care which part of the blocking is
failing in system.c) simplifies some code in the kernel and callers that
check for E{DEADSRCDST,ESRCDIED,EDSTDIED}, but don't care about the
difference, a fair bit, and more significantly doesn't duplicate the
'blocked-on' logic.
2010-03-03 15:32:26 +00:00
Arun Thomas
cbd276e4ce Convert library asm files to GAS syntax 2010-03-03 14:27:30 +00:00
Kees van Reeuwijk
bf7397b64e More correctly use cp_grant_id_t.
More correctly use vir_bytes.
More correctly use endpoint_t.
2010-03-02 23:12:13 +00:00
Kees van Reeuwijk
f3c98fdca2 Fixed a number of cases where a bits in an integer were tested
incorrectly, resulting in real (and nasty) bugs.
2010-03-02 12:55:39 +00:00
Tomas Hruby
975efeac31 Typo in VM server 2010-03-02 10:53:17 +00:00
Ben Gras
5af8c345be slight tuning of /etc/mk situation when making release.
- Make the bootstrap /etc/mk be populated from the newly checked out source
  - Don't chmod 755 all of /etc
  - For the 'real' /etc/mk installing, let the /etc/mk ownership and permission
    come from the mtree file, delete the contents of /etc/mk, then copy the .mk
    files over and set reasonable permissions and ownership. (So that the .mk
    get updated from the real usr/src/ copies, and no other junk if anything,
    after the bootstrap phase, whatever happened there.)
2010-03-01 15:53:57 +00:00
Erik van der Kouwe
6b867ec05c #include <minix/ipc.h> in <minix/sef.h> 2010-02-26 10:13:50 +00:00
Erik van der Kouwe
2a67e38d88 #include <minix/ipc.h> in <minix/sef.h> 2010-02-26 10:12:54 +00:00
Arun Thomas
dd6569d342 Copy mkfiles when building world 2010-02-25 22:10:48 +00:00
Ben Gras
7c4cd0e6b0 - new pread(), fnmatch() calls
- split sprintf() and snprintf() to solve a linking problem when
   compiling an application
2010-02-25 17:08:08 +00:00
Arun Thomas
4cb358d999 Replace Minix tar with pax's tar 2010-02-24 11:58:10 +00:00
Arun Thomas
a4af231978 Improve makefile logic for building programs/libs 2010-02-24 11:58:05 +00:00
Kees van Reeuwijk
1ce69592d2 Fixed an array bounds violation.
Let include guards comform to the Minix standard.
2010-02-24 10:39:58 +00:00
Kees van Reeuwijk
3922d45719 Fix an array-bound violation, add some include guards. 2010-02-22 17:44:08 +00:00
Ben Gras
c460974814 remove subdirs that aren't built.
ftp is superseded by other dirs, i86 is not used, httpd* is superseded
by packages, sed is superseded by simple/sed.c.
2010-02-19 16:31:43 +00:00
Ben Gras
8c88a0219b add swifi to the build/install. 2010-02-19 16:16:28 +00:00
Ben Gras
d3b3c9d36d fix some warning in swifi, make it installable 2010-02-19 16:15:25 +00:00
Erik van der Kouwe
1a326acada Flag to load kernel high (not yet used by default), improved debug output 2010-02-19 12:38:38 +00:00
Erik van der Kouwe
e3bfaaa2d0 Remove executable bit on mkdep.1 2010-02-19 12:32:01 +00:00
Kees van Reeuwijk
1ba0936619 Fix some uses of uninitialized variables. 2010-02-19 10:41:02 +00:00
Kees van Reeuwijk
1597e701a0 Remove useless variables and the computations on them. 2010-02-19 10:00:32 +00:00
Kees van Reeuwijk
cf4f92dc21 Lots of cleanup of boot code. 2010-02-17 20:30:29 +00:00
Kees van Reeuwijk
97c169b93a Remove some unused #include.
Remove some unused variables and computations on them.
2010-02-17 20:24:42 +00:00
Arun Thomas
1e9a3c1423 Bump version number to 3.1.7 2010-02-17 12:51:26 +00:00
Arun Thomas
56b99ca816 Get gcc tests building again 2010-02-17 08:45:56 +00:00
Erik van der Kouwe
5af2471a9a Throw out obsolete Atari, Macintosh and Sun code to un-break packages;
credits to Sernin van de Krol's zip-2.31 patch for showing this problem
2010-02-16 19:19:42 +00:00
Arun Thomas
b706112487 Incorporate bsdmake into buildsystem and reorganize libs 2010-02-16 14:41:33 +00:00
Kees van Reeuwijk
6686e9ae9f The function fabsf should return a float, not a double. 2010-02-15 14:25:33 +00:00
David van Moolenbroek
e306663455 fix the somehow newly introduced warnings 2010-02-14 18:39:47 +00:00
Erik van der Kouwe
ff835e0e35 use the verbose=2 boot monitor setting to get extensive output for debugging 2010-02-13 22:11:16 +00:00
Kees van Reeuwijk
df60646f98 Undo the use of #include <...> because it caused some errors. 2010-02-12 14:43:18 +00:00
Tomas Hruby
b5e7af96c9 top update
- it works with the new TSC based time accounting
2010-02-10 15:38:27 +00:00
Tomas Hruby
1b56fdb33c Time accounting based on TSC
- as thre are still KERNEL and IDLE entries, time accounting for
  kernel and idle time works the same as for any other process

- everytime we stop accounting for the currently running process,
  kernel or idle, we read the TSC counter and increment the p_cycles
  entry.

- the process cycles inherently include some of the kernel cycles as
  we can stop accounting for the process only after we save its
  context and we start accounting just before we restore its context

- this assumes that the system does not scale the CPU frequency which
  will be true for ... long time ;-)
2010-02-10 15:36:54 +00:00
Ben Gras
f08f2bd88c new free_contig() and changes to make drivers use it; so now we
have malloc/free, alloc_contig/free_contig and mmap/munmap nicely
paired up.

memory uses malloc/free instead of mmap/munmap as it doesn't have
to be contiguous for the ramdisks (and it might help if it doesn't!).
2010-02-10 13:56:26 +00:00
Tomas Hruby
49284caf2a Fixes broken orinoco compilation in r6119 2010-02-09 16:43:34 +00:00
Tomas Hruby
d845891a50 And of course, as much as I've tried to be careful I forgot to add this file in
r6116 :(
2010-02-09 15:36:29 +00:00
Tomas Hruby
c9da61022b intr_disabled() tests removed
- we don't need to test this in kernel as we always have interrupts
  disabled

- if interrupts are enabled in kernel, it is only at very carefully
  chosen places. There are no such places now.
2010-02-09 15:29:58 +00:00
Tomas Hruby
c6fec6866f No locking in kernel code
- No locking in RTS_(UN)SET macros

- No lock_notify()

- Removed unused lock_send()

- No lock/unlock macros anymore
2010-02-09 15:26:58 +00:00
Kees van Reeuwijk
064cb7583a Lots of small code cleanup: make symbols local, remove unused symbols,
fixed a typo, removed a now unused header file.
Use #include <..> for header files that represent libraries.
2010-02-09 15:23:38 +00:00
Tomas Hruby
391fd926ff TASK_PRIVILEGE and level0() removed
- there are no tasks running, we don't need TASK_PRIVILEGE priviledge anymore

- as there is no ring 1 anymore, there is no need for level0() to call sensitive
  code from ring 1 in ring 0

- 286 related macros removed as clean up
2010-02-09 15:23:31 +00:00
Tomas Hruby
ebba20a65d No CLOCK task
- no kernel tasks are runnable

- clock initialization moved to the end of main()

- the rest of the body of clock_task() is moved to bsp_timer_int_handler() as
  for now we are going to handle this on the bootstrap cpu. A change later is
  possible.
2010-02-09 15:22:43 +00:00
Tomas Hruby
728f0f0c49 Removal of the system task
* Userspace change to use the new kernel calls

	- _taskcall(SYSTASK...) changed to _kernel_call(...)

	- int 32 reused for the kernel calls

	- _do_kernel_call() to make the trap to kernel

	- kernel_call() to make the actuall kernel call from C using
	  _do_kernel_call()

	- unlike ipc call the kernel call always succeeds as kernel is
	  always available, however, kernel may return an error

* Kernel side implementation of kernel calls

	- the SYSTEm task does not run, only the proc table entry is
	  preserved

	- every data_copy(SYSTEM is no data_copy(KERNEL

	- "locking" is an empty operation now as everything runs in
	  kernel

	- sys_task() is replaced by kernel_call() which copies the
	  message into kernel, dispatches the call to its handler and
	  finishes by either copying the results back to userspace (if
	  need be) or by suspending the process because of VM

	- suspended processes are later made runnable once the memory
	  issue is resolved, picked up by the scheduler and only at
	  this time the call is resumed (in fact restarted) which does
	  not need to copy the message from userspace as the message
	  is already saved in the process structure.

	- no ned for the vmrestart queue, the scheduler will restart
	  the system calls

	- no special case in do_vmctl(), all requests remove the
	  RTS_VMREQUEST flag
2010-02-09 15:20:09 +00:00
Tomas Hruby
5e57818431 copy_msg_from_user() and copy_msg_to_user()
- copies a mesage from/to userspace without need of translating
  addresses

- the assumption is that the address space is installed, i.e. ldt and
  cr3 are loaded correctly

- if a pagefault or a general protection occurs while copying from
  userland to kernel (or vice versa) and error is returned which gives
  the caller a chance to respond in a proper way

- error happens _only_ because of a wrong user pointer if the function
  is used correctly

- if the prerequisites of the function do no hold, the function will
  most likely fail as the user address becomes random
2010-02-09 15:15:45 +00:00
Tomas Hruby
ad9ba944d1 Early address space switch
- switch_address_space() implements a switch of the user address space
  for the destination process

- this makes memory of this process easily accessible, e.g. a pointer
  valid in the userspace can be used with a little complexity to
  access the process's memory

- the switch does not happed only just before we return to userspace,
  however, it happens right after we know which process we are going
  to schedule. This happens before we start processing the misc flags
  of this process so its memory is available

- if the process becomes not runnable while processing the mics flags
  we pick a new process and we switch the address space again which
  introduces possibly a little bit more overhead, however, it is
  hopefully hidden by reducing the overheads when we actually access
  the memory
2010-02-09 15:13:52 +00:00
Tomas Hruby
b14a86ca5c Sys calls are called ipc calls now
- the syscalls are pretty much just ipc calls, however, sendrec() is
  used to implement system task (sys) calls

- sendrec() won't be used anymore for this, therefore ipc calls will
  become pure ipc calls
2010-02-09 15:13:07 +00:00
Tomas Hruby
8a03d497b8 System task initialization moved to main()
- the system task initialization code does not really need to be part
  of the system task process. An earlier initialization in kernel is
  cleaner as it does not only initialize the syscalls but also irq
  hooks etc.
2010-02-09 15:12:20 +00:00
David van Moolenbroek
bdd4f5857f Fixes for truncate system calls:
- VFS: check for negative sizes in all truncate calls
- VFS: update file size after truncating with fcntl(F_FREESP)
- VFS: move pos/len checks for F_FREESP with l_len!=0 from FS to VFS
- MFS: do not zero data block for small files when fully truncating
- MFS: do not write out freed indirect blocks after freeing space
- MFS: make truncate work correctly with differing zone/block sizes
- tests: add new test50 for truncate call family
2010-02-09 08:12:37 +00:00
David van Moolenbroek
f029b0e0b1 Kernel: fix sys_irqctl(IRQ_RMPOLICY) 2010-02-09 08:07:47 +00:00
David van Moolenbroek
448f4305e2 a.out.h typo (Bug#398, reported by 7shi) 2010-02-07 12:01:37 +00:00
Tomas Hruby
c5001b0a5f gas2ack fix
- fixed handling of segment overrides for instruction that may use two
  of them in the long format, e.g. movs
2010-02-05 13:53:10 +00:00
Erik van der Kouwe
d70e7ff3b6 Fixes in mkdep.1, suggested by Greg King 2010-02-05 13:07:08 +00:00
Ben Gras
157e82e76a philip's inet tcp fix. 2010-02-04 22:06:10 +00:00
Ben Gras
cb2ee95cf9 only check local benchmark dir if it exists 2010-02-04 18:15:10 +00:00
Ben Gras
4876a324ab also be able to run benchmarks from packages. 2010-02-04 17:52:38 +00:00
Arun Thomas
4b02d003db Import NetBSD's make 2010-02-04 16:52:54 +00:00
Tomas Hruby
8f82633fa2 Removed useless global variable sys_call_code
- we have to same information in the message (m_ptr) where needed
2010-02-03 18:17:01 +00:00
Ben Gras
15b0595013 makefile for benchmarks. 2010-02-03 16:49:15 +00:00
Ben Gras
d6598cc7cd fix for asmconv - stop translating after .sect .end. 2010-02-03 16:03:00 +00:00
Ben Gras
f28a0a5258 remove traces of benchmarks from test/. 2010-02-03 14:32:36 +00:00
Ben Gras
ffb97108c9 move benchmarks to their own dir. 2010-02-03 14:30:02 +00:00
Ben Gras
0985235ba0 forget difference between big and small commands - obsolete with vm. 2010-02-03 14:16:51 +00:00
Erik van der Kouwe
7c9fe576a8 Throw out getpack, replace printenv with a link to env 2010-02-03 13:51:26 +00:00
Ben Gras
35b471ad94 removal of unused vm<->vfs code. 2010-02-03 13:35:17 +00:00
Ben Gras
3bcfb76e45 small asmconv cleanups.
- put asmconv in /usr/bin so it can be invoked without absolute path
 - make it ignore .end in gnu output mode so that it can be invoked
   without '|| true' in the gnu lib makefiles and it doesn't produce the
   messy error message
2010-02-03 13:29:14 +00:00
David van Moolenbroek
c7f1b547cb Statistical profiling fixes:
- PM: get rid of umap warning
- sprofalyze.pl: update with recently added servers and drivers
- sprofalyze.pl: properly truncate process names for sample matching
2010-02-03 12:27:52 +00:00
Tomas Hruby
cca24d06d8 This patch removes the global variables who_p and who_e from the
kernel (sys task).  The main reason is that these would have to become
cpu local variables on SMP.  Once the system task is not a task but a
genuine part of the kernel there is even less reason to have these
extra variables as proc_ptr will already contain all neccessary
information. In addition converting who_e to the process pointer and
back again all the time will be avoided.

Although proc_ptr will contain all important information, accessing it
as a cpu local variable will be fairly expensive, hence the value
would be assigned to some on stack local variable. Therefore it is
better to add the 'caller' argument to the syscall handlers to pass
the value on stack anyway. It also clearly denotes on who's behalf is
the syscall being executed.

This patch also ANSIfies the syscall function headers.

Last but not least, it also fixes a potential bug in virtual_copy_f()
in case the check is disabled. So far the function in case of a
failure could possible reuse an old who_p in case this function had
not been called from the system task.

virtual_copy_f() takes the caller as a parameter too. In case the
checking is disabled, the caller must be NULL and non NULL if it is
enabled as we must be able to suspend the caller.
2010-02-03 09:04:48 +00:00
Erik van der Kouwe
144de8a7b3 Add smallbunzip2 to bzip2 man-page 2010-02-02 15:26:12 +00:00
Erik van der Kouwe
c107dbe1d0 Man-pages on mkdep, cdprobe, loadramdisk and newroot; thanks to Antoine Leca 2010-02-02 15:10:00 +00:00
Kees van Reeuwijk
2db33d5c8c Fix some incorrect testing of bit flags. 2010-02-02 12:24:35 +00:00
Erik van der Kouwe
310876dcec Kill processes which ignore signals thatshould not be ignored 2010-01-31 19:13:20 +00:00
Ben Gras
82ce09234b improve behaviour under VPC, fixes from nicolas tittley. 2010-01-31 18:29:51 +00:00
Kees van Reeuwijk
2fe20e5aaf Fix a complaint about a value return from a void function.
Propagate error codes a bit more.
Some code cleanup.
2010-01-29 14:14:22 +00:00
Kees van Reeuwijk
477b616fe8 Fixed a number of complaints about missing return statements.
Some cases were fixed by declaring the function void, others were fixed
by adding a return <value> statement, thereby avoiding potentially
incorrect behavior (usually in error handling).
Some enum correctness in boot.c.
2010-01-28 13:17:07 +00:00
3354 changed files with 91177 additions and 113405 deletions

View File

@@ -1,6 +1,6 @@
# Master Makefile to compile everything in /usr/src except the system.
MAKE = exec make -$(MAKEFLAGS)
MAKE=make
usage:
@echo ""
@@ -8,13 +8,15 @@ usage:
@echo "Root privileges are required for some actions."
@echo ""
@echo "Usage:"
@echo " make world # Compile everything (libraries & commands)"
@echo " make includes # Install include files from src/"
@echo " make libraries # Compile and install libraries"
@echo " make cmds # Compile all, commands, but don't install"
@echo " make install # Compile and install commands"
@echo " make depend # Generate required .depend files"
@echo " make clean # Remove all compiler results"
@echo " make world # Compile everything (libraries & commands)"
@echo " make includes # Install include files from src/"
@echo " make libraries # Compile and install libraries"
@echo " make commands # Compile all, commands, but don't install"
@echo " make install # Compile and install commands"
@echo " make depend # Generate required .depend files"
@echo " make gnu-includes # Install include files for GCC"
@echo " make gnu-libraries # Compile and install libraries for GCC"
@echo " make clean # Remove all compiler results"
@echo ""
@echo "Run 'make' in tools/ to create a new MINIX configuration."
@echo ""
@@ -27,45 +29,64 @@ usage:
# 'make install' target.
#
# etcfiles has to be done first.
world: includes depend libraries cmds install postinstall
.if ${COMPILER_TYPE} == "ack"
world: mkfiles includes depend libraries install
.elif ${COMPILER_TYPE} == "gnu"
world: mkfiles includes depend gnu-libraries install
.endif
mkfiles:
cp etc/mk/*.mk /etc/mk/
includes:
cd include && $(MAKE) install gcc
cd include && $(MAKE) includes
libraries:
cd lib && $(MAKE) all install
cd lib && sh ack_build.sh obj depend all install
cmds:
if [ -f commands/Makefile ] ; then cd commands && $(MAKE) all; fi
MKHEADERS411=/usr/gnu/libexec/gcc/i386-pc-minix/4.1.1/install-tools/mkheaders
MKHEADERS443=/usr/gnu/libexec/gcc/i686-pc-minix/4.4.3/install-tools/mkheaders
gnu-includes: includes
SHELL=/bin/sh; if [ -f $(MKHEADERS411) ] ; then sh -e $(MKHEADERS411) ; fi
SHELL=/bin/sh; if [ -f $(MKHEADERS443) ] ; then sh -e $(MKHEADERS443) ; fi
install::
if [ -f commands/Makefile ] ; then cd commands && $(MAKE) install; fi
gnu-libraries:
cd lib && sh gnu_build.sh obj depend all install
commands:
cd commands && $(MAKE) all
depend::
mkdep kernel
mkdep servers
mkdep drivers
cd kernel && $(MAKE) $@
cd servers && $(MAKE) $@
cd drivers && $(MAKE) $@
clean::
cd lib && $(MAKE) $@
test ! -f commands/Makefile || { cd commands && $(MAKE) $@; }
cd boot && $(MAKE) depend
cd commands && $(MAKE) depend
cd kernel && $(MAKE) depend
cd servers && $(MAKE) depend
cd drivers && $(MAKE) depend
etcfiles::
cd etc && $(MAKE) install
all::
cd boot && $(MAKE) all
cd commands && $(MAKE) all
cd tools && $(MAKE) all
install::
cd boot && $(MAKE) install
cd man && $(MAKE) install makedb
cd commands && $(MAKE) install
cd share && $(MAKE) install
cd tools && $(MAKE) install
clean::
cd test && $(MAKE) $@
cd boot && $(MAKE) clean
cd commands && $(MAKE) clean
cd tools && $(MAKE) clean
cd lib && sh ack_build.sh clean
cd lib && sh gnu_build.sh clean
cd test && $(MAKE) clean
all install clean::
cd boot && $(MAKE) $@
cd man && $(MAKE) $@ # First manpages, then commands
test ! -f commands/Makefile || { cd commands && $(MAKE) $@; }
cd tools && $(MAKE) $@
cd servers && $(MAKE) $@
postinstall:
cd etc && $(MAKE) $@
cleandepend::
cd boot && $(MAKE) cleandepend
cd commands && $(MAKE) cleandepend
cd tools && $(MAKE) cleandepend

View File

@@ -1,8 +1,4 @@
#!/bin/sh
export CC=cc
export MINIX=1
if perl -e 'exit 0'
then perl -w Run
else echo "perl not installed. please install perl to run unixbench." >&2
exit 1
fi
./Run

View File

@@ -1,123 +1,79 @@
# Makefile for the boot monitor package.
SYS = ..
# XXX: Can only be built with ACK currently
CC:=${CC:C/^gcc/cc/}
COMPILER_TYPE:=ack
CC = exec cc
CC86 = exec cc -mi86 -Was-ncc
CFLAGS = -I$(SYS)
LIBS = -lsys
LD = $(CC) -s -.o
LD86 = $(CC86) -.o
BIN = /usr/bin
MDEC = /usr/mdec
PROGS= bootblock cdbootblock bootexec boot masterboot \
jumpboot installboot edparams
all: bootblock boot edparams masterboot jumpboot installboot addaout
dos: boot.com mkfile.com
SRCS.bootblock= bootblock.s
CPPFLAGS.bootblock.s= ${I86CPPFLAGS}
LDFLAGS.bootblock= ${I86LDFLAGS}
BINDIR.bootblock= /usr/mdec
MAN.bootblock=
bootblock: bootblock.s
$(LD86) -com -o $@ bootblock.s
SRCS.cdbootblock= cdbootblock.s
CPPFLAGS.cdbootblock.s= ${I86CPPFLAGS} -DCDBOOT
LDFLAGS.cdbootblock= ${I86LDFLAGS}
BINDIR.cdbootblock= /usr/mdec
MAN.cdbootblock=
masterboot: masterboot.s
$(LD86) -com -o $@ masterboot.s
SRCS.bootexec= boothead.s boot.c bootimage.c rawfs86.c
CPPFLAGS.boothead.s= ${I86CPPFLAGS}
CPPFLAGS.boot.c= ${I86CPPFLAGS}
CPPFLAGS.bootimage.c= ${I86CPPFLAGS}
CPPFLAGS.rawfs86.c= ${I86CPPFLAGS}
LDFLAGS.bootexec= ${I86LDFLAGS}
DPADD.bootexec= ${LIBSYS}
LDADD.bootexec= -lsys
BINDIR.bootexec= /usr/mdec
MAN.bootexec=
jumpboot: jumpboot.s
$(LD86) -com -o $@ jumpboot.s
BINDIR.boot= /usr/mdec
MAN.boot=
boot.o: boot.c
$(CC86) $(CFLAGS) -c boot.c
SRCS.masterboot= masterboot.s
CPPFLAGS.masterboot.s= ${I86CPPFLAGS}
LDFLAGS.masterboot= ${I86LDFLAGS}
BINDIR.masterboot= /usr/mdec
MAN.masterboot=
bootimage.o: bootimage.c
$(CC86) $(CFLAGS) -c bootimage.c
SRCS.jumpboot= jumpboot.s
CPPFLAGS.jumpboot.s= ${I86CPPFLAGS}
LDFLAGS.jumpboot= ${I86LDFLAGS}
BINDIR.jumpboot= /usr/mdec
MAN.jumpboot=
rawfs86.o: rawfs.c rawfs.o
SRCS.installboot= installboot.c rawfs.c
BINDIR.installboot= /usr/bin
MAN.installboot=
SRCS.edparams= edparams.c rawfs.c
CPPFLAGS.edparams.c= -DUNIX
BINDIR.edparams= /usr/bin
MAN.edparams=
rawfs86.c: rawfs.c
ln -f rawfs.c rawfs86.c
$(CC86) $(CFLAGS) -c rawfs86.c
rm rawfs86.c
-cmp -s rawfs.o rawfs86.o && ln -f rawfs.o rawfs86.o
boot: boothead.s boot.o bootimage.o rawfs86.o
$(LD86) -o bootexec \
boothead.s boot.o bootimage.o rawfs86.o $(LIBS)
install -S 12kb bootexec
# This is code that is executed when used on a bootable
# CD, as its entry point is the start of the file then.
# It jumps over the a.out header into the part of the
# code in boothead.s where the code knows it's booting
# from CD if entered there.
( printf '\xeb\x3e ' ; cat bootexec ) >boot
chmod 755 boot
edparams.o: boot.c
edparams.c: boot.c
ln -f boot.c edparams.c
$(CC) $(CFLAGS) -DUNIX -c edparams.c
rm edparams.c
edparams: edparams.o rawfs.o
$(CC) $(CFLAGS) $(STRIP) -o $@ edparams.o rawfs.o
install -S 16kw edparams
cdbootblock.s: bootblock.s
ln -f bootblock.s cdbootblock.s
dosboot.o: boot.c
$(CC86) $(CFLAGS) -DDOS -o $@ -c boot.c
boot: bootexec
install -S 22kb bootexec
cp bootexec boot
doshead.o: doshead.s
$(CC) -mi386 -o $@ -c doshead.s
CPPFLAGS= -I${MINIXSRCDIR}
AFLAGS= -I${MINIXSRCDIR}
I86CPPFLAGS= -mi86 -Was-ncc
I86LDFLAGS= -mi86 -Was-ncc -.o -com
dosboot: doshead.o dosboot.o bootimage.o rawfs86.o
$(LD86) -com -o $@ \
doshead.o dosboot.o bootimage.o rawfs86.o $(LIBS)
STRIPFLAG= -s
boot.com: dosboot
exec sh a.out2com dosboot boot.com
CLEANFILES+= rawfs86.c edparams.c cdbootblock.s
mkfile: mkfhead.s mkfile.c
$(LD) -.o -mi86 -com -o $@ mkfhead.s mkfile.c $(LIBS)
mkfile.com: mkfile
exec sh a.out2com mkfile mkfile.com
installboot: installboot.o rawfs.o
$(CC) $(STRIP) -o installboot installboot.o rawfs.o
install -S 6kw installboot
addaout: addaout.o
$(CC) -o addaout addaout.o
installboot.o bootimage.o: image.h
boot.o bootimage.o dosboot.o edparams.o: boot.h
rawfs.o rawfs86.o installboot.o boot.o bootimage.o: rawfs.h
install: $(MDEC)/bootblock $(MDEC)/boot $(MDEC)/masterboot \
$(MDEC)/jumpboot $(BIN)/installboot $(BIN)/edparams
dosinstall: $(MDEC)/boot.com $(MDEC)/mkfile.com
$(MDEC)/bootblock: bootblock
install -cs -o bin -m 644 $? $@
$(MDEC)/boot: boot
install -cs -o bin -m 644 $? $@
$(MDEC)/boot.com: boot.com
install -c -m 644 $? $@
$(MDEC)/mkfile.com: mkfile.com
install -c -m 644 $? $@
$(MDEC)/masterboot: masterboot
install -cs -o bin -m 644 $? $@
$(MDEC)/jumpboot: jumpboot
install -cs -o bin -m 644 $? $@
$(BIN)/installboot: installboot
install -cs -o bin $? $@
$(BIN)/addaout: addaout
install -cs -o bin $? $@
$(BIN)/edparams: edparams
install -cs -o bin $? $@
clean:
rm -f *.bak *.o
rm -f bootblock addaout installboot boot masterboot jumpboot edparams
rm -f dosboot boot.com mkfile mkfile.com
.include <minix.prog.mk>

View File

@@ -20,34 +20,35 @@
#define OUTPUT_FILE 2
/* Report problems. */
void report(char *problem, char *message)
static void report(const char *problem, const char *message)
{
fprintf(stderr, "%s:\n", problem);
fprintf(stderr, " %s\n\n", message);
}
int copy_data(int srcfd, int dstfd)
static int copy_data(int srcfd, int dstfd)
{
char buf[8192];
ssize_t n;
int total=0;
/** FIXME: handle error from read() */
/* Copy the little bytes themselves. (Source from cp.c). */
while ((n= read(srcfd, buf, sizeof(buf))) > 0) {
char *bp = buf;
ssize_t r;
ssize_t r = 0;
/** FIXME: handle error from write() */
while (n > 0 && (r= write(dstfd, bp, n)) > 0) {
bp += r;
n -= r;
total += r;
}
if (r <= 0) {
if (r == 0) {
fprintf(stderr, "Warning: EOF writing to output file.\n");
return(-1);
}
if (r == 0) {
fprintf(stderr, "Warning: EOF writing to output file.\n");
return(-1);
}
}
return(total);
@@ -62,8 +63,7 @@ int main(int argc, char **argv)
int fdin, fdout;
char * bp;
int n,r;
int total_size=0;
int result;
int total_size;
/* Check if command line arguments are present, or print usage. */
if (argc!=3) {
@@ -113,13 +113,13 @@ int main(int argc, char **argv)
bp = (char *) &aout;
n = sizeof(aout);
lseek(fdout, 0, SEEK_SET);
lseek(fdout, 0L, SEEK_SET);
while (n > 0 && (r= write(fdout, bp, n)) > 0) {
bp += r;
n -= r;
}
printf("Prepended data file (%u bytes) with a.out header (%u bytes).\n",
printf("Prepended data file (%d bytes) with a.out header (%u bytes).\n",
total_size, sizeof(aout));
printf("Done.\n");

View File

@@ -17,8 +17,8 @@ char version[]= "2.20";
#include <limits.h>
#include <string.h>
#include <errno.h>
#include <ibm/partition.h>
#include <ibm/bios.h>
#include <machine/partition.h>
#include <machine/bios.h>
#include <minix/config.h>
#include <minix/type.h>
#include <minix/dmap.h>
@@ -64,7 +64,7 @@ static int block_size;
*/
unsigned char boot_spec[24];
char *bios_err(int err)
static const char *bios_err(int err)
/* Translate BIOS error code to a readable string. (This is a rare trait
* known as error checking and reporting. Take a good look at it, you won't
* see it often.)
@@ -125,7 +125,7 @@ char *bios_err(int err)
* sector addressing, we check if the device is a CD in readsectors() and if so,
* read it into our own buffer first
*/
int readsectors(u32_t bufaddr, u32_t sector, U8_t count)
int readsectors(u32_t bufaddr, u32_t sector, u8_t count)
{
#define CDSECTOR_SIZE 2048
static char cdbuf[CDSECTOR_SIZE];
@@ -168,7 +168,7 @@ char *unix_err(int err)
}
}
void rwerr(char *rw, off_t sec, int err)
static void rwerr(const char *rw, off_t sec, int err)
{
printf("\n%s error 0x%02x (%s) at sector %ld absolute\n",
rw, err, bios_err(err), sec);
@@ -208,8 +208,8 @@ struct biosdev {
int device; /* Device to edit parameters. */
} bootdev;
struct termios termbuf;
int istty;
static struct termios termbuf;
static int istty;
void quit(int status)
{
@@ -219,13 +219,13 @@ void quit(int status)
#define exit(s) quit(s)
void report(char *label)
void report(const char *label)
/* edparams: label: No such file or directory */
{
fprintf(stderr, "edparams: %s: %s\n", label, strerror(errno));
}
void fatal(char *label)
void fatal(const char *label)
{
report(label);
exit(1);
@@ -338,7 +338,7 @@ int getch(void)
#endif /* UNIX */
char *readline(void)
static char *readline(void)
/* Read a line including a newline with echoing. */
{
char *line;
@@ -375,13 +375,13 @@ char *readline(void)
return line;
}
int sugar(char *tok)
static int sugar(const char *tok)
/* Recognize special tokens. */
{
return strchr("=(){};\n", tok[0]) != nil;
}
char *onetoken(char **aline)
static char *onetoken(char **aline)
/* Returns a string with one token for tokenize. */
{
char *line= *aline;
@@ -429,7 +429,7 @@ typedef struct token {
char *token;
} token;
token **tokenize(token **acmds, char *line)
static token **tokenize(token **acmds, char *line)
/* Takes a line apart to form tokens. The tokens are inserted into a command
* chain at *acmds. Tokenize returns a reference to where another line could
* be added. Tokenize looks at spaces as token separators, and recognizes only
@@ -450,10 +450,10 @@ token **tokenize(token **acmds, char *line)
return acmds;
}
token *cmds; /* String of commands to execute. */
int err; /* Set on an error. */
static token *cmds; /* String of commands to execute. */
static int err; /* Set on an error. */
char *poptoken(void)
static char *poptoken(void)
/* Pop one token off the command chain. */
{
token *cmd= cmds;
@@ -465,7 +465,7 @@ char *poptoken(void)
return tok;
}
void voidtoken(void)
static void voidtoken(void)
/* Remove one token from the command chain. */
{
free(poptoken());
@@ -480,7 +480,7 @@ void parse_code(char *code)
(void) tokenize(&cmds, code);
}
int interrupt(void)
static int interrupt(void)
/* Clean up after an ESC has been typed. */
{
if (escape()) {
@@ -493,14 +493,14 @@ int interrupt(void)
#if BIOS
int activate;
static int activate;
struct biosdev {
char name[8];
int device, primary, secondary;
} bootdev, tmpdev;
int get_master(char *master, struct part_entry **table, u32_t pos)
static int get_master(char *master, struct part_entry **table, u32_t pos)
/* Read a master boot sector and its partition table. */
{
int r, n;
@@ -526,7 +526,7 @@ int get_master(char *master, struct part_entry **table, u32_t pos)
return 0;
}
void initialize(void)
static void initialize(void)
{
char master[SECTOR_SIZE];
struct part_entry *table[NR_PARTITIONS];
@@ -715,35 +715,35 @@ void initialize(void)
/* Reserved names: */
enum resnames {
R_NULL, R_BOOT, R_CTTY, R_DELAY, R_ECHO, R_EXIT, R_HELP,
R_LS, R_MENU, R_OFF, R_SAVE, R_SET, R_TRAP, R_UNSET
R_LS, R_MENU, R_OFF, R_SAVE, R_SET, R_TRAP, R_UNSET, R_RESET
};
char resnames[][6] = {
static char resnames[][6] = {
"", "boot", "ctty", "delay", "echo", "exit", "help",
"ls", "menu", "off", "save", "set", "trap", "unset",
"ls", "menu", "off", "save", "set", "trap", "unset", "reset",
};
/* Using this for all null strings saves a lot of memory. */
#define null (resnames[0])
int reserved(char *s)
static enum resnames reserved(const char *s)
/* Recognize reserved strings. */
{
int r;
enum resnames r;
for (r= R_BOOT; r <= R_UNSET; r++) {
for (r= R_BOOT; r <= R_RESET; r++) {
if (strcmp(s, resnames[r]) == 0) return r;
}
return R_NULL;
}
void sfree(char *s)
static void sfree(char *s)
/* Free a non-null string. */
{
if (s != nil && s != null) free(s);
}
char *copystr(char *s)
static char *copystr(const char *s)
/* Copy a non-null string using malloc. */
{
char *c;
@@ -754,12 +754,12 @@ char *copystr(char *s)
return c;
}
int is_default(environment *e)
static int is_default(const environment *e)
{
return (e->flags & E_SPECIAL) && e->defval == nil;
}
environment **searchenv(char *name)
static environment **searchenv(const char *name)
{
environment **aenv= &env;
@@ -773,7 +773,7 @@ environment **searchenv(char *name)
#define b_getenv(name) (*searchenv(name))
/* Return the environment *structure* belonging to name, or nil if not found. */
char *b_value(char *name)
char *b_value(const char *name)
/* The value of a variable. */
{
environment *e= b_getenv(name);
@@ -781,7 +781,7 @@ char *b_value(char *name)
return e == nil || !(e->flags & E_VAR) ? nil : e->value;
}
char *b_body(char *name)
static char *b_body(const char *name)
/* The value of a function. */
{
environment *e= b_getenv(name);
@@ -789,7 +789,8 @@ char *b_body(char *name)
return e == nil || !(e->flags & E_FUNCTION) ? nil : e->value;
}
int b_setenv(int flags, char *name, char *arg, char *value)
static int b_setenv(int flags, const char *name, const char *arg,
const char *value)
/* Change the value of an environment variable. Returns the flags of the
* variable if you are not allowed to change it, 0 otherwise.
*/
@@ -838,7 +839,7 @@ int b_setvar(int flags, char *name, char *value)
return r;
}
void b_unset(char *name)
void b_unset(const char *name)
/* Remove a variable from the environment. A special variable is reset to
* its default value.
*/
@@ -864,7 +865,7 @@ void b_unset(char *name)
}
}
long a2l(char *a)
long a2l(const char *a)
/* Cheap atol(). */
{
int sign= 1;
@@ -894,7 +895,7 @@ char *ul2a10(u32_t n)
return ul2a(n, 10);
}
unsigned a2x(char *a)
unsigned a2x(const char *a)
/* Ascii to hex. */
{
unsigned n= 0;
@@ -915,11 +916,11 @@ unsigned a2x(char *a)
return n;
}
void get_parameters(void)
static void get_parameters(void)
{
char params[SECTOR_SIZE + 1];
token **acmds;
int r, bus, processor;
int r, processor;
memory *mp;
static char bus_type[][4] = {
"xt", "at", "mca"
@@ -997,14 +998,14 @@ void get_parameters(void)
#endif
}
char *addptr;
static char *addptr;
void addparm(char *n)
static void addparm(const char *n)
{
while (*n != 0 && *addptr != 0) *addptr++ = *n++;
}
void save_parameters(void)
static void save_parameters(void)
/* Save nondefault environment variables to the bootparams sector. */
{
environment *e;
@@ -1045,7 +1046,7 @@ void save_parameters(void)
}
}
void show_env(void)
static void show_env(void)
/* Show the environment settings. */
{
environment *e;
@@ -1116,7 +1117,6 @@ dev_t name2dev(char *name)
{
dev_t dev;
ino_t ino;
int drive;
struct stat st;
char *n, *s;
@@ -1415,17 +1415,19 @@ int exec_bootstrap(void)
return r;
bootstrap(device, active);
return 0;
}
void boot_device(char *devname)
static void boot_device(char *devname)
/* Boot the device named by devname. */
{
dev_t dev= name2dev(devname);
int save_dev= device;
int r;
char *err;
const char *err;
if (tmpdev.device < 0) {
/* FIXME: clearer error message. */
if (dev != -1) printf("Can't boot from %s\n", devname);
return;
}
@@ -1443,7 +1445,7 @@ void boot_device(char *devname)
(void) dev_open();
}
void ctty(char *line)
static void ctty(char *line)
{
if (line == nil) {
serial_line = -1;
@@ -1458,13 +1460,13 @@ void ctty(char *line)
#else /* DOS */
void boot_device(char *devname)
static void boot_device(char *devname)
/* No booting of other devices under DOS. */
{
printf("Can't boot devices under DOS\n");
}
void ctty(char *line)
static void ctty(char *line)
/* Don't know how to handle serial lines under DOS. */
{
printf("No serial line support under DOS\n");
@@ -1473,7 +1475,7 @@ void ctty(char *line)
#endif /* DOS */
#endif /* BIOS */
void ls(char *dir)
static void ls(char *dir)
/* List the contents of a directory. */
{
ino_t ino;
@@ -1492,24 +1494,24 @@ void ls(char *dir)
}
(void) r_readdir(name); /* Skip ".." too. */
while ((ino= r_readdir(name)) != 0) printf("%s/%s\n", dir, name);
while (r_readdir(name) != 0) printf("%s/%s\n", dir, name);
}
u32_t milli_time(void)
static u32_t milli_time(void)
{
return get_tick() * MSEC_PER_TICK;
}
u32_t milli_since(u32_t base)
static u32_t milli_since(u32_t base)
{
return (milli_time() + (TICKS_PER_DAY*MSEC_PER_TICK) - base)
% (TICKS_PER_DAY*MSEC_PER_TICK);
}
char *Thandler;
u32_t Tbase, Tcount;
static char *Thandler;
static u32_t Tbase, Tcount;
void unschedule(void)
static void unschedule(void)
/* Invalidate a waiting command. */
{
alarm(0);
@@ -1520,7 +1522,7 @@ void unschedule(void)
}
}
void schedule(long msec, char *cmd)
static void schedule(long msec, char *cmd)
/* Schedule command at a certain time from now. */
{
unschedule();
@@ -1536,7 +1538,7 @@ int expired(void)
return (Thandler != nil && milli_since(Tbase) >= Tcount);
}
void delay(char *msec)
void delay(const char *msec)
/* Delay for a given time. */
{
u32_t base, count;
@@ -1551,7 +1553,7 @@ void delay(char *msec)
} while (!interrupt() && !expired() && milli_since(base) < count);
}
enum whatfun { NOFUN, SELECT, DEFFUN, USERFUN } menufun(environment *e)
static enum whatfun { NOFUN, SELECT, DEFFUN, USERFUN } menufun(const environment *e)
{
if (!(e->flags & E_FUNCTION) || e->arg[0] == 0) return NOFUN;
if (e->arg[1] != ',') return SELECT;
@@ -1586,6 +1588,7 @@ void menu(void)
case SELECT:
printf(" %c Select %s kernel\n", e->arg[0],e->name);
break;
case NOFUN:
default:;
}
}
@@ -1654,12 +1657,12 @@ void help(void)
}
}
void execute(void)
static void execute(void)
/* Get one command from the command chain and execute it. */
{
token *second, *third, *fourth, *sep;
char *name;
int res;
enum resnames res;
size_t n= 0;
if (err) {
@@ -1874,6 +1877,7 @@ void execute(void)
case R_EXIT: exit(0);
case R_OFF: off(); ok= 1; break;
case R_CTTY: ctty(nil); ok= 1; break;
case R_RESET: reset(); ok= 1; break;
}
/* Command to check bootparams: */
@@ -1914,7 +1918,7 @@ int run_trailer(void)
return !err;
}
void monitor(void)
static void monitor(void)
/* Read a line and tokenize it. */
{
char *line;
@@ -2026,6 +2030,9 @@ void main(int argc, char **argv)
}
exit(0);
}
reset() { }
#endif /* UNIX */
/*

View File

@@ -93,7 +93,7 @@ void raw_copy(u32_t dstaddr, u32_t srcaddr, u32_t count);
/* Copy bytes from anywhere to anywhere. */
u16_t get_word(u32_t addr);
/* Get a word from anywhere. */
void put_word(u32_t addr, U16_t word);
void put_word(u32_t addr, u16_t word);
/* Put a word anywhere. */
void relocate(void);
/* Switch to a copy of this program. */
@@ -101,12 +101,12 @@ int dev_open(void), dev_close(void);
/* Open device and determine params / close device. */
int dev_boundary(u32_t sector);
/* True if sector is on a track boundary. */
int readsectors(u32_t bufaddr, u32_t sector, U8_t count);
int readsectors(u32_t bufaddr, u32_t sector, u8_t count);
/* Read 1 or more sectors from "device". */
int writesectors(u32_t bufaddr, u32_t sector, U8_t count);
int writesectors(u32_t bufaddr, u32_t sector, u8_t count);
/* Write 1 or more sectors to "device". */
int biosreadsectors(u32_t bufaddr, u32_t sector, U8_t count);
int biosreadsectors(u32_t bufaddr, u32_t sector, u8_t count);
int getch(void);
/* Read a keypress. */
@@ -167,9 +167,9 @@ typedef struct environment {
EXTERN environment *env; /* Lists the environment. */
char *b_value(char *name); /* Get/set the value of a variable. */
char *b_value(const char *name); /* Get/set the value of a variable. */
int b_setvar(int flags, char *name, char *value);
void b_unset(char *name);
void b_unset(const char *name);
void parse_code(char *code); /* Parse boot monitor commands. */
@@ -187,9 +187,9 @@ void readerr(off_t sec, int err);
/* Report a read error. */
char *ul2a(u32_t n, unsigned b), *ul2a10(u32_t n);
/* Transform u32_t to ASCII at base b or base 10. */
long a2l(char *a);
long a2l(const char *a);
/* Cheap atol(). */
unsigned a2x(char *a);
unsigned a2x(const char *a);
/* ASCII to hex. */
dev_t name2dev(char *name);
/* Translate a device name to a device number. */
@@ -213,7 +213,7 @@ EXTERN char *drun; /* Initial command from DOS command line. */
#endif
void readblock(off_t, char *, int);
void delay(char *);
void delay(const char *);
/*
* $PchId: boot.h,v 1.12 2002/02/27 19:42:45 philip Exp $

View File

@@ -1,3 +1,4 @@
#
! Bootblock 1.5 - Minix boot block. Author: Kees J. Bot
! 21 Dec 1991
!
@@ -18,15 +19,21 @@
LOADOFF = 0x7C00 ! 0x0000:LOADOFF is where this code is loaded
BOOTSEG = 0x1000 ! Secondary boot code segment.
#ifdef CDBOOT
BOOTOFF = 0x0050 ! Offset into /boot above header
#else
BOOTOFF = 0x0030 ! Offset into /boot above header
#endif
BUFFER = 0x0600 ! First free memory
#ifndef CDBOOT /* just constants, but make no sense for CDs */
LOWSEC = 8 ! Offset of logical first sector in partition
! table
! Variables addressed using bp register
device = 0 ! The boot device
lowsec = 2 ! Offset of boot partition within drive
secpcyl = 6 ! Sectors per cylinder = heads * sectors
#endif
device = 0 ! The boot device
.text
@@ -51,18 +58,21 @@ boot:
mov di, #LOADOFF+sectors ! char *di = sectors;
#ifndef CDBOOT
testb dl, dl ! Winchester disks if dl >= 0x80
jge floppy
#endif
winchester:
#ifndef CDBOOT
! Get the offset of the first sector of the boot partition from the partition
! table. The table is found at es:si, the lowsec parameter at offset LOWSEC.
eseg
les ax, LOWSEC(si) ! es:ax = LOWSEC+2(si):LOWSEC(si)
mov lowsec+0(bp), ax ! Low 16 bits of partition's first sector
mov lowsec+2(bp), es ! High 16 bits of partition's first sector
mov lowsec+0(bp), ax ! Low 16 bits of partitions first sector
mov lowsec+2(bp), es ! High 16 bits of partitions first sector
! Get the drive parameters, the number of sectors is bluntly written into the
! floppy disk sectors/track array.
@@ -72,8 +82,10 @@ winchester:
andb cl, #0x3F ! cl = max sector number (1-origin)
movb (di), cl ! Number of sectors per track
incb dh ! dh = 1 + max head number (0-origin)
#endif
jmp loadboot
#ifndef CDBOOT
! Floppy:
! Execute three read tests to determine the drive type. Test for each floppy
! type by reading the last sector on the first track. If it fails, try a type
@@ -101,13 +113,16 @@ floppy: xorb ah, ah ! Reset drive
jc next ! Error, try the next floppy type
success:movb dh, #2 ! Load number of heads for multiply
#endif
loadboot:
! Load /boot from the boot device
#ifndef CDBOOT
movb al, (di) ! al = (di) = sectors per track
mulb dh ! dh = heads, ax = heads * sectors
mov secpcyl(bp), ax ! Sectors per cylinder = heads * sectors
#endif
mov ax, #BOOTSEG ! Segment to load /boot into
mov es, ax
@@ -117,6 +132,7 @@ load:
mov ax, 1(si) ! Get next sector number: low 16 bits
movb dl, 3(si) ! Bits 16-23 for your up to 8GB partition
xorb dh, dh ! dx:ax = sector within partition
#ifndef CDBOOT
add ax, lowsec+0(bp)
adc dx, lowsec+2(bp)! dx:ax = sector within drive
cmp dx, #[1024*255*63-255]>>16 ! Near 8G limit?
@@ -136,13 +152,14 @@ load:
movb al, (di) ! Sectors per track - Sector number (0-origin)
subb al, ah ! = Sectors left on this track
cmpb al, (si) ! Compare with # sectors to read
jbe read ! Can't read past the end of a cylinder?
jbe read ! Cant read past the end of a cylinder?
movb al, (si) ! (si) < sectors left on this track
read: push ax ! Save al = sectors to read
movb ah, #0x02 ! Code for disk read (all registers in use now!)
int 0x13 ! Call the BIOS for a read
pop cx ! Restore al in cl
jmp rdeval
#endif
bigdisk:
movb cl, (si) ! Number of sectors to read
push si ! Save si
@@ -161,6 +178,14 @@ rdeval:
movb al, cl ! Restore al = sectors read
addb bh, al ! bx += 2 * al * 256 (add bytes read)
addb bh, al ! es:bx = where next sector must be read
#ifdef CDBOOT
addb bh, al ! For CDs, a sector is 2048 bytes, so
addb bh, al ! do this 6 more times to get byte count.
addb bh, al
addb bh, al
addb bh, al
addb bh, al
#endif
add 1(si), ax ! Update address by sectors read
adcb 3(si), ah ! Don't forget bits 16-23 (add ah = 0)
subb (si), al ! Decrement sector count by sectors read

View File

@@ -46,25 +46,29 @@
.text
! We assume boot is always linked with a short (32 byte) a.out header and has
! 16 bytes of its own prefix, so 48 bytes to skip. bootblock jumps into us
! at offset 0x30, cd boot code at 0x40
! Set cs right
! (skip short a.out header plus 16 byte preefix)
jmpf boot, LOADSEG+3
.space 11
! Set segment registers and stack pointer using the programs own header!
! The header is either 32 bytes (short form) or 48 bytes (long form). The
! bootblock will jump to address 0x10030 in both cases, calling one of the
! two jmpf instructions below.
!
! CD bootblock jumps to address 0x10050 in both cases.
! entry point when booting from CD
jmpf boot, LOADSEG+3 ! Set cs right (skipping long a.out header)
.space 11 ! jmpf + 11 = 16 bytes
jmpf boot, LOADSEG+2 ! Set cs right (skipping short a.out header)
.space 11 ! jmpf + 11 = 16 bytes
jmpf cdboot, LOADSEG+3
.space 11
.space 11
jmpf cdboot, LOADSEG+2
.space 11
cdboot:
mov bx, #1
jmp commonboot
boot:
mov bx, #0
commonboot:
mov ax, #LOADSEG+1
mov ax, #LOADSEG
mov ds, ax ! ds = header
movb al, a_flags
@@ -129,7 +133,7 @@ sepID:
mov _daddr+0, ax
mov _daddr+2, dx
push ds
mov ax, #LOADSEG+1
mov ax, #LOADSEG
mov ds, ax ! Back to the header once more
mov ax, a_total+0
mov dx, a_total+2 ! dx:ax = data + bss + heap + stack
@@ -297,10 +301,12 @@ smallcopy:
ext_copy:
mov x_dst_desc+2, ax
movb x_dst_desc+4, dl ! Set base of destination segment
movb x_dst_desc+7, dh
mov ax, 8(bp)
mov dx, 10(bp)
mov x_src_desc+2, ax
movb x_src_desc+4, dl ! Set base of source segment
movb x_src_desc+7, dh
mov si, #x_gdt ! es:si = global descriptor table
shr cx, #1 ! Words to move
movb ah, #0x87 ! Code for extended memory move
@@ -1448,6 +1454,11 @@ _scan_keyboard:
outb 0x61
ret
.define _reset
_reset:
lidt idt_zero
int 0x3
.data
.ascii "(null)\0" ! Just in case someone follows a null pointer
.align 2
@@ -1455,6 +1466,8 @@ c60: .data2 60 ! Constants for MUL and DIV
c1024: .data2 1024
c1080: .data2 1080
c19663: .data2 19663
idt_zero:
.data4 0,0
! Global descriptor tables.
UNSET = 0 ! Must be computed

View File

@@ -22,12 +22,19 @@
#include <sys/video.h>
#include <kernel/const.h>
#include <kernel/type.h>
#include <ibm/partition.h>
#include <machine/partition.h>
#include "rawfs.h"
#include "image.h"
#include "boot.h"
static int block_size = 0;
static int verboseboot = VERBOSEBOOT_QUIET;
#define DEBUG_PRINT(params, level) do { \
if (verboseboot >= (level)) printf params; } while (0)
#define DEBUGBASIC(params) DEBUG_PRINT(params, VERBOSEBOOT_BASIC)
#define DEBUGEXTRA(params) DEBUG_PRINT(params, VERBOSEBOOT_EXTRA)
#define DEBUGMAX(params) DEBUG_PRINT(params, VERBOSEBOOT_MAX)
extern int serial_line;
extern u16_t vid_port; /* Video i/o port. */
@@ -46,7 +53,8 @@ extern u32_t vid_mem_size; /* Video memory size. */
#define K_INT86 0x0040 /* Requires generic INT support. */
#define K_MEML 0x0080 /* Pass a list of free memory. */
#define K_BRET 0x0100 /* New monitor code on shutdown in boot parameters. */
#define K_ALL 0x01FF /* All feature bits this monitor supports. */
#define K_KHIGH 0x0200 /* Load kernel in extended memory. */
#define K_ALL 0x03FF /* All feature bits this monitor supports. */
/* Data about the different processes. */
@@ -77,7 +85,7 @@ int n_procs; /* Number of processes. */
#define between(a, c, z) ((unsigned) ((c) - (a)) <= ((z) - (a)))
void pretty_image(char *image)
void pretty_image(const char *image)
/* Pretty print the name of the image to load. Translate '/' and '_' to
* space, first letter goes uppercase. An 'r' before a digit prints as
* 'revision'. E.g. 'minix/1.6.16r10' -> 'Minix 1.6.16 revision 10'.
@@ -102,16 +110,20 @@ void pretty_image(char *image)
}
}
#define RAW_ALIGN 16
#define BUFSIZE_ZEROS 128
void raw_clear(u32_t addr, u32_t count)
/* Clear "count" bytes at absolute address "addr". */
{
static char zeros[128];
static char zerosdata[BUFSIZE_ZEROS + RAW_ALIGN];
char *zeros = zerosdata + RAW_ALIGN - (unsigned) &zerosdata % RAW_ALIGN;
u32_t dst;
u32_t zct;
zct= sizeof(zeros);
zct= BUFSIZE_ZEROS;
if (zct > count) zct= count;
raw_copy(addr, mon2abs(&zeros), zct);
raw_copy(addr, mon2abs(zeros), zct);
count-= zct;
while (count > 0) {
@@ -223,7 +235,7 @@ void patch_sizes(void)
put_word(process[FS].data + P_INIT_OFF+4, data_size);
}
int selected(char *name)
int selected(const char *name)
/* True iff name has no label or the proper label. */
{
char *colon, *label;
@@ -238,7 +250,7 @@ int selected(char *name)
return cmp == 0;
}
u32_t proc_size(struct image_header *hdr)
static u32_t proc_size(const struct image_header *hdr)
/* Return the size of a process in sectors as found in an image. */
{
u32_t len= hdr->process.a_text;
@@ -282,9 +294,10 @@ char *get_sector(u32_t vsec)
u32_t sec;
int r;
#define SECBUFS 16
static char buf[SECBUFS * SECTOR_SIZE];
static char bufdata[SECBUFS * SECTOR_SIZE + RAW_ALIGN];
static size_t count; /* Number of sectors in the buffer. */
static u32_t bufsec; /* First Sector now in the buffer. */
char *buf = bufdata + RAW_ALIGN - (unsigned) &bufdata % RAW_ALIGN;
if (vsec == 0) count= 0; /* First sector; initialize. */
@@ -365,10 +378,20 @@ int get_segment(u32_t *vsec, long *size, u32_t *addr, u32_t limit)
if ((buf= get_sector((*vsec)++)) == nil) return 0;
cnt= SECTOR_SIZE;
}
if (*addr + click_size > limit) { errno= ENOMEM; return 0; }
if (*addr + click_size > limit)
{
DEBUGEXTRA(("get_segment: out of memory; "
"addr=0x%lx; limit=0x%lx; size=%lx\n",
*addr, limit, size));
errno= ENOMEM;
return 0;
}
n= click_size;
if (n > cnt) n= cnt;
DEBUGMAX(("raw_copy(0x%lx, 0x%lx/0x%x, 0x%lx)... ",
*addr, mon2abs(buf), buf, n));
raw_copy(*addr, mon2abs(buf), n);
DEBUGMAX(("done\n"));
*addr+= n;
*size-= n;
buf+= n;
@@ -377,7 +400,9 @@ int get_segment(u32_t *vsec, long *size, u32_t *addr, u32_t limit)
/* Zero extend to a click. */
n= align(*addr, click_size) - *addr;
DEBUGMAX(("raw_clear(0x%lx, 0x%lx)... ", *addr, n));
raw_clear(*addr, n);
DEBUGMAX(("done\n"));
*addr+= n;
*size-= n;
return 1;
@@ -400,7 +425,7 @@ static void restore_screen(void)
sizeof(boot_tty_info));
if(boot_tty_info.magic == TTYMAGIC) {
if(boot_tty_info.flags & (BTIF_CONSORIGIN|BTIF_CONSCURSOR) ==
if((boot_tty_info.flags & (BTIF_CONSORIGIN|BTIF_CONSCURSOR)) ==
(BTIF_CONSORIGIN|BTIF_CONSCURSOR)) {
int line;
raw_copy(mon2abs(consolescreen),
@@ -430,18 +455,17 @@ void exec_image(char *image)
long a_text, a_data, a_bss, a_stack;
int banner= 0;
long processor= a2l(b_value("processor"));
u16_t mode;
u16_t kmagic, mode;
char *console;
char params[SECTOR_SIZE];
extern char *sbrk(int);
char *verb;
int verbose = 0;
/* The stack is pretty deep here, so check if heap and stack collide. */
(void) sbrk(0);
if ((verb= b_value("verbose")) != nil && a2l(verb) > 0)
verbose = 1;
if ((verb= b_value(VERBOSEBOOTVARNAME)) != nil)
verboseboot = a2l(verb);
printf("\nLoading ");
pretty_image(image);
@@ -471,6 +495,7 @@ void exec_image(char *image)
procp= &process[i];
/* Read header. */
DEBUGEXTRA(("Reading header... "));
for (;;) {
if ((buf= get_sector(vsec++)) == nil) return;
@@ -484,6 +509,7 @@ void exec_image(char *image)
/* Bad label, skip this process. */
vsec+= proc_size(&hdr);
}
DEBUGEXTRA(("done\n"));
/* Sanity check: an 8086 can't run a 386 kernel. */
if (hdr.process.a_cpu == A_I80386 && processor < 386) {
@@ -497,22 +523,35 @@ void exec_image(char *image)
if (i == KERNEL_IDX) {
if (!get_clickshift(vsec, &hdr)) return;
addr= align(addr, click_size);
/* big kernels must be loaded into extended memory */
if (k_flags & K_KHIGH) {
addr= mem[1].base;
limit= mem[1].base + mem[1].size;
}
}
/* Save a copy of the header for the kernel, with a_syms
* misused as the address where the process is loaded at.
*/
DEBUGEXTRA(("raw_copy(0x%x, 0x%lx, 0x%x)... ",
aout + i * A_MINHDR, mon2abs(&hdr.process), A_MINHDR));
hdr.process.a_syms= addr;
raw_copy(aout + i * A_MINHDR, mon2abs(&hdr.process), A_MINHDR);
DEBUGEXTRA(("done\n"));
if (!banner && verbose) {
printf(" cs ds text data bss");
if (k_flags & K_CHMEM) printf(" stack");
putch('\n');
if (!banner) {
DEBUGBASIC((" cs ds text data bss"));
if (k_flags & K_CHMEM) DEBUGBASIC((" stack"));
DEBUGBASIC(("\n"));
banner= 1;
}
/* Segment sizes. */
DEBUGEXTRA(("a_text=0x%lx; a_data=0x%lx; a_bss=0x%lx; a_flags=0x%x)\n",
hdr.process.a_text, hdr.process.a_data,
hdr.process.a_bss, hdr.process.a_flags));
a_text= hdr.process.a_text;
a_data= hdr.process.a_data;
a_bss= hdr.process.a_bss;
@@ -536,7 +575,12 @@ void exec_image(char *image)
/* Separate I&D: two segments. Common I&D: only one. */
if (hdr.process.a_flags & A_SEP) {
/* Read the text segment. */
DEBUGEXTRA(("get_segment(0x%lx, 0x%lx, 0x%lx, 0x%lx)\n",
vsec, a_text, addr, limit));
if (!get_segment(&vsec, &a_text, &addr, limit)) return;
DEBUGEXTRA(("get_segment done vsec=0x%lx a_text=0x%lx "
"addr=0x%lx\n",
vsec, a_text, addr));
/* The data segment follows. */
procp->ds= addr;
@@ -550,19 +594,20 @@ void exec_image(char *image)
}
/* Read the data segment. */
DEBUGEXTRA(("get_segment(0x%lx, 0x%lx, 0x%lx, 0x%lx)\n",
vsec, a_data, addr, limit));
if (!get_segment(&vsec, &a_data, &addr, limit)) return;
DEBUGEXTRA(("get_segment done vsec=0x%lx a_data=0x%lx "
"addr=0x%lx\n",
vsec, a_data, addr));
/* Make space for bss and stack unless... */
if (i != KERNEL_IDX && (k_flags & K_CLAIM)) a_bss= a_stack= 0;
if(verbose) {
printf("%07lx %07lx %8ld %8ld %8ld",
procp->cs, procp->ds,
hdr.process.a_text, hdr.process.a_data,
hdr.process.a_bss
);
}
if ((k_flags & K_CHMEM) && verbose) printf(" %8ld", a_stack);
DEBUGBASIC(("%07lx %07lx %8ld %8ld %8ld",
procp->cs, procp->ds, hdr.process.a_text,
hdr.process.a_data, hdr.process.a_bss));
if (k_flags & K_CHMEM) DEBUGBASIC((" %8ld", a_stack));
/* Note that a_data may be negative now, but we can look at it
* as -a_data bss bytes.
@@ -574,8 +619,10 @@ void exec_image(char *image)
a_bss-= n;
/* Zero out bss. */
DEBUGEXTRA(("\nraw_clear(0x%lx, 0x%lx); limit=0x%lx... ", addr, n, limit));
if (addr + n > limit) { errno= ENOMEM; return; }
raw_clear(addr, n);
DEBUGEXTRA(("done\n"));
addr+= n;
/* And the number of stack clicks. */
@@ -589,7 +636,7 @@ void exec_image(char *image)
/* Process endpoint. */
procp->end= addr;
if(verbose)
if (verboseboot >= VERBOSEBOOT_BASIC)
printf(" %s\n", hdr.name);
else {
u32_t mem;
@@ -598,14 +645,14 @@ void exec_image(char *image)
totalmem += mem;
}
if (i == 0 && (k_flags & K_HIGH)) {
if (i == 0 && (k_flags & (K_HIGH | K_KHIGH)) == K_HIGH) {
/* Load the rest in extended memory. */
addr= mem[1].base;
limit= mem[1].base + mem[1].size;
}
}
if(!verbose)
if (verboseboot < VERBOSEBOOT_BASIC)
printf("(%dk)\n", totalmem/1024);
if ((n_procs= i) == 0) {
@@ -615,14 +662,19 @@ void exec_image(char *image)
}
/* Check the kernel magic number. */
if (get_word(process[KERNEL_IDX].data + MAGIC_OFF) != KERNEL_D_MAGIC) {
printf("Kernel magic number is incorrect\n");
raw_copy(mon2abs(&kmagic),
process[KERNEL_IDX].data + MAGIC_OFF, sizeof(kmagic));
if (kmagic != KERNEL_D_MAGIC) {
printf("Kernel magic number is incorrect (0x%x@0x%lx)\n",
kmagic, process[KERNEL_IDX].data + MAGIC_OFF);
errno= 0;
return;
}
/* Patch sizes, etc. into kernel data. */
DEBUGEXTRA(("patch_sizes()... "));
patch_sizes();
DEBUGEXTRA(("done\n"));
#if !DOS
if (!(k_flags & K_MEML)) {
@@ -632,22 +684,33 @@ void exec_image(char *image)
#endif
/* Run the trailer function just before starting Minix. */
DEBUGEXTRA(("run_trailer()... "));
if (!run_trailer()) { errno= 0; return; }
DEBUGEXTRA(("done\n"));
/* Translate the boot parameters to what Minix likes best. */
DEBUGEXTRA(("params2params(0x%x, 0x%x)... ", params, sizeof(params)));
if (!params2params(params, sizeof(params))) { errno= 0; return; }
DEBUGEXTRA(("done\n"));
/* Set the video to the required mode. */
if ((console= b_value("console")) == nil || (mode= a2x(console)) == 0) {
mode= strcmp(b_value("chrome"), "color") == 0 ? COLOR_MODE :
MONO_MODE;
}
DEBUGEXTRA(("set_mode(%d)... ", mode));
set_mode(mode);
DEBUGEXTRA(("done\n"));
/* Close the disk. */
DEBUGEXTRA(("dev_close()... "));
(void) dev_close();
DEBUGEXTRA(("done\n"));
/* Minix. */
DEBUGEXTRA(("minix(0x%lx, 0x%lx, 0x%lx, 0x%x, 0x%x, 0x%lx)\n",
process[KERNEL_IDX].entry, process[KERNEL_IDX].cs,
process[KERNEL_IDX].ds, params, sizeof(params), aout));
minix(process[KERNEL_IDX].entry, process[KERNEL_IDX].cs,
process[KERNEL_IDX].ds, params, sizeof(params), aout);

View File

@@ -3,7 +3,6 @@
*
* Either make a device bootable or make an image from kernel, mm, fs, etc.
*/
#define nil 0
#define _POSIX_SOURCE 1
#define _MINIX 1
#include <stdio.h>
@@ -40,13 +39,13 @@
#define BOOT_BLOCK_SIZE 1024
void report(char *label)
static void report(const char *label)
/* installboot: label: No such file or directory */
{
fprintf(stderr, "installboot: %s: %s\n", label, strerror(errno));
}
void fatal(char *label)
static void fatal(const char *label)
{
report(label);
exit(1);
@@ -61,12 +60,12 @@ char *basename(char *name)
static char base[IM_NAME_MAX];
char *p, *bp= base;
if ((p= strchr(name, ':')) != nil) {
if ((p= strchr(name, ':')) != NULL) {
while (name <= p && bp < base + IM_NAME_MAX - 1)
*bp++ = *name++;
}
for (;;) {
if ((p= strrchr(name, '/')) == nil) { p= name; break; }
if ((p= strrchr(name, '/')) == NULL) { p= name; break; }
if (*++p != 0) break;
*--p= 0;
}
@@ -75,7 +74,7 @@ char *basename(char *name)
return base;
}
void bread(FILE *f, char *name, void *buf, size_t len)
static void bread(FILE *f, char *name, void *buf, size_t len)
/* Read len bytes. Don't dare return without them. */
{
if (len > 0 && fread(buf, len, 1, f) != 1) {
@@ -85,7 +84,7 @@ void bread(FILE *f, char *name, void *buf, size_t len)
}
}
void bwrite(FILE *f, char *name, void *buf, size_t len)
static void bwrite(FILE *f, const char *name, const void *buf, size_t len)
{
if (len > 0 && fwrite(buf, len, 1, f) != 1) fatal(name);
}
@@ -95,14 +94,14 @@ int making_image= 0;
void read_header(int talk, char *proc, FILE *procf, struct image_header *ihdr)
/* Read the a.out header of a program and check it. If procf happens to be
* nil then the header is already in *image_hdr and need only be checked.
* NULL then the header is already in *image_hdr and need only be checked.
*/
{
int n, big= 0;
static int banner= 0;
struct exec *phdr= &ihdr->process;
if (procf == nil) {
if (procf == NULL) {
/* Header already present. */
n= phdr->a_hdrlen;
} else {
@@ -122,7 +121,7 @@ void read_header(int talk, char *proc, FILE *procf, struct image_header *ihdr)
}
/* Get the rest of the exec header. */
if (procf != nil) {
if (procf != NULL) {
bread(procf, proc, ((char *) phdr) + A_MINHDR,
phdr->a_hdrlen - A_MINHDR);
}
@@ -160,7 +159,7 @@ void read_header(int talk, char *proc, FILE *procf, struct image_header *ihdr)
}
}
void padimage(char *image, FILE *imagef, int n)
void padimage(const char *image, FILE *imagef, int n)
/* Add n zeros to image to pad it to a sector boundary. */
{
while (n > 0) {
@@ -206,16 +205,16 @@ void make_image(char *image, char **procv)
making_image= 1;
if ((imagef= fopen(image, "w")) == nil) fatal(image);
if ((imagef= fopen(image, "w")) == NULL) fatal(image);
for (procn= 0; (proc= *procv++) != nil; procn++) {
for (procn= 0; (proc= *procv++) != NULL; procn++) {
/* Remove the label from the file name. */
if ((file= strchr(proc, ':')) != nil) file++; else file= proc;
if ((file= strchr(proc, ':')) != NULL) file++; else file= proc;
/* Real files please, may need to seek. */
if (stat(file, &st) < 0
|| (errno= EISDIR, !S_ISREG(st.st_mode))
|| (procf= fopen(file, "r")) == nil
|| (procf= fopen(file, "r")) == NULL
) fatal(proc);
/* Read a.out header. */
@@ -296,7 +295,7 @@ void extract_image(char *image)
/* Size of the image. */
len= S_ISREG(st.st_mode) ? st.st_size : -1;
if ((imagef= fopen(image, "r")) == nil) fatal(image);
if ((imagef= fopen(image, "r")) == NULL) fatal(image);
while (len != 0) {
/* Extract a program, first sector is an extended header. */
@@ -307,9 +306,9 @@ void extract_image(char *image)
phdr= ihdr.process;
/* Check header. */
read_header(1, ihdr.name, nil, &ihdr);
read_header(1, ihdr.name, NULL, &ihdr);
if ((procf= fopen(ihdr.name, "w")) == nil) fatal(ihdr.name);
if ((procf= fopen(ihdr.name, "w")) == NULL) fatal(ihdr.name);
if (phdr.a_flags & A_PAL) {
/* A page aligned process contains a header in text. */
@@ -333,8 +332,8 @@ void extract_image(char *image)
}
}
int rawfd; /* File descriptor to open device. */
char *rawdev; /* Name of device. */
static int rawfd; /* File descriptor to open device. */
static const char *rawdev; /* Name of device. */
void readblock(off_t blk, char *buf, int block_size)
/* For rawfs, so that it can read blocks. */
@@ -351,7 +350,7 @@ void readblock(off_t blk, char *buf, int block_size)
}
}
void writeblock(off_t blk, char *buf, int block_size)
void writeblock(off_t blk, const char *buf, int block_size)
/* Add a function to write blocks for local use. */
{
if (lseek(rawfd, blk * block_size, SEEK_SET) < 0
@@ -378,7 +377,7 @@ int raw_install(char *file, off_t *start, off_t *len, int block_size)
devsize= -1;
if (ioctl(rawfd, DIOCGETP, &entry) == 0) devsize= cv64ul(entry.size);
if ((f= fopen(file, "r")) == nil) fatal(file);
if ((f= fopen(file, "r")) == NULL) fatal(file);
/* Copy sectors from file onto the boot device. */
sec= *start;
@@ -486,7 +485,7 @@ void make_bootable(enum howto how, char *device, char *bootblock,
*/
if (stat(bootcode, &st) < 0) fatal(bootcode);
if ((bootf= fopen(bootcode, "r")) == nil) fatal(bootcode);
if ((bootf= fopen(bootcode, "r")) == NULL) fatal(bootcode);
} else {
/* Boot code is present in the file system. */
r_stat(ino, &st);
@@ -496,17 +495,16 @@ void make_bootable(enum howto how, char *device, char *bootblock,
boothdr.a_magic[0]= !A_MAGIC0;
} else {
readblock(addr, buf, block_size);
/* Must skip 16 bytes of 'boot' as that contains code. */
memcpy(&boothdr, buf + 16, sizeof(struct exec));
memcpy(&boothdr, buf, sizeof(struct exec));
}
bootf= nil;
bootf= NULL;
dummy.process= boothdr;
}
/* See if it is an executable (read_header does the check). */
read_header(0, bootcode, bootf, &dummy);
boothdr= dummy.process;
if (bootf != nil) fclose(bootf);
if (bootf != NULL) fclose(bootf);
/* Get all the sector addresses of the secondary boot code. */
max_sector= (boothdr.a_hdrlen + boothdr.a_text
@@ -551,7 +549,7 @@ void make_bootable(enum howto how, char *device, char *bootblock,
/* Get the boot block and patch the pieces in. */
readblock(BOOTBLOCK, buf, BOOT_BLOCK_SIZE);
if ((bootf= fopen(bootblock, "r")) == nil) fatal(bootblock);
if ((bootf= fopen(bootblock, "r")) == NULL) fatal(bootblock);
read_header(0, bootblock, bootf, &dummy);
boothdr= dummy.process;
@@ -596,7 +594,7 @@ void make_bootable(enum howto how, char *device, char *bootblock,
* necessary.
*/
for (parmp= buf + SECTOR_SIZE; parmp < buf + 2*SECTOR_SIZE; parmp++) {
if (*imagev != nil || (control(*parmp) && *parmp != '\n')) {
if (*imagev != NULL || (control(*parmp) && *parmp != '\n')) {
/* Param sector must be initialized. */
memset(buf + SECTOR_SIZE, '\n', SECTOR_SIZE);
break;
@@ -629,10 +627,10 @@ void make_bootable(enum howto how, char *device, char *bootblock,
parmp+= strlen(parmp);
}
while ((labels= *imagev++) != nil) {
while ((labels= *imagev++) != NULL) {
/* Place each kernel image on the boot device. */
if ((image= strchr(labels, ':')) != nil)
if ((image= strchr(labels, ':')) != NULL)
*image++= 0;
else {
if (nolabel) {
@@ -642,23 +640,23 @@ void make_bootable(enum howto how, char *device, char *bootblock,
}
nolabel= 1;
image= labels;
labels= nil;
labels= NULL;
}
len= 0;
if (!raw_install(image, &pos, &len, block_size)) exit(1);
if (labels == nil) {
if (labels == NULL) {
/* Let this image be the default. */
sprintf(parmp, "image=%ld:%ld\n", pos-len, len);
parmp+= strlen(parmp);
}
while (labels != nil) {
while (labels != NULL) {
/* Image is prefixed by a comma separated list of
* labels. Define functions to select label and image.
*/
label= labels;
if ((labels= strchr(labels, ',')) != nil) *labels++ = 0;
if ((labels= strchr(labels, ',')) != NULL) *labels++ = 0;
sprintf(parmp,
"%s(%c){label=%s;image=%ld:%ld;echo %s kernel selected;menu}\n",
@@ -685,7 +683,7 @@ void make_bootable(enum howto how, char *device, char *bootblock,
}
}
void install_master(char *device, char *masterboot, char **guide)
static void install_master(const char *device, char *masterboot, char **guide)
/* Booting a hard disk is a two stage process: The master bootstrap in sector
* 0 loads the bootstrap from sector 0 of the active partition which in turn
* starts the operating system. This code installs such a master bootstrap
@@ -702,7 +700,7 @@ void install_master(char *device, char *masterboot, char **guide)
if ((rawfd= open(rawdev= device, O_RDWR)) < 0) fatal(device);
/* Open the master boot code. */
if ((masf= fopen(masterboot, "r")) == nil) fatal(masterboot);
if ((masf= fopen(masterboot, "r")) == NULL) fatal(masterboot);
/* See if the user is cloning a device. */
if (fstat(fileno(masf), &st) >=0 && S_ISBLK(st.st_mode))
@@ -725,10 +723,10 @@ void install_master(char *device, char *masterboot, char **guide)
memset(buf, 0, PARTPOS);
(void) bread(masf, masterboot, buf, size);
if (guide[0] != nil) {
if (guide[0] != NULL) {
/* Fixate partition to boot. */
char *keys= guide[0];
char *logical= guide[1];
const char *keys= guide[0];
const char *logical= guide[1];
size_t i;
int logfd;
u32_t offset;
@@ -755,7 +753,7 @@ void install_master(char *device, char *masterboot, char **guide)
size += i;
buf[size]= '\r';
if (logical != nil) {
if (logical != NULL) {
if ((logfd= open(logical, O_RDONLY)) < 0
|| ioctl(logfd, DIOCGETP, &geometry) < 0
) {
@@ -782,7 +780,7 @@ void install_master(char *device, char *masterboot, char **guide)
writeblock(BOOTBLOCK, buf, BOOT_BLOCK_SIZE);
}
void usage(void)
static void usage(void)
{
fprintf(stderr,
"Usage: installboot -i(mage) image kernel mm fs ... init\n"
@@ -793,7 +791,7 @@ void usage(void)
exit(1);
}
int isoption(char *option, char *test)
static int isoption(const char *option, const char *test)
/* Check if the option argument is equals "test". Also accept -i as short
* for -image, and the special case -x for -extract.
*/

View File

@@ -21,7 +21,7 @@ int printf(const char *fmt, ...);
#define SEEK_END 2
/* Kernel printf requires a putk() function. */
int putk(int c)
void putk(int c)
{
char ch = c;
@@ -72,7 +72,6 @@ char *strerror(int err)
int main(int argc, char **argv)
{
int i;
static char buf[512];
unsigned long size, mul;
off_t offset;

View File

@@ -2,7 +2,6 @@
* 23 Dec 1991
* Based on readfs by Paul Polderman
*/
#define nil 0
#define _POSIX_SOURCE 1
#define _MINIX 1
#include <sys/types.h>
@@ -286,7 +285,7 @@ off_t r_vir2abs(off_t virblk)
return z;
}
ino_t r_lookup(Ino_t cwd, char *path)
ino_t r_lookup(Ino_t cwd, const char *path)
/* Translates a pathname to an inode number. This is just a nice utility
* function, it only needs r_stat and r_readdir.
*/

View File

@@ -17,7 +17,7 @@
* Return next directory entry or 0 if there are no more.
* Returns -1 and sets errno on error.
*
* ino_t r_lookup(ino_t cwd, char *path);
* ino_t r_lookup(ino_t cwd, const char *path);
* A utility function that translates a pathname to an
* inode number. It starts from directory "cwd" unless
* path starts with a '/', then from ROOT_INO.
@@ -30,14 +30,19 @@
* errors.
*/
#ifndef INC_RAWFS_H
#define INC_RAWFS_H
#define ROOT_INO ((ino_t) 1) /* Inode nr of root dir. */
off_t r_super(int *);
void r_stat(Ino_t file, struct stat *stp);
off_t r_vir2abs(off_t virblockno);
ino_t r_readdir(char *name);
ino_t r_lookup(Ino_t cwd, char *path);
extern off_t r_super(int *);
extern void r_stat(Ino_t file, struct stat *stp);
extern off_t r_vir2abs(off_t virblockno);
extern ino_t r_readdir(char *name);
extern ino_t r_lookup(Ino_t cwd, const char *path);
/*
* $PchId: rawfs.h,v 1.4 1996/04/19 08:16:36 philip Exp $
*/
#endif

View File

@@ -190,6 +190,9 @@ do
16,0)
des="pseudo random number generator" dev=urandom
;;
17,0)
des="hello" dev=hello
;;
BAD,BAD)
des= dev=
;;

View File

@@ -0,0 +1,4 @@
SCRIPTS= DESCRIBE.sh
MAN=
.include <minix.prog.mk>

0
commands/scripts/M.sh → commands/M/M.sh Executable file → Normal file
View File

7
commands/M/Makefile Normal file
View File

@@ -0,0 +1,7 @@
SCRIPTS= M.sh
BINDIR= /bin
MAN=
LINKS+= ${BINDIR}/M ${BINDIR}/U
.include <minix.prog.mk>

View File

@@ -23,7 +23,7 @@ case $#:$1 in
ttypa ttypb ttypc ttypd ttype ttypf \
ttyq0 ttyq1 ttyq2 ttyq3 ttyq4 ttyq5 ttyq6 ttyq7 ttyq8 ttyq9 \
ttyqa ttyqb ttyqc ttyqd ttyqe ttyqf \
eth klog random filter
eth klog random filter hello
;;
0:|1:-\?)
cat >&2 <<EOF
@@ -48,6 +48,7 @@ Where key is one of the following:
kbd # Make /dev/kbd
kbdaux # Make /dev/kbdaux
filter # Make /dev/filter
hello # Make /dev/hello
video # Make /dev/video
std # All standard devices
EOF
@@ -259,6 +260,11 @@ do
$e mknod filter b 11 0
$e chmod 644 filter
;;
hello)
# hello driver
$e mknod hello c 17 0
$e chmod 644 hello
;;
*)
echo "$0: don't know about $dev" >&2
ex=1

View File

@@ -0,0 +1,4 @@
SCRIPTS= MAKEDEV.sh
MAN=
.include <minix.prog.mk>

View File

@@ -1,31 +1,44 @@
# Makefile for commands.
MAKE = exec make -$(MAKEFLAGS)
BZIP2=bzip2-1.0.3
FLEX=flex-2.5.4
.include <minix.own.mk>
SMALLPROGRAMS=`arch` aal advent ash autil awk byacc cawf cron de dhcpd dis88 elle elvis ftp101 ftpd200 ibm indent m4 make mdb mined patch pax profile ps reboot rlogind scripts sh simple syslogd talk talkd telnet telnetd urlget yap zoneinfo
usage:
@echo "Usage: make all # Compile all commands" >&2
@echo " make install # Install the result (run as bin!)" >&2
@echo " make clean # Delete .o files and other junk" >&2
all:
cd zmodem && make
cd $(BZIP2) && /bin/sh build build
set -e; for p in $(SMALLPROGRAMS); do ( cd $$p && make all ); done
install:
set -e; for p in $(SMALLPROGRAMS); do ( cd $$p && make install ); done
cd zmodem && make install
cd $(BZIP2) && make install
cd $(FLEX) && sh build
clean::
cd $(BZIP2) && make clean
cd zmodem && make clean
if [ -f $(FLEX)/Makefile ]; then cd $(FLEX) && make distclean ; fi
for p in $(SMALLPROGRAMS); do ( cd $$p && make clean ); done
SUBDIR= aal add_route adduser advent arp ash at autil awk \
backup badblocks banner basename bigmake binpackage \
binpackages binsizes bzip2 bzip2recover cal calendar \
cat cawf cd cdiff cdprobe cgrep checkhier chmem \
chmod chown chroot ci cksum cleantmp clear cmp co \
comm compress cp crc cron crontab cut datasizes date \
dd de decomp16 DESCRIBE dev2name devsize df dhcpd \
dhrystone diff dirname dis88 du dumpcore easypack \
ed eject elle elvis env expand factor fgrep file \
find finger fingerd fix fold format fortune fsck \
fsck1 ftp101 ftpd200 getty gomoku grep head host \
hostaddr id ifconfig ifdef indent install \
intr ipcrm ipcs irdpd isoread join kill last leave \
lex life loadkeys loadramdisk logger login look lp \
lpd ls lspci M m4 mail make MAKEDEV makewhatis man \
mdb mesg mined mkdep mkdir mkdist mkfifo mkfs mknod \
mkproto modem mount mt netconf newroot nice nm nohup \
nonamed od packit packman passwd paste patch pax \
ping postinstall poweroff pr prep printf printroot \
profile progressbar proto pr_routes ps pwd pwdauth \
ramdisk rarpd rawspeed rcp rdate readall readclock \
readfs reboot remsync rev rget rlogin rlogind rmdir \
rotate rsh rshd sed service setup shar size \
sleep slip sort spell split srccrc stat strings strip \
stty su sum svclog swapfs swifi sync synctree sysenv \
syslogd tail talk talkd tcpd tcpdp tcpstat tee telnet \
telnetd term termcap tget time tinyhalt top touch tr \
truncate tsort ttt tty udpstat umount uname unexpand \
uniq unstack update urlget uud uue version vol wc \
whatis whereis which who whoami write writeisofs \
xargs yacc yap yes zdump zic zmodem
.if ${ARCH} == "i386"
SUBDIR+= atnormalize dosread fdisk loadfont \
mixer autopart part partition playwave postmort \
recwave repartition screendump
SUBDIR+= acd asmconv gas2ack
.endif
.include <minix.subdir.mk>

2
commands/Makefile.inc Normal file
View File

@@ -0,0 +1,2 @@
CPPFLAGS+= -D_MINIX -D_POSIX_SOURCE
BINDIR?=/usr/bin

View File

@@ -1,56 +1,12 @@
# Makefile for aal
CC=exec cc
CFLAGS=-I. -wo -DAAL -DSTB -DNDEBUG -DDISTRIBUTION -D_POSIX_SOURCE -D_MINIX
LDFLAGS=-i
PROG= aal
SRCS= archiver.c print.c rd.c rd_arhdr.c rd_unsig2.c sprint.c \
wr_arhdr.c wr_bytes.c wr_int2.c wr_long.c wr_ranlib.c \
format.c rd_bytes.c system.c write.c long2str.c
CPPFLAGS+= -I${.CURDIR} -DAAL -DSTB -DNDEBUG -DDISTRIBUTION
all: aal
LINKS+= ${BINDIR}/aal ${BINDIR}/ar
MAN=
OFILES= archiver.o \
print.o \
rd.o \
rd_arhdr.o \
rd_unsig2.o \
sprint.o \
wr_arhdr.o \
wr_bytes.o \
wr_int2.o \
wr_long.o \
wr_ranlib.o \
format.o \
rd_bytes.o \
system.o \
write.o \
long2str.o
aal: $(OFILES)
$(CC) $(LDFLAGS) -o aal $(OFILES)
install -S 512k $@
install: /usr/bin/aal /usr/bin/ar
/usr/bin/aal: aal
install -cs -o bin aal $@
/usr/bin/ar: /usr/bin/aal
install -l $? $@
archiver.o:
print.o:
rd.o:
rd_arhdr.o:
rd_unsig2.o:
sprint.o:
wr_arhdr.o:
wr_bytes.o:
wr_int2.o:
wr_long.o:
wr_ranlib.o:
format.o:
rd_bytes.o:
system.o:
write.o:
long2str.o:
clean:
rm -f *.o core *.bak aal
.include <minix.prog.mk>

View File

@@ -25,6 +25,7 @@ static char RcsId[] = "$Header$";
#endif
*/
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef S_IREAD
@@ -47,7 +48,6 @@ struct ranlib *tab;
unsigned int tnum = 0;
char *tstrtab;
unsigned int tssiz = 0;
char *malloc(), *realloc(), *strcpy(), *strncpy();
long time();
unsigned int tabsz, strtabsz;
#else
@@ -68,10 +68,6 @@ typedef char BOOL;
#define MEMBER struct ar_hdr
#define NIL_PTR ((char *) 0)
#define NIL_MEM ((MEMBER *) 0)
#define NIL_LONG ((long *) 0)
#define IO_SIZE (10 * 1024)
#define equal(str1, str2) (!strncmp((str1), (str2), 14))
@@ -136,14 +132,14 @@ char *basename(path)
char *path;
{
register char *ptr = path;
register char *last = NIL_PTR;
register char *last = NULL;
while (*ptr != '\0') {
if (*ptr == '/')
last = ptr;
ptr++;
}
if (last == NIL_PTR)
if (last == NULL)
return path;
if (*(last + 1) == '\0') {
*last = '\0';
@@ -302,7 +298,7 @@ get_member()
again:
if (rd_arhdr(ar_fd, &member) == 0)
return NIL_MEM;
return NULL;
if (member.ar_size < 0) {
error(TRUE, "archive has member with negative size\n");
}
@@ -332,7 +328,7 @@ register char *argv[];
#endif
)
temp_fd = open_archive(temp_arch, CREATE);
while ((member = get_member()) != NIL_MEM) {
while ((member = get_member()) != NULL) {
if (argc > 3) {
for (i = 3; i < argc; i++) {
if (equal(basename(argv[i]), member->ar_name))
@@ -797,4 +793,4 @@ enter_name(namep)
}
tnum++;
}
#endif AAL
#endif /* AAL */

View File

@@ -1,3 +0,0 @@
#!/bin/sh
make clean
make && make install

View File

@@ -12,7 +12,7 @@
# define ACKM "minix"
/* size of local machine, either 0 (for 16 bit address space), or 1 */
# undef BIGMACHINE 1
# undef BIGMACHINE
/* operating system, SYS_5, V7, BSD4_1 or BSD4_2; Do NOT delete the comment
in the next line! */

View File

@@ -44,4 +44,4 @@ extern File _sys_ftab[];
/* system's idea of block */
#define BUFSIZ 1024
#endif __SYSTEM_INCLUDED__
#endif /* __SYSTEM_INCLUDED__ */

13
commands/acd/Makefile Normal file
View File

@@ -0,0 +1,13 @@
# Makefile for acd
.include <minix.own.mk>
PROG= acd
CPPFLAGS+= -DARCH=\"`arch`\" -DDESCR=\"/usr/lib/descr\"
LINKS+= ${BINDIR}/acd ${BINDIR}/cc
FILESDIR= /usr/lib
FILES= acd.descr
FILESNAME= descr
MAN=
.include <minix.prog.mk>

View File

@@ -74,18 +74,6 @@ if $PROGRAM = cc
RTSO = -.c
LIBS = $LIBS + -.c
arg -.mod
if $PROGRAM = m2
ifndef RTSO
RTSO = -.mod
LIBS = $LIBS + -.mod
arg -.p
if $PROGRAM = pc
ifndef RTSO
RTSO = -.p
LIBS = $LIBS + -.p
# Omit the runtime startoff, but keep the libraries.
arg -.o
RTSO =
@@ -315,24 +303,6 @@ transform .i .k
RTSO = -.c
LIBS = $LIBS + -.c
# Compile Modula-2 source to EM-code.
transform .mod .k
ifhash $*
apply .c .i
$ACK_M2 $* $>
ifndef RTSO
RTSO = -.mod
LIBS = $LIBS + -.mod
# Compile Pascal source to EM-code.
transform .p .k
ifhash $*
apply .c .i
$ACK_PC $* $>
ifndef RTSO
RTSO = -.p
LIBS = $LIBS + -.p
# Compact EM to readable EM.
transform .k .e
transform .m .e
@@ -393,23 +363,13 @@ combine (.o .a) .out
rtso =
if $RTSO = -.c
rtso = $A/$ARCH/crtso.o
if $RTSO = -.mod
rtso = $A/$ARCH/m2rtso.o
if $RTSO = -.p
rtso = $A/$ARCH/prtso.o
libm2 = ; libp = ; libd = ; libc = ; libfp =
if (-.mod - $LIBS) = ()
libm2 = $A/$ARCH/libm2.a
libc = $A/$ARCH/libc.a
if (-.p - $LIBS) = ()
libp = $A/$ARCH/libp.a
libc = $A/$ARCH/libc.a
libd = ; libc = ; libfp =
if (-.c - $LIBS) = ()
libd = $A/$ARCH/libd.a
libc = $A/$ARCH/libc.a
if (-fsoft - $LIBS) = ()
libfp = $A/$ARCH/libfp.a
libs = $libm2 $libp $libd $libc $libfp $A/$ARCH/libe.a
libs = $libd $libc $libfp $A/$ARCH/libe.a
ifndef OUT
OUT = a.out
if (-r - $MODEL) = ()
@@ -418,7 +378,7 @@ combine (.o .a) .out
else
# Combine to an executable.
mktemp EXE
$ACK_LED $model -o $EXE $rtso $* $libs $A/$ARCH/end.a
$ACK_LED $model -o $EXE $rtso $* $libs $A/$ARCH/libend.a
$ACK_CV -x -m$ARCH $EXE $OUT
# Add object files to a library.

View File

@@ -0,0 +1,6 @@
PROG= add_route
MAN=
LINKS+= ${BINDIR}/add_route ${BINDIR}/del_route
.include <minix.prog.mk>

View File

@@ -28,8 +28,8 @@ static char *prog_name;
static enum { ADD, DEL } action;
static void usage(void);
static int name_to_ip(char *name, ipaddr_t *addr);
static int parse_cidr(char *cidr, ipaddr_t *addr, ipaddr_t *mask);
static int name_to_ip(const char *name, ipaddr_t *addr);
static int parse_cidr(const char *cidr, ipaddr_t *addr, ipaddr_t *mask);
int main(int argc, char *argv[])
{
@@ -297,7 +297,7 @@ static void usage(void)
exit(1);
}
static int name_to_ip(char *name, ipaddr_t *addr)
static int name_to_ip(const char *name, ipaddr_t *addr)
{
/* Translate a name to an IP address. Try first with inet_aton(), then
* with gethostbyname(). (The latter can also recognize an IP address,
@@ -314,7 +314,7 @@ static int name_to_ip(char *name, ipaddr_t *addr)
return 1;
}
static int parse_cidr(char *cidr, ipaddr_t *addr, ipaddr_t *mask)
static int parse_cidr(const char *cidr, ipaddr_t *addr, ipaddr_t *mask)
{
char *slash, *check;
ipaddr_t a;

View File

@@ -0,0 +1,4 @@
SCRIPTS= adduser.sh
MAN=
.include <minix.prog.mk>

View File

View File

@@ -1,63 +1,28 @@
# Makefile for advent
# Where to put the adventure text files, and the binary executable.
# Need the trailing "/"s.
TEXTDIR = /usr/lib/advent/
BINDIR = /usr/bin
PROG= advent
SRCS= advent.c database.c english.c initial.c itverb.c score.c \
travel.c turn.c utility.c verb.c vocab.c
# Flags you may want to add to CFLAGS:
# -DHAS_STDC=0 or 1 We have Standard C. Default=1 iff __STDC__ is nonzero.
# Where to put the adventure text files
# Need the trailing "/" on TEXTDIR
TEXTDIR= /usr/lib/advent/
FILESDIR= ${TEXTDIR}
DATFILES= advent1.dat advent2.dat advent3.dat advent4.dat
FILES= ${DATFILES}
MAN=
CC = exec cc
CFLAGS = -D_POSIX_SOURCE
LDFLAGS = -i
OBJS = advent.o database.o english.o initial.o itverb.o score.o\
travel.o turn.o utility.o verb.o vocab.o
DAT = advent1.dat advent2.dat advent3.dat advent4.dat
INSTDAT = $(TEXTDIR)advent1.dat $(TEXTDIR)advent2.dat \
$(TEXTDIR)advent3.dat $(TEXTDIR)advent4.dat
all: $(DAT) advent
install: $(TEXTDIR) $(INSTDAT) $(BINDIR)/advent
$(TEXTDIR):
install -d -o bin $(TEXTDIR)
$(TEXTDIR)advent1.dat: advent1.dat
install -c -o bin $? $@
$(TEXTDIR)advent2.dat: advent2.dat
install -c -o bin $? $@
$(TEXTDIR)advent3.dat: advent3.dat
install -c -o bin $? $@
$(TEXTDIR)advent4.dat: advent4.dat
install -c -o bin $? $@
$(BINDIR)/advent: advent
install -cs -o bin $? $@
advent: $(OBJS)
$(CC) $(LDFLAGS) -o advent $(OBJS)
database.o: advtext.h
setup: setup.c advent.h
$(CC) $(CFLAGS) $(LDFLAGS) -o setup setup.c
${CC} ${CPPFLAGS} ${LDFLAGS} -o setup setup.c
advtext.h advent1.dat advent2.dat advent3.dat advent4.dat: \
setup advent1.txt advent2.txt advent3.txt advent4.txt
./setup
advent.o: advent.h advdec.h advent.c
$(CC) -c $(CFLAGS) -DTEXTDIR='"$(TEXTDIR)"' advent.c
CPPFLAGS.advent.c= -DTEXTDIR='"${TEXTDIR}"'
database.o: advent.h advdec.h advtext.h
travel.o: advent.h advdec.h advcave.h
initial.o english.o itverb.o score.o turn.o utility.o\
verb.o vocab.o: advent.h advdec.h
CLEANFILES+= ${DATFILES} advtext.h setup
clean:
@rm -f *.o *.BAK *.dat advtext.h core advent setup
.include <minix.prog.mk>

View File

@@ -1,3 +0,0 @@
#!/bin/sh
make clean
make && make install

5
commands/arp/Makefile Normal file
View File

@@ -0,0 +1,5 @@
PROG= arp
BINMODE= 4755
MAN=
.include <minix.prog.mk>

View File

@@ -43,7 +43,7 @@ static void delete(char *hostname);
static void do_set(char *hostname, char *ethername, int temp, int pub,
int optdelete);
static ipaddr_t nametoipaddr(char *hostname);
static void fatal(char *fmt, ...);
static void fatal(const char *fmt, ...);
static void usage(void);
int main(int argc, char *argv[])
@@ -444,7 +444,7 @@ static char *ether_ntoa(struct ether_addr *eap)
}
#endif
static void fatal(char *fmt, ...)
static void fatal(const char *fmt, ...)
{
va_list ap;

View File

@@ -1,33 +1,34 @@
# Makefile for ash.
SRCS= alias.c builtins.c cd.c error.c eval.c exec.c expand.c histedit.c \
input.c \
jobs.c mail.c main.c memalloc.c miscbltin.c mystring.c nodes.c \
options.c parser.c redir.c setmode.c show.c signames.c syntax.c \
trap.c \
output.c var.c
.include <minix.own.mk>
OBJS= alias.o builtins.o cd.o error.o eval.o exec.o expand.o histedit.o \
input.o \
jobs.o mail.o main.o memalloc.o miscbltin.o mystring.o nodes.o \
options.o parser.o redir.o setmode.o show.o signames.o syntax.o \
trap.o \
output.o var.o init.o \
bltin/echo.o bltin/expr.o bltin/operators.o bltin/regexp.o \
arith.o arith_lex.o
YHEADER=1
PROG= sh
LEX=flex
YACC=/usr/bin/yacc
.c.o:
$(CC) $(CFLAGS) -c $< -o $@
SHSRCS= alias.c arith.y arith_lex.l cd.c echo.c error.c eval.c exec.c expand.c \
histedit.c input.c jobs.c mail.c main.c memalloc.c miscbltin.c \
mystring.c options.c output.c parser.c redir.c show.c \
trap.c var.c setmode.c expr.c regexp.c
GENSRCS= builtins.c init.c nodes.c syntax.c operators.c signames.c
GENHDRS= builtins.h nodes.h syntax.h token.h operators.h signames.h
SRCS= ${SHSRCS} ${GENSRCS}
DPSRCS+=${GENHDRS}
BINDIR= /bin
MAN=
DPADD+= ${LIBL} ${LIBEDIT}
LDADD+= -ll -ledit
LFLAGS= -8 # 8-bit lex scanner for arithmetic
YFLAGS= -d
# The .depend file can get references to these temporary files
.OPTIONAL: lex.yy.c y.tab.c
# Enable this line to disable command line editing
#EDIT=-DNO_HISTORY
# Enable this line to use the editline library instead of libedit
EDIT=-DEDITLINE
EDITLIB=-ledit
FLEXLIB=-lfl
# Enable this line if your system does not have a <paths.h>
NO_PATHS_H=-DNO_PATHS_H
@@ -36,88 +37,50 @@ NO_PATHS_H=-DNO_PATHS_H
NO_JOBS=-DJOBS=0
MKB_NO_JOBS=-j
CPPFLAGS= -DSHELL -I. -D_MINIX $(EDIT) $(NO_PATHS_H) $(NO_JOBS)
CFLAGS= $(OPT) $(CPPFLAGS)
LIBS= $(EDITLIB) $(FLEXLIB)
CPPFLAGS+=-DSHELL -I. -I${.CURDIR}
CPPFLAGS+=${EDIT} ${NO_PATHS_H} ${NO_JOBS}
CLEANFILES= $(OBJS) \
arith.c arith_y.h arith_lex.c builtins.c builtins.h init.c \
mkinit mknodes mksignames mksyntax \
nodes.c nodes.h signames.c signames.h syntax.c syntax.h token.h \
bltin/operators.h bltin/operators.c
.PATH: ${.CURDIR}/bltin
all: sh
CLEANFILES+= mkinit mkinit.o mknodes mknodes.o \
mksyntax mksyntax.o mksignames mksignames.o
CLEANFILES+= ${GENSRCS} ${GENHDRS} y.tab.h
sh: $(OBJS)
$(CC) $(CFLAGS) -fnone -o sh $(OBJS) $(LIBS)
install -S 136k sh
build-tools: mkinit mknodes mksyntax mksignames
install: /usr/bin/ash /usr/bin/sh /bin/sh /bin/bigsh
.ORDER: builtins.c builtins.h
builtins.c builtins.h: mkbuiltins builtins.def shell.h
cd ${.CURDIR}; sh mkbuiltins ${MKB_NO_JOBS} ${.OBJDIR} shell.h builtins.def
/usr/bin/ash: sh
install -cs -o bin $< $@
init.c: mkinit alias.c eval.c exec.c input.c jobs.c options.c parser.c \
redir.c trap.c var.c
./mkinit ${.ALLSRC:S/^mkinit$//}
/usr/bin/sh: /usr/bin/ash
install -l $< $@
/bin/sh: /usr/bin/ash
install -lcs $< $@
/bin/bigsh: /usr/bin/ash
install -S 6600k -lcs $< $@
clean:
rm -f $(CLEANFILES) sh core
parser.o: token.def
token.def: mktokens
sh mktokens
arith.c: arith.y
$(YACC) -d $<
mv y.tab.c $@
mv y.tab.h arith_y.h
arith_lex.c: arith_lex.l
builtins.c builtins.h: builtins.def shell.h
sh mkbuiltins $(MKB_NO_JOBS) . shell.h builtins.def
init.c: mkinit $(SRCS)
./mkinit $(SRCS)
mkinit: mkinit.c
$(CC) $(CFLAGS) mkinit.c -o $@
mkinit: mkinit.o
mknodes: mknodes.o
mksyntax: mksyntax.o
mksignames: mksignames.o
.ORDER: nodes.c nodes.h
nodes.c nodes.h: mknodes nodetypes nodes.c.pat
./mknodes nodetypes nodes.c.pat
mknodes: mknodes.c
$(CC) $(CFLAGS) mknodes.c -o $@
signames.c signames.h: mksignames
./mksignames
mksignames: mksignames.c
$(CC) $(CFLAGS) mksignames.c -o $@
./mknodes ${.CURDIR}/nodetypes ${.CURDIR}/nodes.c.pat
.ORDER: syntax.c syntax.h
syntax.c syntax.h: mksyntax
./mksyntax
mksyntax: mksyntax.c parser.h
$(CC) $(CFLAGS) mksyntax.c -o $@
token.h: mktokens
sh ${.CURDIR}/mktokens
bltin/operators.h: bltin/mkexpr bltin/unary_op bltin/binary_op
cd bltin && sh mkexpr unary_op binary_op
.ORDER: signames.c signames.h
signames.c signames.h: mksignames
./mksignames
# Dependencies you say? This will have to do.
$(OBJS): error.h eval.h exec.h expand.h init.h input.h \
jobs.h machdep.h mail.h main.h memalloc.h mystring.h options.h \
output.h parser.h redir.h shell.h trap.h var.h \
builtins.h nodes.h signames.h syntax.h
.ORDER: operators.c operators.h
operators.c operators.h: mkexpr unary_op binary_op
sh bltin/mkexpr bltin/unary_op bltin/binary_op
bltin/expr.o bltin/operators.o: bltin/operators.h
arith.h: arith.c
arith.c: arith.y
#
# $PchId: Makefile,v 1.4 2006/05/22 12:40:46 philip Exp $
.include <minix.prog.mk>

View File

@@ -49,19 +49,18 @@ __FBSDID("$FreeBSD: src/bin/sh/alias.c,v 1.18 2004/04/06 20:06:51 markm Exp $");
#include "mystring.h"
#include "alias.h"
#include "options.h" /* XXX for argptr (should remove?) */
#include "builtins.h"
#define ATABSIZE 39
STATIC struct alias *atab[ATABSIZE];
STATIC void setalias(char *, char *);
STATIC int unalias(char *);
STATIC struct alias **hashalias(char *);
STATIC void setalias(const char *, const char *);
STATIC int unalias(const char *);
STATIC struct alias **hashalias(const char *);
STATIC
void
setalias(char *name, char *val)
setalias(const char *name, const char *val)
{
struct alias *ap, **app;
@@ -114,7 +113,7 @@ setalias(char *name, char *val)
}
STATIC int
unalias(char *name)
unalias(const char *name)
{
struct alias *ap, **app;
@@ -175,7 +174,7 @@ rmaliases(void)
}
struct alias *
lookupalias(char *name, int check)
lookupalias(const char *name, int check)
{
struct alias *ap = *hashalias(name);
@@ -250,7 +249,7 @@ unaliascmd(int argc __unused, char **argv __unused)
}
STATIC struct alias **
hashalias(char *p)
hashalias(const char *p)
{
unsigned int hashval;

View File

@@ -42,7 +42,7 @@ struct alias {
int flag;
};
struct alias *lookupalias(char *, int);
struct alias *lookupalias(const char *, int);
int aliascmd(int, char **);
int unaliascmd(int, char **);
void rmaliases(void);

View File

@@ -42,12 +42,11 @@ __FBSDID("$FreeBSD: src/bin/sh/arith.y,v 1.19 2004/05/24 10:11:31 stefanf Exp $"
*/
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include "shell.h"
#include "arith.h"
#include "arith_lex.h"
#include "expand.h"
#include "var.h"
%}
%union {
@@ -261,7 +260,6 @@ expr:
#include "error.h"
#include "output.h"
#include "memalloc.h"
#include "builtins.h"
#define lstrlen(var) (3 + (2 + CHAR_BIT * sizeof((var))) / 3)
@@ -360,7 +358,3 @@ error(char *s)
exit(1);
}
#endif
/*
* $PchId: arith.y,v 1.6 2006/05/22 12:41:47 philip Exp $
*/

View File

@@ -44,8 +44,7 @@ __FBSDID("$FreeBSD: src/bin/sh/arith_lex.l,v 1.22 2004/04/06 20:06:51 markm Exp
#include <string.h>
#include "shell.h"
#include "arith_lex.h"
#include "arith_y.h"
#include "arith.h"
#include "error.h"
#include "memalloc.h"
#include "var.h"
@@ -132,7 +131,3 @@ arith_lex_reset(void)
{
YY_NEW_FILE;
}
/*
* $PchId: arith_lex.l,v 1.5 2006/04/10 14:35:29 philip Exp $
*/

View File

@@ -67,11 +67,11 @@ __FBSDID("$FreeBSD: src/bin/sh/cd.c,v 1.34 2004/04/06 20:06:51 markm Exp $");
#include "show.h"
#include "cd.h"
STATIC int cdlogical(char *);
STATIC int cdphysical(char *);
STATIC int docd(char *, int, int);
STATIC int cdlogical(const char *);
STATIC int cdphysical(const char *);
STATIC int docd(const char *, int, int);
STATIC char *getcomponent(void);
STATIC int updatepwd(char *);
STATIC int updatepwd(const char *);
STATIC char *curdir = NULL; /* current working directory */
STATIC char *prevdir; /* previous working directory */
@@ -145,7 +145,7 @@ cdcmd(int argc, char **argv)
* directory name if "print" is nonzero.
*/
STATIC int
docd(char *dest, int print, int phys)
docd(const char *dest, int print, int phys)
{
TRACE(("docd(\"%s\", %d, %d) called\n", dest, print, phys));
@@ -161,7 +161,7 @@ docd(char *dest, int print, int phys)
}
STATIC int
cdlogical(char *dest)
cdlogical(const char *dest)
{
char *p;
char *q;
@@ -212,7 +212,7 @@ cdlogical(char *dest)
}
STATIC int
cdphysical(char *dest)
cdphysical(const char *dest)
{
INTOFF;
@@ -255,7 +255,7 @@ getcomponent(void)
* that the current directory has changed.
*/
STATIC int
updatepwd(char *dir)
updatepwd(const char *dir)
{
char *new;
char *p;

View File

@@ -49,13 +49,10 @@ __FBSDID("$FreeBSD: src/bin/sh/error.c,v 1.25 2004/04/06 20:06:51 markm Exp $");
#include "options.h"
#include "output.h"
#include "error.h"
#include "nodes.h" /* show.h needs nodes.h */
#include "show.h"
#include "trap.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>

View File

@@ -62,6 +62,13 @@ void rmescapes(char *);
int casematch(union node *, char *);
int wordexpcmd(int, char **);
/* From arith.y */
int arith(char *);
int arith_assign(char *, arith_t);
int expcmd(int , char **);
void arith_lex_reset(void);
/*
* $PchId: expand.h,v 1.4 2006/03/30 14:50:52 philip Exp $
*/

View File

@@ -83,7 +83,7 @@ ckrealloc(pointer p, int nbytes)
*/
char *
savestr(char *s)
savestr(const char *s)
{
char *p;

View File

@@ -48,7 +48,7 @@ extern int herefd;
pointer ckmalloc(int);
pointer ckrealloc(pointer, int);
char *savestr(char *);
char *savestr(const char *);
pointer stalloc(int);
void stunalloc(pointer);
void setstackmark(struct stackmark *);

View File

@@ -0,0 +1,8 @@
# Makefile for asmconv.
PROG= asmconv
SRCS= asm86.c asmconv.c parse_ack.c parse_gnu.c parse_bas.c \
tokenize.c emit_ack.c emit_gnu.c
MAN=
.include <minix.prog.mk>

5
commands/at/Makefile Normal file
View File

@@ -0,0 +1,5 @@
PROG= at
BINMODE= 4755
MAN=
.include <minix.prog.mk>

View File

@@ -13,9 +13,9 @@
#include <errno.h>
#define STARTDAY 0 /* see ctime(3) */
#define LEAPDAY STARTDAY+59
#define MAXDAYNR STARTDAY+365
#define NODAY -2
#define LEAPDAY (STARTDAY+59)
#define MAXDAYNR (STARTDAY+365)
#define NODAY (-2)
char CRONPID[] = "/usr/run/cron.pid";
_PROTOTYPE(int main, (int argc, char **argv, char **envp));

View File

@@ -0,0 +1,4 @@
PROG= atnormalize
MAN=
.include <minix.prog.mk>

View File

@@ -20,7 +20,7 @@
#include <minix/const.h>
#include <minix/partition.h>
#include <minix/u64.h>
#include <ibm/partition.h>
#include <machine/partition.h>
#include <termios.h>
#include <stdarg.h>

View File

@@ -1,26 +1,10 @@
# Makefile for commands/autil
CC = exec cc
CFLAGS = -I. -D_MINIX -D_POSIX_SOURCE -wo
CCLD = $(CC) -i $(CFLAGS)
PROGS= anm asize
SRCS.anm= anm.c rd.c rd_arhdr.c rd_bytes.c rd_unsig2.c
SRCS.asize= asize.c
CPPFLAGS+= -I${.CURDIR}
MAN.anm=
MAN.asize=
all: anm asize
anm: anm.c rd.c rd_arhdr.c rd_bytes.c rd_unsig2.c
$(CCLD) -o $@ $?
install -S 32kw $@
asize: asize.c
$(CCLD) -o $@ $?
install -S 4kw $@
install: /usr/bin/anm /usr/bin/asize
/usr/bin/anm: anm
install -cs -o bin $? $@
/usr/bin/asize: asize
install -cs -o bin $? $@
clean:
rm -f anm asize core
.include <minix.prog.mk>

View File

@@ -2,7 +2,6 @@
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
/* $Id$ */
/*
** print symbol tables for
** ACK object files

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -1,3 +0,0 @@
#!/bin/sh
make clean
make && make install

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -2,7 +2,6 @@
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".
*/
/* $Id$ */
#ifndef __RANLIB_H_INCLUDED
#define __RANLIB_H_INCLUDED

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -1,4 +1,3 @@
/* $Id$ */
/*
* (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
* See the copyright notice in the ACK home directory, in the file "Copyright".

View File

@@ -0,0 +1,4 @@
PROG= autopart
MAN=
.include <minix.prog.mk>

View File

@@ -31,7 +31,7 @@
#include <minix/u64.h>
#include <minix/com.h>
#include <minix/sysinfo.h>
#include <ibm/partition.h>
#include <machine/partition.h>
#include <termios.h>
#include <stdarg.h>

961
commands/awk/FIXES Normal file
View File

@@ -0,0 +1,961 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
This file lists all bug fixes, changes, etc., made since the AWK book
was sent to the printers in August, 1987.
Feb 8, 2010:
i give up. replaced isblank with isspace in b.c; there are
no consistent header files.
Nov 26, 2009:
fixed a long-standing issue with when FS takes effect. a
change to FS is now noticed immediately for subsequent splits.
changed the name getline() to awkgetline() to avoid yet another
name conflict somewhere.
Feb 11, 2009:
temporarily for now defined HAS_ISBLANK, since that seems to
be the best way through the thicket. isblank arrived in C99,
but seems to be arriving at different systems at different
times.
Oct 8, 2008:
fixed typo in b.c that set tmpvec wrongly. no one had ever
run into the problem, apparently. thanks to alistair crooks.
Oct 23, 2007:
minor fix in lib.c: increase inputFS to 100, change malloc
for fields to n+1.
fixed memory fault caused by out of order test in setsval.
thanks to david o'brien, freebsd, for both fixes.
May 1, 2007:
fiddle in makefile to fix for BSD make; thanks to igor sobrado.
Mar 31, 2007:
fixed some null pointer refs calling adjbuf.
Feb 21, 2007:
fixed a bug in matching the null RE in sub and gsub. thanks to al aho
who actually did the fix (in b.c), and to wolfgang seeberg for finding
it and providing a very compact test case.
fixed quotation in b.c; thanks to Hal Pratt and the Princeton Dante
Project.
removed some no-effect asserts in run.c.
fiddled maketab.c to not complain about bison-generated values.
removed the obsolete -V argument; fixed --version to print the
version and exit.
fixed wording and an outright error in the usage message; thanks to igor
sobrado and jason mcintyre.
fixed a bug in -d that caused core dump if no program followed.
Jan 1, 2007:
dropped mac.code from makefile; there are few non-MacOSX
mac's these days.
Jan 17, 2006:
system() not flagged as unsafe in the unadvertised -safe option.
found it while enhancing tests before shipping the ;login: article.
practice what you preach.
removed the 9-years-obsolete -mr and -mf flags.
added -version and --version options.
core dump on linux with BEGIN {nextfile}, now fixed.
removed some #ifdef's in run.c and lex.c that appear to no
longer be necessary.
Apr 24, 2005:
modified lib.c so that values of $0 et al are preserved in the END
block, apparently as required by posix. thanks to havard eidnes
for the report and code.
Jan 14, 2005:
fixed infinite loop in parsing, originally found by brian tsang.
thanks to arnold robbins for a suggestion that started me
rethinking it.
Dec 31, 2004:
prevent overflow of -f array in main, head off potential error in
call of SYNTAX(), test malloc return in lib.c, all with thanks to
todd miller.
Dec 22, 2004:
cranked up size of NCHARS; coverity thinks it can be overrun with
smaller size, and i think that's right. added some assertions to b.c
to catch places where it might overrun. the RE code is still fragile.
Dec 5, 2004:
fixed a couple of overflow problems with ridiculous field numbers:
e.g., print $(2^32-1). thanks to ruslan ermilov, giorgos keramidas
and david o'brien at freebsd.org for patches. this really should
be re-done from scratch.
Nov 21, 2004:
fixed another 25-year-old RE bug, in split. it's another failure
to (re-)initialize. thanks to steve fisher for spotting this and
providing a good test case.
Nov 22, 2003:
fixed a bug in regular expressions that dates (so help me) from 1977;
it's been there from the beginning. an anchored longest match that
was longer than the number of states triggered a failure to initialize
the machine properly. many thanks to moinak ghosh for not only finding
this one but for providing a fix, in some of the most mysterious
code known to man.
fixed a storage leak in call() that appears to have been there since
1983 or so -- a function without an explicit return that assigns a
string to a parameter leaked a Cell. thanks to moinak ghosh for
spotting this very subtle one.
Jul 31, 2003:
fixed, thanks to andrey chernov and ruslan ermilov, a bug in lex.c
that mis-handled the character 255 in input. (it was being compared
to EOF with a signed comparison.)
Jul 29, 2003:
fixed (i think) the long-standing botch that included the beginning of
line state ^ for RE's in the set of valid characters; this led to a
variety of odd problems, including failure to properly match certain
regular expressions in non-US locales. thanks to ruslan for keeping
at this one.
Jul 28, 2003:
n-th try at getting internationalization right, with thanks to volker
kiefel, arnold robbins and ruslan ermilov for advice, though they
should not be blamed for the outcome. according to posix, "." is the
radix character in programs and command line arguments regardless of
the locale; otherwise, the locale should prevail for input and output
of numbers. so it's intended to work that way.
i have rescinded the attempt to use strcoll in expanding shorthands in
regular expressions (cclenter). its properties are much too
surprising; for example [a-c] matches aAbBc in locale en_US but abBcC
in locale fr_CA. i can see how this might arise by implementation
but i cannot explain it to a human user. (this behavior can be seen
in gawk as well; we're leaning on the same library.)
the issue appears to be that strcoll is meant for sorting, where
merging upper and lower case may make sense (though note that unix
sort does not do this by default either). it is not appropriate
for regular expressions, where the goal is to match specific
patterns of characters. in any case, the notations [:lower:], etc.,
are available in awk, and they are more likely to work correctly in
most locales.
a moratorium is hereby declared on internationalization changes.
i apologize to friends and colleagues in other parts of the world.
i would truly like to get this "right", but i don't know what
that is, and i do not want to keep making changes until it's clear.
Jul 4, 2003:
fixed bug that permitted non-terminated RE, as in "awk /x".
Jun 1, 2003:
subtle change to split: if source is empty, number of elems
is always 0 and the array is not set.
Mar 21, 2003:
added some parens to isblank, in another attempt to make things
internationally portable.
Mar 14, 2003:
the internationalization changes, somewhat modified, are now
reinstated. in theory awk will now do character comparisons
and case conversions in national language, but "." will always
be the decimal point separator on input and output regardless
of national language. isblank(){} has an #ifndef.
this no longer compiles on windows: LC_MESSAGES isn't defined
in vc6++.
fixed subtle behavior in field and record splitting: if FS is
a single character and RS is not empty, \n is NOT a separator.
this tortuous reading is found in the awk book; behavior now
matches gawk and mawk.
Dec 13, 2002:
for the moment, the internationalization changes of nov 29 are
rolled back -- programs like x = 1.2 don't work in some locales,
because the parser is expecting x = 1,2. until i understand this
better, this will have to wait.
Nov 29, 2002:
modified b.c (with tiny changes in main and run) to support
locales, using strcoll and iswhatever tests for posix character
classes. thanks to ruslan ermilov (ru@freebsd.org) for code.
the function isblank doesn't seem to have propagated to any
header file near me, so it's there explicitly. not properly
tested on non-ascii character sets by me.
Jun 28, 2002:
modified run/format() and tran/getsval() to do a slightly better
job on using OFMT for output from print and CONVFMT for other
number->string conversions, as promised by posix and done by
gawk and mawk. there are still places where it doesn't work
right if CONVFMT is changed; by then the STR attribute of the
variable has been irrevocably set. thanks to arnold robbins for
code and examples.
fixed subtle bug in format that could get core dump. thanks to
Jaromir Dolecek <jdolecek@NetBSD.org> for finding and fixing.
minor cleanup in run.c / format() at the same time.
added some tests for null pointers to debugging printf's, which
were never intended for external consumption. thanks to dave
kerns (dkerns@lucent.com) for pointing this out.
GNU compatibility: an empty regexp matches anything (thanks to
dag-erling smorgrav, des@ofug.org). subject to reversion if
this does more harm than good.
pervasive small changes to make things more const-correct, as
reported by gcc's -Wwrite-strings. as it says in the gcc manual,
this may be more nuisance than useful. provoked by a suggestion
and code from arnaud desitter, arnaud@nimbus.geog.ox.ac.uk
minor documentation changes to note that this now compiles out
of the box on Mac OS X.
Feb 10, 2002:
changed types in posix chars structure to quiet solaris cc.
Jan 1, 2002:
fflush() or fflush("") flushes all files and pipes.
length(arrayname) returns number of elements; thanks to
arnold robbins for suggestion.
added a makefile.win to make it easier to build on windows.
based on dan allen's buildwin.bat.
Nov 16, 2001:
added support for posix character class names like [:digit:],
which are not exactly shorter than [0-9] and perhaps no more
portable. thanks to dag-erling smorgrav for code.
Feb 16, 2001:
removed -m option; no longer needed, and it was actually
broken (noted thanks to volker kiefel).
Feb 10, 2001:
fixed an appalling bug in gettok: any sequence of digits, +,-, E, e,
and period was accepted as a valid number if it started with a period.
this would never have happened with the lex version.
other 1-character botches, now fixed, include a bare $ and a
bare " at the end of the input.
Feb 7, 2001:
more (const char *) casts in b.c and tran.c to silence warnings.
Nov 15, 2000:
fixed a bug introduced in august 1997 that caused expressions
like $f[1] to be syntax errors. thanks to arnold robbins for
noticing this and providing a fix.
Oct 30, 2000:
fixed some nextfile bugs: not handling all cases. thanks to
arnold robbins for pointing this out. new regressions added.
close() is now a function. it returns whatever the library
fclose returns, and -1 for closing a file or pipe that wasn't
opened.
Sep 24, 2000:
permit \n explicitly in character classes; won't work right
if comes in as "[\n]" but ok as /[\n]/, because of multiple
processing of \'s. thanks to arnold robbins.
July 5, 2000:
minor fiddles in tran.c to keep compilers happy about uschar.
thanks to norman wilson.
May 25, 2000:
yet another attempt at making 8-bit input work, with another
band-aid in b.c (member()), and some (uschar) casts to head
off potential errors in subscripts (like isdigit). also
changed HAT to NCHARS-2. thanks again to santiago vila.
changed maketab.c to ignore apparently out of range definitions
instead of halting; new freeBSD generates one. thanks to
jon snader <jsnader@ix.netcom.com> for pointing out the problem.
May 2, 2000:
fixed an 8-bit problem in b.c by making several char*'s into
unsigned char*'s. not clear i have them all yet. thanks to
Santiago Vila <sanvila@unex.es> for the bug report.
Apr 21, 2000:
finally found and fixed a memory leak in function call; it's
been there since functions were added ~1983. thanks to
jon bentley for the test case that found it.
added test in envinit to catch environment "variables" with
names beginning with '='; thanks to Berend Hasselman.
Jul 28, 1999:
added test in defn() to catch function foo(foo), which
otherwise recurses until core dump. thanks to arnold
robbins for noticing this.
Jun 20, 1999:
added *bp in gettok in lex.c; appears possible to exit function
without terminating the string. thanks to russ cox.
Jun 2, 1999:
added function stdinit() to run to initialize files[] array,
in case stdin, etc., are not constants; some compilers care.
May 10, 1999:
replaced the ERROR ... FATAL, etc., macros with functions
based on vprintf, to avoid problems caused by overrunning
fixed-size errbuf array. thanks to ralph corderoy for the
impetus, and for pointing out a string termination bug in
qstring as well.
Apr 21, 1999:
fixed bug that caused occasional core dumps with commandline
variable with value ending in \. (thanks to nelson beebe for
the test case.)
Apr 16, 1999:
with code kindly provided by Bruce Lilly, awk now parses
/=/ and similar constructs more sensibly in more places.
Bruce also provided some helpful test cases.
Apr 5, 1999:
changed true/false to True/False in run.c to make it
easier to compile with C++. Added some casts on malloc
and realloc to be honest about casts; ditto. changed
ltype int to long in struct rrow to reduce some 64-bit
complaints; other changes scattered throughout for the
same purpose. thanks to Nelson Beebe for these portability
improvements.
removed some horrible pointer-int casting in b.c and elsewhere
by adding ptoi and itonp to localize the casts, which are
all benign. fixed one incipient bug that showed up on sgi
in 64-bit mode.
reset lineno for new source file; include filename in error
message. also fixed line number error in continuation lines.
(thanks to Nelson Beebe for both of these.)
Mar 24, 1999:
Nelson Beebe notes that irix 5.3 yacc dies with a bogus
error; use a newer version or switch to bison, since sgi
is unlikely to fix it.
Mar 5, 1999:
changed isnumber to is_number to avoid the problem caused by
versions of ctype.h that include the name isnumber.
distribution now includes a script for building on a Mac,
thanks to Dan Allen.
Feb 20, 1999:
fixed memory leaks in run.c (call) and tran.c (setfval).
thanks to Stephen Nutt for finding these and providing the fixes.
Jan 13, 1999:
replaced srand argument by (unsigned int) in run.c;
avoids problem on Mac and potentially on Unix & Windows.
thanks to Dan Allen.
added a few (int) casts to silence useless compiler warnings.
e.g., errorflag= in run.c jump().
added proctab.c to the bundle outout; one less thing
to have to compile out of the box.
added calls to _popen and _pclose to the win95 stub for
pipes (thanks to Steve Adams for this helpful suggestion).
seems to work, though properties are not well understood
by me, and it appears that under some circumstances the
pipe output is truncated. Be careful.
Oct 19, 1998:
fixed a couple of bugs in getrec: could fail to update $0
after a getline var; because inputFS wasn't initialized,
could split $0 on every character, a misleading diversion.
fixed caching bug in makedfa: LRU was actually removing
least often used.
thanks to ross ridge for finding these, and for providing
great bug reports.
May 12, 1998:
fixed potential bug in readrec: might fail to update record
pointer after growing. thanks to dan levy for spotting this
and suggesting the fix.
Mar 12, 1998:
added -V to print version number and die.
Feb 11, 1998:
subtle silent bug in lex.c: if the program ended with a number
longer than 1 digit, part of the input would be pushed back and
parsed again because token buffer wasn't terminated right.
example: awk 'length($0) > 10'. blush. at least i found it
myself.
Aug 31, 1997:
s/adelete/awkdelete/: SGI uses this in malloc.h.
thanks to nelson beebe for pointing this one out.
Aug 21, 1997:
fixed some bugs in sub and gsub when replacement includes \\.
this is a dark, horrible corner, but at least now i believe that
the behavior is the same as gawk and the intended posix standard.
thanks to arnold robbins for advice here.
Aug 9, 1997:
somewhat regretfully, replaced the ancient lex-based lexical
analyzer with one written in C. it's longer, generates less code,
and more portable; the old one depended too much on mysterious
properties of lex that were not preserved in other environments.
in theory these recognize the same language.
now using strtod to test whether a string is a number, instead of
the convoluted original function. should be more portable and
reliable if strtod is implemented right.
removed now-pointless optimization in makefile that tries to avoid
recompilation when awkgram.y is changed but symbols are not.
removed most fixed-size arrays, though a handful remain, some
of which are unchecked. you have been warned.
Aug 4, 1997:
with some trepidation, replaced the ancient code that managed
fields and $0 in fixed-size arrays with arrays that grow on
demand. there is still some tension between trying to make this
run fast and making it clean; not sure it's right yet.
the ill-conceived -mr and -mf arguments are now useful only
for debugging. previous dynamic string code removed.
numerous other minor cleanups along the way.
Jul 30, 1997:
using code provided by dan levy (to whom profuse thanks), replaced
fixed-size arrays and awkward kludges by a fairly uniform mechanism
to grow arrays as needed for printf, sub, gsub, etc.
Jul 23, 1997:
falling off the end of a function returns "" and 0, not 0.
thanks to arnold robbins.
Jun 17, 1997:
replaced several fixed-size arrays by dynamically-created ones
in run.c; added overflow tests to some previously unchecked cases.
getline, toupper, tolower.
getline code is still broken in that recursive calls may wind
up using the same space. [fixed later]
increased RECSIZE to 8192 to push problems further over the horizon.
added \r to \n as input line separator for programs, not data.
damn CRLFs.
modified format() to permit explicit printf("%c", 0) to include
a null byte in output. thanks to ken stailey for the fix.
added a "-safe" argument that disables file output (print >,
print >>), process creation (cmd|getline, print |, system), and
access to the environment (ENVIRON). this is a first approximation
to a "safe" version of awk, but don't rely on it too much. thanks
to joan feigenbaum and matt blaze for the inspiration long ago.
Jul 8, 1996:
fixed long-standing bug in sub, gsub(/a/, "\\\\&"); thanks to
ralph corderoy.
Jun 29, 1996:
fixed awful bug in new field splitting; didn't get all the places
where input was done.
Jun 28, 1996:
changed field-splitting to conform to posix definition: fields are
split using the value of FS at the time of input; it used to be
the value when the field or NF was first referred to, a much less
predictable definition. thanks to arnold robbins for encouragement
to do the right thing.
May 28, 1996:
fixed appalling but apparently unimportant bug in parsing octal
numbers in reg exprs.
explicit hex in reg exprs now limited to 2 chars: \xa, \xaa.
May 27, 1996:
cleaned up some declarations so gcc -Wall is now almost silent.
makefile now includes backup copies of ytab.c and lexyy.c in case
one makes before looking; it also avoids recreating lexyy.c unless
really needed.
s/aprintf/awkprint, s/asprintf/awksprintf/ to avoid some name clashes
with unwisely-written header files.
thanks to jeffrey friedl for several of these.
May 26, 1996:
an attempt to rationalize the (unsigned) char issue. almost all
instances of unsigned char have been removed; the handful of places
in b.c where chars are used as table indices have been hand-crafted.
added some latin-1 tests to the regression, but i'm not confident;
none of my compilers seem to care much. thanks to nelson beebe for
pointing out some others that do care.
May 2, 1996:
removed all register declarations.
enhanced split(), as in gawk, etc: split(s, a, "") splits s into
a[1]...a[length(s)] with each character a single element.
made the same changes for field-splitting if FS is "".
added nextfile, as in gawk: causes immediate advance to next
input file. (thanks to arnold robbins for inspiration and code).
small fixes to regexpr code: can now handle []], [[], and
variants; [] is now a syntax error, rather than matching
everything; [z-a] is now empty, not z. far from complete
or correct, however. (thanks to jeffrey friedl for pointing out
some awful behaviors.)
Apr 29, 1996:
replaced uchar by uschar everywhere; apparently some compilers
usurp this name and this causes conflicts.
fixed call to time in run.c (bltin); arg is time_t *.
replaced horrible pointer/long punning in b.c by a legitimate
union. should be safer on 64-bit machines and cleaner everywhere.
(thanks to nelson beebe for pointing out some of these problems.)
replaced nested comments by #if 0...#endif in run.c, lib.c.
removed getsval, setsval, execute macros from run.c and lib.c.
machines are 100x faster than they were when these macros were
first used.
revised filenames: awk.g.y => awkgram.y, awk.lx.l => awklex.l,
y.tab.[ch] => ytab.[ch], lex.yy.c => lexyy.c, all in the aid of
portability to nameless systems.
"make bundle" now includes yacc and lex output files for recipients
who don't have yacc or lex.
Aug 15, 1995:
initialized Cells in setsymtab more carefully; some fields
were not set. (thanks to purify, all of whose complaints i
think i now understand.)
fixed at least one error in gsub that looked at -1-th element
of an array when substituting for a null match (e.g., $).
delete arrayname is now legal; it clears the elements but leaves
the array, which may not be the right behavior.
modified makefile: my current make can't cope with the test used
to avoid unnecessary yacc invocations.
Jul 17, 1995:
added dynamically growing strings to awk.lx.l and b.c
to permit regular expressions to be much bigger.
the state arrays can still overflow.
Aug 24, 1994:
detect duplicate arguments in function definitions (mdm).
May 11, 1994:
trivial fix to printf to limit string size in sub().
Apr 22, 1994:
fixed yet another subtle self-assignment problem:
$1 = $2; $1 = $1 clobbered $1.
Regression tests now use private echo, to avoid quoting problems.
Feb 2, 1994:
changed error() to print line number as %d, not %g.
Jul 23, 1993:
cosmetic changes: increased sizes of some arrays,
reworded some error messages.
added CONVFMT as in posix (just replaced OFMT in getsval)
FILENAME is now "" until the first thing that causes a file
to be opened.
Nov 28, 1992:
deleted yyunput and yyoutput from proto.h;
different versions of lex give these different declarations.
May 31, 1992:
added -mr N and -mf N options: more record and fields.
these really ought to adjust automatically.
cleaned up some error messages; "out of space" now means
malloc returned NULL in all cases.
changed rehash so that if it runs out, it just returns;
things will continue to run slow, but maybe a bit longer.
Apr 24, 1992:
remove redundant close of stdin when using -f -.
got rid of core dump with -d; awk -d just prints date.
Apr 12, 1992:
added explicit check for /dev/std(in,out,err) in redirection.
unlike gawk, no /dev/fd/n yet.
added (file/pipe) builtin. hard to test satisfactorily.
not posix.
Feb 20, 1992:
recompile after abortive changes; should be unchanged.
Dec 2, 1991:
die-casting time: converted to ansi C, installed that.
Nov 30, 1991:
fixed storage leak in freefa, failing to recover [N]CCL.
thanks to Bill Jones (jones@cs.usask.ca)
Nov 19, 1991:
use RAND_MAX instead of literal in builtin().
Nov 12, 1991:
cranked up some fixed-size arrays in b.c, and added a test for
overflow in penter. thanks to mark larsen.
Sep 24, 1991:
increased buffer in gsub. a very crude fix to a general problem.
and again on Sep 26.
Aug 18, 1991:
enforce variable name syntax for commandline variables: has to
start with letter or _.
Jul 27, 1991:
allow newline after ; in for statements.
Jul 21, 1991:
fixed so that in self-assignment like $1=$1, side effects
like recomputing $0 take place. (this is getting subtle.)
Jun 30, 1991:
better test for detecting too-long output record.
Jun 2, 1991:
better defense against very long printf strings.
made break and continue illegal outside of loops.
May 13, 1991:
removed extra arg on gettemp, tempfree. minor error message rewording.
May 6, 1991:
fixed silly bug in hex parsing in hexstr().
removed an apparently unnecessary test in isnumber().
warn about weird printf conversions.
fixed unchecked array overwrite in relex().
changed for (i in array) to access elements in sorted order.
then unchanged it -- it really does run slower in too many cases.
left the code in place, commented out.
Feb 10, 1991:
check error status on all writes, to avoid banging on full disks.
Jan 28, 1991:
awk -f - reads the program from stdin.
Jan 11, 1991:
failed to set numeric state on $0 in cmd|getline context in run.c.
Nov 2, 1990:
fixed sleazy test for integrality in getsval; use modf.
Oct 29, 1990:
fixed sleazy buggy code in lib.c that looked (incorrectly) for
too long input lines.
Oct 14, 1990:
fixed the bug on p. 198 in which it couldn't deduce that an
argument was an array in some contexts. replaced the error
message in intest() by code that damn well makes it an array.
Oct 8, 1990:
fixed horrible bug: types and values were not preserved in
some kinds of self-assignment. (in assign().)
Aug 24, 1990:
changed NCHARS to 256 to handle 8-bit characters in strings
presented to match(), etc.
Jun 26, 1990:
changed struct rrow (awk.h) to use long instead of int for lval,
since cfoll() stores a pointer in it. now works better when int's
are smaller than pointers!
May 6, 1990:
AVA fixed the grammar so that ! is uniformly of the same precedence as
unary + and -. This renders illegal some constructs like !x=y, which
now has to be parenthesized as !(x=y), and makes others work properly:
!x+y is (!x)+y, and x!y is x !y, not two pattern-action statements.
(These problems were pointed out by Bob Lenk of Posix.)
Added \x to regular expressions (already in strings).
Limited octal to octal digits; \8 and \9 are not octal.
Centralized the code for parsing escapes in regular expressions.
Added a bunch of tests to T.re and T.sub to verify some of this.
Feb 9, 1990:
fixed null pointer dereference bug in main.c: -F[nothing]. sigh.
restored srand behavior: it returns the current seed.
Jan 18, 1990:
srand now returns previous seed value (0 to start).
Jan 5, 1990:
fix potential problem in tran.c -- something was freed,
then used in freesymtab.
Oct 18, 1989:
another try to get the max number of open files set with
relatively machine-independent code.
small fix to input() in case of multiple reads after EOF.
Oct 11, 1989:
FILENAME is now defined in the BEGIN block -- too many old
programs broke.
"-" means stdin in getline as well as on the commandline.
added a bunch of casts to the code to tell the truth about
char * vs. unsigned char *, a right royal pain. added a
setlocale call to the front of main, though probably no one
has it usefully implemented yet.
Aug 24, 1989:
removed redundant relational tests against nullnode if parse
tree already had a relational at that point.
Aug 11, 1989:
fixed bug: commandline variable assignment has to look like
var=something. (consider the man page for =, in file =.1)
changed number of arguments to functions to static arrays
to avoid repeated malloc calls.
Aug 2, 1989:
restored -F (space) separator
Jul 30, 1989:
added -v x=1 y=2 ... for immediate commandline variable assignment;
done before the BEGIN block for sure. they have to precede the
program if the program is on the commandline.
Modified Aug 2 to require a separate -v for each assignment.
Jul 10, 1989:
fixed ref-thru-zero bug in environment code in tran.c
Jun 23, 1989:
add newline to usage message.
Jun 14, 1989:
added some missing ansi printf conversion letters: %i %X %E %G.
no sensible meaning for h or L, so they may not do what one expects.
made %* conversions work.
changed x^y so that if n is a positive integer, it's done
by explicit multiplication, thus achieving maximum accuracy.
(this should be done by pow() but it seems not to be locally.)
done to x ^= y as well.
Jun 4, 1989:
ENVIRON array contains environment: if shell variable V=thing,
ENVIRON["V"] is "thing"
multiple -f arguments permitted. error reporting is naive.
(they were permitted before, but only the last was used.)
fixed a really stupid botch in the debugging macro dprintf
fixed order of evaluation of commandline assignments to match
what the book claims: an argument of the form x=e is evaluated
at the time it would have been opened if it were a filename (p 63).
this invalidates the suggested answer to ex 4-1 (p 195).
removed some code that permitted -F (space) fieldseparator,
since it didn't quite work right anyway. (restored aug 2)
Apr 27, 1989:
Line number now accumulated correctly for comment lines.
Apr 26, 1989:
Debugging output now includes a version date,
if one compiles it into the source each time.
Apr 9, 1989:
Changed grammar to prohibit constants as 3rd arg of sub and gsub;
prevents class of overwriting-a-constant errors. (Last one?)
This invalidates the "banana" example on page 43 of the book.
Added \a ("alert"), \v (vertical tab), \xhhh (hexadecimal),
as in ANSI, for strings. Rescinded the sloppiness that permitted
non-octal digits in \ooo. Warning: not all compilers and libraries
will be able to deal with \x correctly.
Jan 9, 1989:
Fixed bug that caused tempcell list to contain a duplicate.
The fix is kludgy.
Dec 17, 1988:
Catches some more commandline errors in main.
Removed redundant decl of modf in run.c (confuses some compilers).
Warning: there's no single declaration of malloc, etc., in awk.h
that seems to satisfy all compilers.
Dec 7, 1988:
Added a bit of code to error printing to avoid printing nulls.
(Not clear that it actually would.)
Nov 27, 1988:
With fear and trembling, modified the grammar to permit
multiple pattern-action statements on one line without
an explicit separator. By definition, this capitulation
to the ghost of ancient implementations remains undefined
and thus subject to change without notice or apology.
DO NOT COUNT ON IT.
Oct 30, 1988:
Fixed bug in call() that failed to recover storage.
A warning is now generated if there are more arguments
in the call than in the definition (in lieu of fixing
another storage leak).
Oct 20, 1988:
Fixed %c: if expr is numeric, use numeric value;
otherwise print 1st char of string value. still
doesn't work if the value is 0 -- won't print \0.
Added a few more checks for running out of malloc.
Oct 12, 1988:
Fixed bug in call() that freed local arrays twice.
Fixed to handle deletion of non-existent array right;
complains about attempt to delete non-array element.
Sep 30, 1988:
Now guarantees to evaluate all arguments of built-in
functions, as in C; the appearance is that arguments
are evaluated before the function is called. Places
affected are sub (gsub was ok), substr, printf, and
all the built-in arithmetic functions in bltin().
A warning is generated if a bltin() is called with
the wrong number of arguments.
This requires changing makeprof on p167 of the book.
Aug 23, 1988:
setting FILENAME in BEGIN caused core dump, apparently
because it was freeing space not allocated by malloc.
July 24, 1988:
fixed egregious error in toupper/tolower functions.
still subject to rescinding, however.
July 2, 1988:
flush stdout before opening file or pipe
July 2, 1988:
performance bug in b.c/cgoto(): not freeing some sets of states.
partial fix only right now, and the number of states increased
to make it less obvious.
June 1, 1988:
check error status on close
May 28, 1988:
srand returns seed value it's using.
see 1/18/90
May 22, 1988:
Removed limit on depth of function calls.
May 10, 1988:
Fixed lib.c to permit _ in commandline variable names.
Mar 25, 1988:
main.c fixed to recognize -- as terminator of command-
line options. Illegal options flagged.
Error reporting slightly cleaned up.
Dec 2, 1987:
Newer C compilers apply a strict scope rule to extern
declarations within functions. Two extern declarations in
lib.c and tran.c have been moved to obviate this problem.
Oct xx, 1987:
Reluctantly added toupper and tolower functions.
Subject to rescinding without notice.
Sep 17, 1987:
Error-message printer had printf(s) instead of
printf("%s",s); got core dumps when the message
included a %.
Sep 12, 1987:
Very long printf strings caused core dump;
fixed aprintf, asprintf, format to catch them.
Can still get a core dump in printf itself.

View File

@@ -1,30 +1,17 @@
# Makefile for awk.
.include <minix.own.mk>
CC = exec cc
CFLAGS = -D_MINIX -D_POSIX_SOURCE -wo -w
LDFLAGS = -i -f
PROG= awk
SRCS= awkgram.y b.c lex.c lib.c main.c parse.c proctab.c run.c tran.c
YHEADER= yes
QUIET_YACC= yes
OBJS = m.o e.o n.o l.o r.o v.o y.o regexp.o k.o
build-tools: maketab
all: awk
proctab.c: maketab
./maketab > proctab.c
awk: $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS) #-lm
install -S 32kw $@
maketab: awkgram.h maketab.c
install: /usr/bin/awk
CLEANFILES= maketab proctab.c
/usr/bin/awk: awk
install -cs -o bin $? $@
clean:
rm -f awk *.o a.out *.bak core
e.o: awk.h regexp.h
l.o: awk.h
m.o: awk.h
n.o: awk.h
r.o: awk.h regexp.h
regexp.o: regexp.h
v.o: awk.h regexp.h
y.o: awk.h
.include <minix.prog.mk>

View File

@@ -0,0 +1,94 @@
# /****************************************************************
# Copyright (C) Lucent Technologies 1997
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in all
# copies and that both that the copyright notice and this
# permission notice and warranty disclaimer appear in supporting
# documentation, and that the name Lucent Technologies or any of
# its entities not be used in advertising or publicity pertaining
# to distribution of the software without specific, written prior
# permission.
#
# LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
# IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
# THIS SOFTWARE.
# ****************************************************************/
CFLAGS = -g
CFLAGS = -O2
CFLAGS =
CC = gcc -Wall -g -Wwrite-strings
CC = gcc -fprofile-arcs -ftest-coverage # then gcov f1.c; cat f1.c.gcov
CC = gcc -Wall -g
CC = cc
CC = gcc -O4
CC = cc -O
YACC = bison -y
YACC = yacc
YFLAGS = -d
OFILES = b.o main.o parse.o proctab.o tran.o lib.o run.o lex.o
SOURCE = awk.h ytab.c ytab.h proto.h awkgram.y lex.c b.c main.c \
maketab.c parse.c lib.c run.c tran.c proctab.c missing95.c
LISTING = awk.h proto.h awkgram.y lex.c b.c main.c maketab.c parse.c \
lib.c run.c tran.c missing95.c
SHIP = README FIXES $(SOURCE) ytab[ch].bak makefile makefile.win \
vcvars32.bat buildwin.bat awk.1
all: awk
install: awk awk.1
install -m 755 -o bin -g operator awk /usr/bin/awk
install -m 644 -o bin -g operator awk.1 /usr/man/man1
awk: ytab.o $(OFILES)
$(CC) $(CFLAGS) ytab.o $(OFILES) $(ALLOC) -lm -o $@
$(OFILES): awk.h ytab.h proto.h
ytab.o ytab.c ytab.h: awk.h proto.h awkgram.y
$(YACC) $(YFLAGS) awkgram.y 2>/dev/null
mv y.tab.c ytab.c
mv y.tab.h ytab.h
$(CC) $(CFLAGS) -c ytab.c
proctab.c: maketab
./maketab >proctab.c
maketab: ytab.h maketab.c
$(CC) $(CFLAGS) maketab.c -o maketab
bundle:
@cp ytab.h ytabh.bak
@cp ytab.c ytabc.bak
@bundle $(SHIP)
tar:
@cp ytab.h ytabh.bak
@cp ytab.c ytabc.bak
@bundle $(SHIP) >awk.shar
@tar cf awk.tar $(SHIP)
gzip awk.tar
ls -l awk.tar.gz
@zip awk.zip $(SHIP)
ls -l awk.zip
names:
@echo $(LISTING)
clean:
rm -f awk *.o *.obj maketab maketab.exe *.bb *.bbg *.da *.gcov *.gcno *.gcda # proctab.c

View File

@@ -1,13 +1,94 @@
A small AWK clone for the 16-bit Minix
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
We have written this program for the Minix 1.2 to fit into 64K+64K
memory. When compiling this program, you need the Peter S. Housel's
Floating Math Package with corrected the atan() function. Original atan()
function has incorrect argument sequence.
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
This program supports Japanese Shift-JIS KANJI code and passes
all the test program of the "AWK programming language" written by original
AWK authors except some programs relied upon the way of regular expression
evaluation.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
Kouichi Hirabayashi (kh@mogami-wire.co.jp)
This is the version of awk described in "The AWK Programming Language",
by Al Aho, Brian Kernighan, and Peter Weinberger
(Addison-Wesley, 1988, ISBN 0-201-07981-X).
Changes, mostly bug fixes and occasional enhancements, are listed
in FIXES. If you distribute this code further, please please please
distribute FIXES with it. If you find errors, please report them
to bwk@bell-labs.com. Thanks.
The program itself is created by
make
which should produce a sequence of messages roughly like this:
yacc -d awkgram.y
conflicts: 43 shift/reduce, 85 reduce/reduce
mv y.tab.c ytab.c
mv y.tab.h ytab.h
cc -c ytab.c
cc -c b.c
cc -c main.c
cc -c parse.c
cc maketab.c -o maketab
./maketab >proctab.c
cc -c proctab.c
cc -c tran.c
cc -c lib.c
cc -c run.c
cc -c lex.c
cc ytab.o b.o main.o parse.o proctab.o tran.o lib.o run.o lex.o -lm
This produces an executable a.out; you will eventually want to
move this to some place like /usr/bin/awk.
If your system does not have yacc or bison (the GNU
equivalent), you must compile the pieces manually. We have
included yacc output in ytab.c and ytab.h, and backup copies in
case you overwrite them. We have also included a copy of
proctab.c so you do not need to run maketab.
NOTE: This version uses ANSI C, as you should also. We have
compiled this without any changes using gcc -Wall and/or local C
compilers on a variety of systems, but new systems or compilers
may raise some new complaint; reports of difficulties are
welcome.
This also compiles with Visual C++ on all flavors of Windows,
*if* you provide versions of popen and pclose. The file
missing95.c contains versions that can be used to get started
with, though the underlying support has mysterious properties,
the symptom of which can be truncated pipe output. Beware. The
file makefile.win gives hints on how to proceed; if you run
vcvars32.bat, it will set up necessary paths and parameters so
you can subsequently run nmake -f makefile.win. Beware also that
when running on Windows under command.com, various quoting
conventions are different from Unix systems: single quotes won't
work around arguments, and various characters like % are
interpreted within double quotes.
This compiles without change on Macintosh OS X using gcc and
the standard developer tools.
This is also said to compile on Macintosh OS 9 systems, using the
file "buildmac" provided by Dan Allen (danallen@microsoft.com),
to whom many thanks.
The version of malloc that comes with some systems is sometimes
astonishly slow. If awk seems slow, you might try fixing that.
More generally, turning on optimization can significantly improve
awk's speed, perhaps by 1/3 for highest levels.

529
commands/awk/awk.1 Normal file
View File

@@ -0,0 +1,529 @@
.de EX
.nf
.ft CW
..
.de EE
.br
.fi
.ft 1
..
awk
.TH AWK 1
.CT 1 files prog_other
.SH NAME
awk \- pattern-directed scanning and processing language
.SH SYNOPSIS
.B awk
[
.BI \-F
.I fs
]
[
.BI \-v
.I var=value
]
[
.I 'prog'
|
.BI \-f
.I progfile
]
[
.I file ...
]
.SH DESCRIPTION
.I Awk
scans each input
.I file
for lines that match any of a set of patterns specified literally in
.IR prog
or in one or more files
specified as
.B \-f
.IR progfile .
With each pattern
there can be an associated action that will be performed
when a line of a
.I file
matches the pattern.
Each line is matched against the
pattern portion of every pattern-action statement;
the associated action is performed for each matched pattern.
The file name
.B \-
means the standard input.
Any
.IR file
of the form
.I var=value
is treated as an assignment, not a filename,
and is executed at the time it would have been opened if it were a filename.
The option
.B \-v
followed by
.I var=value
is an assignment to be done before
.I prog
is executed;
any number of
.B \-v
options may be present.
The
.B \-F
.IR fs
option defines the input field separator to be the regular expression
.IR fs.
.PP
An input line is normally made up of fields separated by white space,
or by regular expression
.BR FS .
The fields are denoted
.BR $1 ,
.BR $2 ,
\&..., while
.B $0
refers to the entire line.
If
.BR FS
is null, the input line is split into one field per character.
.PP
A pattern-action statement has the form
.IP
.IB pattern " { " action " }
.PP
A missing
.BI { " action " }
means print the line;
a missing pattern always matches.
Pattern-action statements are separated by newlines or semicolons.
.PP
An action is a sequence of statements.
A statement can be one of the following:
.PP
.EX
.ta \w'\f(CWdelete array[expression]'u
.RS
.nf
.ft CW
if(\fI expression \fP)\fI statement \fP\fR[ \fPelse\fI statement \fP\fR]\fP
while(\fI expression \fP)\fI statement\fP
for(\fI expression \fP;\fI expression \fP;\fI expression \fP)\fI statement\fP
for(\fI var \fPin\fI array \fP)\fI statement\fP
do\fI statement \fPwhile(\fI expression \fP)
break
continue
{\fR [\fP\fI statement ... \fP\fR] \fP}
\fIexpression\fP #\fR commonly\fP\fI var = expression\fP
print\fR [ \fP\fIexpression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP
printf\fI format \fP\fR[ \fP,\fI expression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP
return\fR [ \fP\fIexpression \fP\fR]\fP
next #\fR skip remaining patterns on this input line\fP
nextfile #\fR skip rest of this file, open next, start at top\fP
delete\fI array\fP[\fI expression \fP] #\fR delete an array element\fP
delete\fI array\fP #\fR delete all elements of array\fP
exit\fR [ \fP\fIexpression \fP\fR]\fP #\fR exit immediately; status is \fP\fIexpression\fP
.fi
.RE
.EE
.DT
.PP
Statements are terminated by
semicolons, newlines or right braces.
An empty
.I expression-list
stands for
.BR $0 .
String constants are quoted \&\f(CW"\ "\fR,
with the usual C escapes recognized within.
Expressions take on string or numeric values as appropriate,
and are built using the operators
.B + \- * / % ^
(exponentiation), and concatenation (indicated by white space).
The operators
.B
! ++ \-\- += \-= *= /= %= ^= > >= < <= == != ?:
are also available in expressions.
Variables may be scalars, array elements
(denoted
.IB x [ i ] )
or fields.
Variables are initialized to the null string.
Array subscripts may be any string,
not necessarily numeric;
this allows for a form of associative memory.
Multiple subscripts such as
.B [i,j,k]
are permitted; the constituents are concatenated,
separated by the value of
.BR SUBSEP .
.PP
The
.B print
statement prints its arguments on the standard output
(or on a file if
.BI > file
or
.BI >> file
is present or on a pipe if
.BI | cmd
is present), separated by the current output field separator,
and terminated by the output record separator.
.I file
and
.I cmd
may be literal names or parenthesized expressions;
identical string values in different statements denote
the same open file.
The
.B printf
statement formats its expression list according to the format
(see
.IR printf (3)) .
The built-in function
.BI close( expr )
closes the file or pipe
.IR expr .
The built-in function
.BI fflush( expr )
flushes any buffered output for the file or pipe
.IR expr .
.PP
The mathematical functions
.BR exp ,
.BR log ,
.BR sqrt ,
.BR sin ,
.BR cos ,
and
.BR atan2
are built in.
Other built-in functions:
.TF length
.TP
.B length
the length of its argument
taken as a string,
or of
.B $0
if no argument.
.TP
.B rand
random number on (0,1)
.TP
.B srand
sets seed for
.B rand
and returns the previous seed.
.TP
.B int
truncates to an integer value
.TP
.BI substr( s , " m" , " n\fB)
the
.IR n -character
substring of
.I s
that begins at position
.IR m
counted from 1.
.TP
.BI index( s , " t" )
the position in
.I s
where the string
.I t
occurs, or 0 if it does not.
.TP
.BI match( s , " r" )
the position in
.I s
where the regular expression
.I r
occurs, or 0 if it does not.
The variables
.B RSTART
and
.B RLENGTH
are set to the position and length of the matched string.
.TP
.BI split( s , " a" , " fs\fB)
splits the string
.I s
into array elements
.IB a [1] ,
.IB a [2] ,
\&...,
.IB a [ n ] ,
and returns
.IR n .
The separation is done with the regular expression
.I fs
or with the field separator
.B FS
if
.I fs
is not given.
An empty string as field separator splits the string
into one array element per character.
.TP
.BI sub( r , " t" , " s\fB)
substitutes
.I t
for the first occurrence of the regular expression
.I r
in the string
.IR s .
If
.I s
is not given,
.B $0
is used.
.TP
.B gsub
same as
.B sub
except that all occurrences of the regular expression
are replaced;
.B sub
and
.B gsub
return the number of replacements.
.TP
.BI sprintf( fmt , " expr" , " ...\fB )
the string resulting from formatting
.I expr ...
according to the
.IR printf (3)
format
.I fmt
.TP
.BI system( cmd )
executes
.I cmd
and returns its exit status
.TP
.BI tolower( str )
returns a copy of
.I str
with all upper-case characters translated to their
corresponding lower-case equivalents.
.TP
.BI toupper( str )
returns a copy of
.I str
with all lower-case characters translated to their
corresponding upper-case equivalents.
.PD
.PP
The ``function''
.B getline
sets
.B $0
to the next input record from the current input file;
.B getline
.BI < file
sets
.B $0
to the next record from
.IR file .
.B getline
.I x
sets variable
.I x
instead.
Finally,
.IB cmd " | getline
pipes the output of
.I cmd
into
.BR getline ;
each call of
.B getline
returns the next line of output from
.IR cmd .
In all cases,
.B getline
returns 1 for a successful input,
0 for end of file, and \-1 for an error.
.PP
Patterns are arbitrary Boolean combinations
(with
.BR "! || &&" )
of regular expressions and
relational expressions.
Regular expressions are as in
.IR egrep ;
see
.IR grep (1).
Isolated regular expressions
in a pattern apply to the entire line.
Regular expressions may also occur in
relational expressions, using the operators
.BR ~
and
.BR !~ .
.BI / re /
is a constant regular expression;
any string (constant or variable) may be used
as a regular expression, except in the position of an isolated regular expression
in a pattern.
.PP
A pattern may consist of two patterns separated by a comma;
in this case, the action is performed for all lines
from an occurrence of the first pattern
though an occurrence of the second.
.PP
A relational expression is one of the following:
.IP
.I expression matchop regular-expression
.br
.I expression relop expression
.br
.IB expression " in " array-name
.br
.BI ( expr , expr,... ") in " array-name
.PP
where a relop is any of the six relational operators in C,
and a matchop is either
.B ~
(matches)
or
.B !~
(does not match).
A conditional is an arithmetic expression,
a relational expression,
or a Boolean combination
of these.
.PP
The special patterns
.B BEGIN
and
.B END
may be used to capture control before the first input line is read
and after the last.
.B BEGIN
and
.B END
do not combine with other patterns.
.PP
Variable names with special meanings:
.TF FILENAME
.TP
.B CONVFMT
conversion format used when converting numbers
(default
.BR "%.6g" )
.TP
.B FS
regular expression used to separate fields; also settable
by option
.BI \-F fs.
.TP
.BR NF
number of fields in the current record
.TP
.B NR
ordinal number of the current record
.TP
.B FNR
ordinal number of the current record in the current file
.TP
.B FILENAME
the name of the current input file
.TP
.B RS
input record separator (default newline)
.TP
.B OFS
output field separator (default blank)
.TP
.B ORS
output record separator (default newline)
.TP
.B OFMT
output format for numbers (default
.BR "%.6g" )
.TP
.B SUBSEP
separates multiple subscripts (default 034)
.TP
.B ARGC
argument count, assignable
.TP
.B ARGV
argument array, assignable;
non-null members are taken as filenames
.TP
.B ENVIRON
array of environment variables; subscripts are names.
.PD
.PP
Functions may be defined (at the position of a pattern-action statement) thus:
.IP
.B
function foo(a, b, c) { ...; return x }
.PP
Parameters are passed by value if scalar and by reference if array name;
functions may be called recursively.
Parameters are local to the function; all other variables are global.
Thus local variables may be created by providing excess parameters in
the function definition.
.SH EXAMPLES
.TP
.EX
length($0) > 72
.EE
Print lines longer than 72 characters.
.TP
.EX
{ print $2, $1 }
.EE
Print first two fields in opposite order.
.PP
.EX
BEGIN { FS = ",[ \et]*|[ \et]+" }
{ print $2, $1 }
.EE
.ns
.IP
Same, with input fields separated by comma and/or blanks and tabs.
.PP
.EX
.nf
{ s += $1 }
END { print "sum is", s, " average is", s/NR }
.fi
.EE
.ns
.IP
Add up first column, print sum and average.
.TP
.EX
/start/, /stop/
.EE
Print all lines between start/stop pairs.
.PP
.EX
.nf
BEGIN { # Simulate echo(1)
for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i]
printf "\en"
exit }
.fi
.EE
.SH SEE ALSO
.IR lex (1),
.IR sed (1)
.br
A. V. Aho, B. W. Kernighan, P. J. Weinberger,
.I
The AWK Programming Language,
Addison-Wesley, 1988. ISBN 0-201-07981-X
.SH BUGS
There are no explicit conversions between numbers and strings.
To force an expression to be treated as a number add 0 to it;
to force it to be treated as a string concatenate
\&\f(CW""\fP to it.
.br
The scope rules for variables in functions are a botch;
the syntax is worse.

View File

@@ -1,186 +1,233 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
/* lexical/parser tokens and executable statements */
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
#define FIRSTP 256
#define ARG 256
#define ARITH 257
#define ARRAY 258
#define ASSIGN 259
#define CALL 260
#define CAT 261
#define COND 262
#define DELETE 263
#define DO 264
#define ELEMENT 265
#define FIELD 266
#define FOR 267
#define FORIN 268
#define GETLINE 269
#define IF 270
#define IN 271
#define JUMP 272
#define MATHFUN 273
#define NULPROC 274
#define P1STAT 275
#define P2STAT 276
#define PRINT 277
#define PRINT0 278
#define STRFUN 279
#define SUBST 280
#define USRFUN 281
#define WHILE 282
#define LASTP 282
/* lexical token */
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#define ADD 300 /* + */
#define ADDEQ 301 /* += */
#define AND 302 /* && */
#define BEGIN 303 /* BEGIN */
#define BINAND 304 /* & */
#define BINOR 305 /* | */
#define BREAK 306 /* break */
#define CLOSE 307 /* close */
#define CONTIN 308 /* continue */
#define DEC 309 /* -- */
#define DIV 310 /* / */
#define DIVEQ 311 /* /= */
#define ELSE 312 /* else */
#define END 313 /* END */
#define EOL 314 /* ; or '\n' */
#define EQ 315 /* == */
#define EXIT 316 /* exit */
#define FUNC 317 /* function */
#define GE 318 /* >= */
#define GT 319 /* > */
#define IDENT 320 /* identifier */
#define INC 321 /* ++ */
#define LE 322 /* <= */
#define LT 323 /* < */
#define MATCH 324 /* ~ */
#define MOD 325 /* % */
#define MODEQ 326 /* %= */
#define MULT 327 /* * */
#define MULTEQ 328 /* *= */
#define NE 329 /* != */
#define NEXT 330 /* next */
#define NOMATCH 331 /* !~ */
#define NOT 332 /* ! */
#define NUMBER 333 /* integer or floating number */
#define OR 334 /* || */
#define POWEQ 335 /* ^= */
#define POWER 336 /* ^ */
#define PRINTF 337 /* printf */
#define REGEXP 338 /* /REG/ */
#define RETURN 339 /* return */
#define SHIFTL 340 /* << */
#define SHIFTR 341 /* >> */
#define SPRINT 342 /* sprint */
#define SPRINTF 343 /* sprintf */
#define STRING 344 /* ".." */
#define SUB 345 /* - */
#define SUBEQ 346 /* -= */
#define SYSTEM 347 /* system */
#define UMINUS 348 /* - */
#include <assert.h>
/* tokens in parser */
typedef double Awkfloat;
#define VALUE 400 /* value node */
#define INCDEC 401 /* ++, -- */
#define PRE 402 /* pre incre/decre */
#define POST 403 /* post incre/decre */
/* unsigned char is more trouble than it's worth */
/* redirect in print(f) statement */
typedef unsigned char uschar;
#define R_OUT 410 /* > */
#define R_APD 411 /* >> */
#define R_PIPE 412 /* | */
#define R_IN 413 /* < */
#define R_PIN 414 /* | getline */
#define R_POUT 415 /* print | */
#define xfree(a) { if ((a) != NULL) { free((void *) (a)); (a) = NULL; } }
/* function */
#define NN(p) ((p) ? (p) : "(null)") /* guaranteed non-null for dprintf
*/
#define DEBUG
#ifdef DEBUG
/* uses have to be doubly parenthesized */
# define dprintf(x) if (dbg) printf x
#else
# define dprintf(x)
#endif
#define ATAN2 500 /* atan2 */
#define COS 501 /* cos */
#define EXP 502 /* exp */
#define INDEX 503 /* index */
#define INT 504 /* int */
#define LENGTH 505 /* length */
#define LOG 506 /* log */
#define RAND 507 /* rand */
#define RGSUB 508 /* gsub */
#define RMATCH 509 /* match */
#define RSUB 510 /* sub */
#define SIN 511 /* sin */
#define SPLIT 512 /* split */
#define SQRT 513 /* sqrt */
#define SRAND 514 /* srand */
#define SUBSTR 515 /* substr */
extern int compile_time; /* 1 if compiling, 0 if running */
extern int safe; /* 0 => unsafe, 1 => safe */
/* print(f) options */
#define RECSIZE (8 * 1024) /* sets limit on records, fields, etc., etc. */
extern int recsize; /* size of current record, orig RECSIZE */
#define FORMAT 1024 /* PRINTF, SPRINTF */
#define STROUT 2048 /* SPRINTF */
#define PRMASK 0x3ff /* ~(FORMAT|STROUT) */
extern char **FS;
extern char **RS;
extern char **ORS;
extern char **OFS;
extern char **OFMT;
extern Awkfloat *NR;
extern Awkfloat *FNR;
extern Awkfloat *NF;
extern char **FILENAME;
extern char **SUBSEP;
extern Awkfloat *RSTART;
extern Awkfloat *RLENGTH;
/* node - used in parsed tree */
extern char *record; /* points to $0 */
extern int lineno; /* line number in awk program */
extern int errorflag; /* 1 if error has occurred */
extern int donefld; /* 1 if record broken into fields */
extern int donerec; /* 1 if record is valid (no fld has changed */
extern char inputFS[]; /* FS at time of input, for field splitting */
struct node {
int n_type; /* node type */
struct node *n_next; /* pointer to next node */
struct node *n_arg[1]; /* argument (variable length) */
};
extern int dbg;
typedef struct node NODE;
extern char *patbeg; /* beginning of pattern matched */
extern int patlen; /* length of pattern matched. set in b.c */
/* object cell */
/* Cell: all information about a variable or constant */
struct cell {
int c_type; /* cell type */
char *c_sval; /* string value */
double c_fval; /* floating value */
};
typedef struct Cell {
uschar ctype; /* OCELL, OBOOL, OJUMP, etc. */
uschar csub; /* CCON, CTEMP, CFLD, etc. */
char *nval; /* name, for variables only */
char *sval; /* string value */
Awkfloat fval; /* value as number */
int tval; /* type info: STR|NUM|ARR|FCN|FLD|CON|DONTFREE */
struct Cell *cnext; /* ptr to next if chained */
} Cell;
typedef struct cell CELL;
typedef struct Array { /* symbol table array */
int nelem; /* elements in table right now */
int size; /* size of tab */
Cell **tab; /* hash table pointers */
} Array;
/* cell type */
#define NSYMTAB 50 /* initial size of a symbol table */
extern Array *symtab;
#define UDF 0 /* pass parameter */
#define VAR 1 /* variable */
#define NUM 2 /* number */
#define ARR 4 /* array */
#define STR 8 /* string */
#define REC 16 /* record */
#define FLD 32 /* filed */
#define PAT 64 /* pattern (compiled REGEXPR) */
#define BRK 128 /* break */
#define CNT 256 /* continue */
#define NXT 512 /* next */
#define EXT 1024 /* exit */
#define RTN 2048 /* return */
#define TMP 4096 /* temp cell */
#define POS 8192 /* argument position */
#define FUN 16384 /* function */
extern Cell *nrloc; /* NR */
extern Cell *fnrloc; /* FNR */
extern Cell *nfloc; /* NF */
extern Cell *rstartloc; /* RSTART */
extern Cell *rlengthloc; /* RLENGTH */
/* symbol cell - linked to symbol table */
/* Cell.tval values: */
#define NUM 01 /* number value is valid */
#define STR 02 /* string value is valid */
#define DONTFREE 04 /* string space is not freeable */
#define CON 010 /* this is a constant */
#define ARR 020 /* this is an array */
#define FCN 040 /* this is a function name */
#define FLD 0100 /* this is a field $1, $2, ... */
#define REC 0200 /* this is $0 */
struct symbol {
char *s_name;
CELL *s_val;
struct symbol *s_next;
};
typedef struct symbol SYMBOL;
/* function types */
#define FLENGTH 1
#define FSQRT 2
#define FEXP 3
#define FLOG 4
#define FINT 5
#define FSYSTEM 6
#define FRAND 7
#define FSRAND 8
#define FSIN 9
#define FCOS 10
#define FATAN 11
#define FTOUPPER 12
#define FTOLOWER 13
#define FFLUSH 14
/* Node: parse tree is made of nodes, with Cell's at bottom */
typedef struct Node {
int ntype;
struct Node *nnext;
int lineno;
int nobj;
struct Node *narg[1]; /* variable: actual size set by calling malloc */
} Node;
#define NIL ((Node *) 0)
extern Node *winner;
extern Node *nullstat;
extern Node *nullnode;
/* ctypes */
#define OCELL 1
#define OBOOL 2
#define OJUMP 3
/* Cell subtypes: csub */
#define CFREE 7
#define CCOPY 6
#define CCON 5
#define CTEMP 4
#define CNAME 3
#define CVAR 2
#define CFLD 1
#define CUNK 0
/* bool subtypes */
#define BTRUE 11
#define BFALSE 12
/* jump subtypes */
#define JEXIT 21
#define JNEXT 22
#define JBREAK 23
#define JCONT 24
#define JRET 25
#define JNEXTFILE 26
/* node types */
#define NVALUE 1
#define NSTAT 2
#define NEXPR 3
extern int pairstack[], paircnt;
#define notlegal(n) (n <= FIRSTTOKEN || n >= LASTTOKEN || proctab[n-FIRSTTOKEN] == nullproc)
#define isvalue(n) ((n)->ntype == NVALUE)
#define isexpr(n) ((n)->ntype == NEXPR)
#define isjump(n) ((n)->ctype == OJUMP)
#define isexit(n) ((n)->csub == JEXIT)
#define isbreak(n) ((n)->csub == JBREAK)
#define iscont(n) ((n)->csub == JCONT)
#define isnext(n) ((n)->csub == JNEXT || (n)->csub == JNEXTFILE)
#define isret(n) ((n)->csub == JRET)
#define isrec(n) ((n)->tval & REC)
#define isfld(n) ((n)->tval & FLD)
#define isstr(n) ((n)->tval & STR)
#define isnum(n) ((n)->tval & NUM)
#define isarr(n) ((n)->tval & ARR)
#define isfcn(n) ((n)->tval & FCN)
#define istrue(n) ((n)->csub == BTRUE)
#define istemp(n) ((n)->csub == CTEMP)
#define isargument(n) ((n)->nobj == ARG)
/* #define freeable(p) (!((p)->tval & DONTFREE)) */
#define freeable(p) ( ((p)->tval & (STR|DONTFREE)) == STR )
/* structures used by regular expression matching machinery, mostly b.c: */
#define NCHARS (256+3) /* 256 handles 8-bit chars; 128 does 7-bit */
/* watch out in match(), etc. */
#define NSTATES 32
typedef struct rrow {
long ltype; /* long avoids pointer warnings on 64-bit */
union {
int i;
Node *np;
uschar *up;
} lval; /* because Al stores a pointer in it! */
int *lfollow;
} rrow;
typedef struct fa {
uschar gototab[NSTATES][NCHARS];
uschar out[NSTATES];
uschar *restr;
int *posns[NSTATES];
int anchor;
int use;
int initstat;
int curstat;
int accept;
int reset;
struct rrow re[1]; /* variable: actual size set by calling malloc */
} fa;
#include "proto.h"

486
commands/awk/awkgram.y Normal file
View File

@@ -0,0 +1,486 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
%{
#include <stdio.h>
#include <string.h>
#include "awk.h"
void checkdup(Node *list, Cell *item);
int yywrap(void) { return(1); }
Node *beginloc = 0;
Node *endloc = 0;
int infunc = 0; /* = 1 if in arglist or body of func */
int inloop = 0; /* = 1 if in while, for, do */
char *curfname = 0; /* current function name */
Node *arglist = 0; /* list of args for current function */
%}
%union {
Node *p;
Cell *cp;
int i;
char *s;
}
%token <i> FIRSTTOKEN /* must be first */
%token <p> PROGRAM PASTAT PASTAT2 XBEGIN XEND
%token <i> NL ',' '{' '(' '|' ';' '/' ')' '}' '[' ']'
%token <i> ARRAY
%token <i> MATCH NOTMATCH MATCHOP
%token <i> FINAL DOT ALL CCL NCCL CHAR OR STAR QUEST PLUS EMPTYRE
%token <i> AND BOR APPEND EQ GE GT LE LT NE IN
%token <i> ARG BLTIN BREAK CLOSE CONTINUE DELETE DO EXIT FOR FUNC
%token <i> SUB GSUB IF INDEX LSUBSTR MATCHFCN NEXT NEXTFILE
%token <i> ADD MINUS MULT DIVIDE MOD
%token <i> ASSIGN ASGNOP ADDEQ SUBEQ MULTEQ DIVEQ MODEQ POWEQ
%token <i> PRINT PRINTF SPRINTF
%token <p> ELSE INTEST CONDEXPR
%token <i> POSTINCR PREINCR POSTDECR PREDECR
%token <cp> VAR IVAR VARNF CALL NUMBER STRING
%token <s> REGEXPR
%type <p> pas pattern ppattern plist pplist patlist prarg term re
%type <p> pa_pat pa_stat pa_stats
%type <s> reg_expr
%type <p> simple_stmt opt_simple_stmt stmt stmtlist
%type <p> var varname funcname varlist
%type <p> for if else while
%type <i> do st
%type <i> pst opt_pst lbrace rbrace rparen comma nl opt_nl and bor
%type <i> subop print
%right ASGNOP
%right '?'
%right ':'
%left BOR
%left AND
%left GETLINE
%nonassoc APPEND EQ GE GT LE LT NE MATCHOP IN '|'
%left ARG BLTIN BREAK CALL CLOSE CONTINUE DELETE DO EXIT FOR FUNC
%left GSUB IF INDEX LSUBSTR MATCHFCN NEXT NUMBER
%left PRINT PRINTF RETURN SPLIT SPRINTF STRING SUB SUBSTR
%left REGEXPR VAR VARNF IVAR WHILE '('
%left CAT
%left '+' '-'
%left '*' '/' '%'
%left NOT UMINUS
%right POWER
%right DECR INCR
%left INDIRECT
%token LASTTOKEN /* must be last */
%%
program:
pas { if (errorflag==0)
winner = (Node *)stat3(PROGRAM, beginloc, $1, endloc); }
| error { yyclearin; bracecheck(); SYNTAX("bailing out"); }
;
and:
AND | and NL
;
bor:
BOR | bor NL
;
comma:
',' | comma NL
;
do:
DO | do NL
;
else:
ELSE | else NL
;
for:
FOR '(' opt_simple_stmt ';' opt_nl pattern ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt
{ --inloop; $$ = stat4(FOR, $3, notnull($6), $9, $12); }
| FOR '(' opt_simple_stmt ';' ';' opt_nl opt_simple_stmt rparen {inloop++;} stmt
{ --inloop; $$ = stat4(FOR, $3, NIL, $7, $10); }
| FOR '(' varname IN varname rparen {inloop++;} stmt
{ --inloop; $$ = stat3(IN, $3, makearr($5), $8); }
;
funcname:
VAR { setfname($1); }
| CALL { setfname($1); }
;
if:
IF '(' pattern rparen { $$ = notnull($3); }
;
lbrace:
'{' | lbrace NL
;
nl:
NL | nl NL
;
opt_nl:
/* empty */ { $$ = 0; }
| nl
;
opt_pst:
/* empty */ { $$ = 0; }
| pst
;
opt_simple_stmt:
/* empty */ { $$ = 0; }
| simple_stmt
;
pas:
opt_pst { $$ = 0; }
| opt_pst pa_stats opt_pst { $$ = $2; }
;
pa_pat:
pattern { $$ = notnull($1); }
;
pa_stat:
pa_pat { $$ = stat2(PASTAT, $1, stat2(PRINT, rectonode(), NIL)); }
| pa_pat lbrace stmtlist '}' { $$ = stat2(PASTAT, $1, $3); }
| pa_pat ',' pa_pat { $$ = pa2stat($1, $3, stat2(PRINT, rectonode(), NIL)); }
| pa_pat ',' pa_pat lbrace stmtlist '}' { $$ = pa2stat($1, $3, $5); }
| lbrace stmtlist '}' { $$ = stat2(PASTAT, NIL, $2); }
| XBEGIN lbrace stmtlist '}'
{ beginloc = linkum(beginloc, $3); $$ = 0; }
| XEND lbrace stmtlist '}'
{ endloc = linkum(endloc, $3); $$ = 0; }
| FUNC funcname '(' varlist rparen {infunc++;} lbrace stmtlist '}'
{ infunc--; curfname=0; defn((Cell *)$2, $4, $8); $$ = 0; }
;
pa_stats:
pa_stat
| pa_stats opt_pst pa_stat { $$ = linkum($1, $3); }
;
patlist:
pattern
| patlist comma pattern { $$ = linkum($1, $3); }
;
ppattern:
var ASGNOP ppattern { $$ = op2($2, $1, $3); }
| ppattern '?' ppattern ':' ppattern %prec '?'
{ $$ = op3(CONDEXPR, notnull($1), $3, $5); }
| ppattern bor ppattern %prec BOR
{ $$ = op2(BOR, notnull($1), notnull($3)); }
| ppattern and ppattern %prec AND
{ $$ = op2(AND, notnull($1), notnull($3)); }
| ppattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); }
| ppattern MATCHOP ppattern
{ if (constnode($3))
$$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0));
else
$$ = op3($2, (Node *)1, $1, $3); }
| ppattern IN varname { $$ = op2(INTEST, $1, makearr($3)); }
| '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); }
| ppattern term %prec CAT { $$ = op2(CAT, $1, $2); }
| re
| term
;
pattern:
var ASGNOP pattern { $$ = op2($2, $1, $3); }
| pattern '?' pattern ':' pattern %prec '?'
{ $$ = op3(CONDEXPR, notnull($1), $3, $5); }
| pattern bor pattern %prec BOR
{ $$ = op2(BOR, notnull($1), notnull($3)); }
| pattern and pattern %prec AND
{ $$ = op2(AND, notnull($1), notnull($3)); }
| pattern EQ pattern { $$ = op2($2, $1, $3); }
| pattern GE pattern { $$ = op2($2, $1, $3); }
| pattern GT pattern { $$ = op2($2, $1, $3); }
| pattern LE pattern { $$ = op2($2, $1, $3); }
| pattern LT pattern { $$ = op2($2, $1, $3); }
| pattern NE pattern { $$ = op2($2, $1, $3); }
| pattern MATCHOP reg_expr { $$ = op3($2, NIL, $1, (Node*)makedfa($3, 0)); }
| pattern MATCHOP pattern
{ if (constnode($3))
$$ = op3($2, NIL, $1, (Node*)makedfa(strnode($3), 0));
else
$$ = op3($2, (Node *)1, $1, $3); }
| pattern IN varname { $$ = op2(INTEST, $1, makearr($3)); }
| '(' plist ')' IN varname { $$ = op2(INTEST, $2, makearr($5)); }
| pattern '|' GETLINE var {
if (safe) SYNTAX("cmd | getline is unsafe");
else $$ = op3(GETLINE, $4, itonp($2), $1); }
| pattern '|' GETLINE {
if (safe) SYNTAX("cmd | getline is unsafe");
else $$ = op3(GETLINE, (Node*)0, itonp($2), $1); }
| pattern term %prec CAT { $$ = op2(CAT, $1, $2); }
| re
| term
;
plist:
pattern comma pattern { $$ = linkum($1, $3); }
| plist comma pattern { $$ = linkum($1, $3); }
;
pplist:
ppattern
| pplist comma ppattern { $$ = linkum($1, $3); }
;
prarg:
/* empty */ { $$ = rectonode(); }
| pplist
| '(' plist ')' { $$ = $2; }
;
print:
PRINT | PRINTF
;
pst:
NL | ';' | pst NL | pst ';'
;
rbrace:
'}' | rbrace NL
;
re:
reg_expr
{ $$ = op3(MATCH, NIL, rectonode(), (Node*)makedfa($1, 0)); }
| NOT re { $$ = op1(NOT, notnull($2)); }
;
reg_expr:
'/' {startreg();} REGEXPR '/' { $$ = $3; }
;
rparen:
')' | rparen NL
;
simple_stmt:
print prarg '|' term {
if (safe) SYNTAX("print | is unsafe");
else $$ = stat3($1, $2, itonp($3), $4); }
| print prarg APPEND term {
if (safe) SYNTAX("print >> is unsafe");
else $$ = stat3($1, $2, itonp($3), $4); }
| print prarg GT term {
if (safe) SYNTAX("print > is unsafe");
else $$ = stat3($1, $2, itonp($3), $4); }
| print prarg { $$ = stat3($1, $2, NIL, NIL); }
| DELETE varname '[' patlist ']' { $$ = stat2(DELETE, makearr($2), $4); }
| DELETE varname { $$ = stat2(DELETE, makearr($2), 0); }
| pattern { $$ = exptostat($1); }
| error { yyclearin; SYNTAX("illegal statement"); }
;
st:
nl
| ';' opt_nl
;
stmt:
BREAK st { if (!inloop) SYNTAX("break illegal outside of loops");
$$ = stat1(BREAK, NIL); }
| CONTINUE st { if (!inloop) SYNTAX("continue illegal outside of loops");
$$ = stat1(CONTINUE, NIL); }
| do {inloop++;} stmt {--inloop;} WHILE '(' pattern ')' st
{ $$ = stat2(DO, $3, notnull($7)); }
| EXIT pattern st { $$ = stat1(EXIT, $2); }
| EXIT st { $$ = stat1(EXIT, NIL); }
| for
| if stmt else stmt { $$ = stat3(IF, $1, $2, $4); }
| if stmt { $$ = stat3(IF, $1, $2, NIL); }
| lbrace stmtlist rbrace { $$ = $2; }
| NEXT st { if (infunc)
SYNTAX("next is illegal inside a function");
$$ = stat1(NEXT, NIL); }
| NEXTFILE st { if (infunc)
SYNTAX("nextfile is illegal inside a function");
$$ = stat1(NEXTFILE, NIL); }
| RETURN pattern st { $$ = stat1(RETURN, $2); }
| RETURN st { $$ = stat1(RETURN, NIL); }
| simple_stmt st
| while {inloop++;} stmt { --inloop; $$ = stat2(WHILE, $1, $3); }
| ';' opt_nl { $$ = 0; }
;
stmtlist:
stmt
| stmtlist stmt { $$ = linkum($1, $2); }
;
subop:
SUB | GSUB
;
term:
term '/' ASGNOP term { $$ = op2(DIVEQ, $1, $4); }
| term '+' term { $$ = op2(ADD, $1, $3); }
| term '-' term { $$ = op2(MINUS, $1, $3); }
| term '*' term { $$ = op2(MULT, $1, $3); }
| term '/' term { $$ = op2(DIVIDE, $1, $3); }
| term '%' term { $$ = op2(MOD, $1, $3); }
| term POWER term { $$ = op2(POWER, $1, $3); }
| '-' term %prec UMINUS { $$ = op1(UMINUS, $2); }
| '+' term %prec UMINUS { $$ = $2; }
| NOT term %prec UMINUS { $$ = op1(NOT, notnull($2)); }
| BLTIN '(' ')' { $$ = op2(BLTIN, itonp($1), rectonode()); }
| BLTIN '(' patlist ')' { $$ = op2(BLTIN, itonp($1), $3); }
| BLTIN { $$ = op2(BLTIN, itonp($1), rectonode()); }
| CALL '(' ')' { $$ = op2(CALL, celltonode($1,CVAR), NIL); }
| CALL '(' patlist ')' { $$ = op2(CALL, celltonode($1,CVAR), $3); }
| CLOSE term { $$ = op1(CLOSE, $2); }
| DECR var { $$ = op1(PREDECR, $2); }
| INCR var { $$ = op1(PREINCR, $2); }
| var DECR { $$ = op1(POSTDECR, $1); }
| var INCR { $$ = op1(POSTINCR, $1); }
| GETLINE var LT term { $$ = op3(GETLINE, $2, itonp($3), $4); }
| GETLINE LT term { $$ = op3(GETLINE, NIL, itonp($2), $3); }
| GETLINE var { $$ = op3(GETLINE, $2, NIL, NIL); }
| GETLINE { $$ = op3(GETLINE, NIL, NIL, NIL); }
| INDEX '(' pattern comma pattern ')'
{ $$ = op2(INDEX, $3, $5); }
| INDEX '(' pattern comma reg_expr ')'
{ SYNTAX("index() doesn't permit regular expressions");
$$ = op2(INDEX, $3, (Node*)$5); }
| '(' pattern ')' { $$ = $2; }
| MATCHFCN '(' pattern comma reg_expr ')'
{ $$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa($5, 1)); }
| MATCHFCN '(' pattern comma pattern ')'
{ if (constnode($5))
$$ = op3(MATCHFCN, NIL, $3, (Node*)makedfa(strnode($5), 1));
else
$$ = op3(MATCHFCN, (Node *)1, $3, $5); }
| NUMBER { $$ = celltonode($1, CCON); }
| SPLIT '(' pattern comma varname comma pattern ')' /* string */
{ $$ = op4(SPLIT, $3, makearr($5), $7, (Node*)STRING); }
| SPLIT '(' pattern comma varname comma reg_expr ')' /* const /regexp/ */
{ $$ = op4(SPLIT, $3, makearr($5), (Node*)makedfa($7, 1), (Node *)REGEXPR); }
| SPLIT '(' pattern comma varname ')'
{ $$ = op4(SPLIT, $3, makearr($5), NIL, (Node*)STRING); } /* default */
| SPRINTF '(' patlist ')' { $$ = op1($1, $3); }
| STRING { $$ = celltonode($1, CCON); }
| subop '(' reg_expr comma pattern ')'
{ $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, rectonode()); }
| subop '(' pattern comma pattern ')'
{ if (constnode($3))
$$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, rectonode());
else
$$ = op4($1, (Node *)1, $3, $5, rectonode()); }
| subop '(' reg_expr comma pattern comma var ')'
{ $$ = op4($1, NIL, (Node*)makedfa($3, 1), $5, $7); }
| subop '(' pattern comma pattern comma var ')'
{ if (constnode($3))
$$ = op4($1, NIL, (Node*)makedfa(strnode($3), 1), $5, $7);
else
$$ = op4($1, (Node *)1, $3, $5, $7); }
| SUBSTR '(' pattern comma pattern comma pattern ')'
{ $$ = op3(SUBSTR, $3, $5, $7); }
| SUBSTR '(' pattern comma pattern ')'
{ $$ = op3(SUBSTR, $3, $5, NIL); }
| var
;
var:
varname
| varname '[' patlist ']' { $$ = op2(ARRAY, makearr($1), $3); }
| IVAR { $$ = op1(INDIRECT, celltonode($1, CVAR)); }
| INDIRECT term { $$ = op1(INDIRECT, $2); }
;
varlist:
/* nothing */ { arglist = $$ = 0; }
| VAR { arglist = $$ = celltonode($1,CVAR); }
| varlist comma VAR {
checkdup($1, $3);
arglist = $$ = linkum($1,celltonode($3,CVAR)); }
;
varname:
VAR { $$ = celltonode($1, CVAR); }
| ARG { $$ = op1(ARG, itonp($1)); }
| VARNF { $$ = op1(VARNF, (Node *) $1); }
;
while:
WHILE '(' pattern rparen { $$ = notnull($3); }
;
%%
void setfname(Cell *p)
{
if (isarr(p))
SYNTAX("%s is an array, not a function", p->nval);
else if (isfcn(p))
SYNTAX("you can't define function %s more than once", p->nval);
curfname = p->nval;
}
int constnode(Node *p)
{
return isvalue(p) && ((Cell *) (p->narg[0]))->csub == CCON;
}
char *strnode(Node *p)
{
return ((Cell *)(p->narg[0]))->sval;
}
Node *notnull(Node *n)
{
switch (n->nobj) {
case LE: case LT: case EQ: case NE: case GT: case GE:
case BOR: case AND: case NOT:
return n;
default:
return op2(NE, n, nullnode);
}
}
void checkdup(Node *vl, Cell *cp) /* check if name already in list */
{
char *s = cp->nval;
for ( ; vl; vl = vl->nnext) {
if (strcmp(s, ((Cell *)(vl->narg[0]))->nval) == 0) {
SYNTAX("duplicate argument %s", s);
break;
}
}
}

954
commands/awk/b.c Normal file
View File

@@ -0,0 +1,954 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
/* lasciate ogne speranza, voi ch'intrate. */
#define DEBUG
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "awk.h"
#include "awkgram.h"
#define HAT (NCHARS+2) /* matches ^ in regular expr */
/* NCHARS is 2**n */
#define MAXLIN 22
#define type(v) (v)->nobj /* badly overloaded here */
#define info(v) (v)->ntype /* badly overloaded here */
#define left(v) (v)->narg[0]
#define right(v) (v)->narg[1]
#define parent(v) (v)->nnext
#define LEAF case CCL: case NCCL: case CHAR: case DOT: case FINAL: case ALL:
#define ELEAF case EMPTYRE: /* empty string in regexp */
#define UNARY case STAR: case PLUS: case QUEST:
/* encoding in tree Nodes:
leaf (CCL, NCCL, CHAR, DOT, FINAL, ALL, EMPTYRE):
left is index, right contains value or pointer to value
unary (STAR, PLUS, QUEST): left is child, right is null
binary (CAT, OR): left and right are children
parent contains pointer to parent
*/
int *setvec;
int *tmpset;
int maxsetvec = 0;
int rtok; /* next token in current re */
int rlxval;
static uschar *rlxstr;
static uschar *prestr; /* current position in current re */
static uschar *lastre; /* origin of last re */
static int setcnt;
static int poscnt;
char *patbeg;
int patlen;
#define NFA 20 /* cache this many dynamic fa's */
fa *fatab[NFA];
int nfatab = 0; /* entries in fatab */
fa *makedfa(const char *s, int anchor) /* returns dfa for reg expr s */
{
int i, use, nuse;
fa *pfa;
static int now = 1;
if (setvec == 0) { /* first time through any RE */
maxsetvec = MAXLIN;
setvec = (int *) malloc(maxsetvec * sizeof(int));
tmpset = (int *) malloc(maxsetvec * sizeof(int));
if (setvec == 0 || tmpset == 0)
overflo("out of space initializing makedfa");
}
if (compile_time) /* a constant for sure */
return mkdfa(s, anchor);
for (i = 0; i < nfatab; i++) /* is it there already? */
if (fatab[i]->anchor == anchor
&& strcmp((const char *) fatab[i]->restr, s) == 0) {
fatab[i]->use = now++;
return fatab[i];
}
pfa = mkdfa(s, anchor);
if (nfatab < NFA) { /* room for another */
fatab[nfatab] = pfa;
fatab[nfatab]->use = now++;
nfatab++;
return pfa;
}
use = fatab[0]->use; /* replace least-recently used */
nuse = 0;
for (i = 1; i < nfatab; i++)
if (fatab[i]->use < use) {
use = fatab[i]->use;
nuse = i;
}
freefa(fatab[nuse]);
fatab[nuse] = pfa;
pfa->use = now++;
return pfa;
}
fa *mkdfa(const char *s, int anchor) /* does the real work of making a dfa */
/* anchor = 1 for anchored matches, else 0 */
{
Node *p, *p1;
fa *f;
p = reparse(s);
p1 = op2(CAT, op2(STAR, op2(ALL, NIL, NIL), NIL), p);
/* put ALL STAR in front of reg. exp. */
p1 = op2(CAT, p1, op2(FINAL, NIL, NIL));
/* put FINAL after reg. exp. */
poscnt = 0;
penter(p1); /* enter parent pointers and leaf indices */
if ((f = (fa *) calloc(1, sizeof(fa) + poscnt*sizeof(rrow))) == NULL)
overflo("out of space for fa");
f->accept = poscnt-1; /* penter has computed number of positions in re */
cfoll(f, p1); /* set up follow sets */
freetr(p1);
if ((f->posns[0] = (int *) calloc(1, *(f->re[0].lfollow)*sizeof(int))) == NULL)
overflo("out of space in makedfa");
if ((f->posns[1] = (int *) calloc(1, sizeof(int))) == NULL)
overflo("out of space in makedfa");
*f->posns[1] = 0;
f->initstat = makeinit(f, anchor);
f->anchor = anchor;
f->restr = (uschar *) tostring(s);
return f;
}
int makeinit(fa *f, int anchor)
{
int i, k;
f->curstat = 2;
f->out[2] = 0;
f->reset = 0;
k = *(f->re[0].lfollow);
xfree(f->posns[2]);
if ((f->posns[2] = (int *) calloc(1, (k+1)*sizeof(int))) == NULL)
overflo("out of space in makeinit");
for (i=0; i <= k; i++) {
(f->posns[2])[i] = (f->re[0].lfollow)[i];
}
if ((f->posns[2])[1] == f->accept)
f->out[2] = 1;
for (i=0; i < NCHARS; i++)
f->gototab[2][i] = 0;
f->curstat = cgoto(f, 2, HAT);
if (anchor) {
*f->posns[2] = k-1; /* leave out position 0 */
for (i=0; i < k; i++) {
(f->posns[0])[i] = (f->posns[2])[i];
}
f->out[0] = f->out[2];
if (f->curstat != 2)
--(*f->posns[f->curstat]);
}
return f->curstat;
}
void penter(Node *p) /* set up parent pointers and leaf indices */
{
switch (type(p)) {
ELEAF
LEAF
info(p) = poscnt;
poscnt++;
break;
UNARY
penter(left(p));
parent(left(p)) = p;
break;
case CAT:
case OR:
penter(left(p));
penter(right(p));
parent(left(p)) = p;
parent(right(p)) = p;
break;
default: /* can't happen */
FATAL("can't happen: unknown type %d in penter", type(p));
break;
}
}
void freetr(Node *p) /* free parse tree */
{
switch (type(p)) {
ELEAF
LEAF
xfree(p);
break;
UNARY
freetr(left(p));
xfree(p);
break;
case CAT:
case OR:
freetr(left(p));
freetr(right(p));
xfree(p);
break;
default: /* can't happen */
FATAL("can't happen: unknown type %d in freetr", type(p));
break;
}
}
/* in the parsing of regular expressions, metacharacters like . have */
/* to be seen literally; \056 is not a metacharacter. */
int hexstr(char **pp) /* find and eval hex string at pp, return new p */
{ /* only pick up one 8-bit byte (2 chars) */
uschar *p;
int n = 0;
int i;
for (i = 0, p = (uschar *) *pp; i < 2 && isxdigit(*p); i++, p++) {
if (isdigit(*p))
n = 16 * n + *p - '0';
else if (*p >= 'a' && *p <= 'f')
n = 16 * n + *p - 'a' + 10;
else if (*p >= 'A' && *p <= 'F')
n = 16 * n + *p - 'A' + 10;
}
*pp = (char *) p;
return n;
}
#define isoctdigit(c) ((c) >= '0' && (c) <= '7') /* multiple use of arg */
int quoted(char **pp) /* pick up next thing after a \\ */
/* and increment *pp */
{
char *p = *pp;
int c;
if ((c = *p++) == 't')
c = '\t';
else if (c == 'n')
c = '\n';
else if (c == 'f')
c = '\f';
else if (c == 'r')
c = '\r';
else if (c == 'b')
c = '\b';
else if (c == '\\')
c = '\\';
else if (c == 'x') { /* hexadecimal goo follows */
c = hexstr(&p); /* this adds a null if number is invalid */
} else if (isoctdigit(c)) { /* \d \dd \ddd */
int n = c - '0';
if (isoctdigit(*p)) {
n = 8 * n + *p++ - '0';
if (isoctdigit(*p))
n = 8 * n + *p++ - '0';
}
c = n;
} /* else */
/* c = c; */
*pp = p;
return c;
}
char *cclenter(const char *argp) /* add a character class */
{
int i, c, c2;
uschar *p = (uschar *) argp;
uschar *op, *bp;
static uschar *buf = 0;
static int bufsz = 100;
op = p;
if (buf == 0 && (buf = (uschar *) malloc(bufsz)) == NULL)
FATAL("out of space for character class [%.10s...] 1", p);
bp = buf;
for (i = 0; (c = *p++) != 0; ) {
if (c == '\\') {
c = quoted((char **) &p);
} else if (c == '-' && i > 0 && bp[-1] != 0) {
if (*p != 0) {
c = bp[-1];
c2 = *p++;
if (c2 == '\\')
c2 = quoted((char **) &p);
if (c > c2) { /* empty; ignore */
bp--;
i--;
continue;
}
while (c < c2) {
if (!adjbuf((char **) &buf, &bufsz, bp-buf+2, 100, (char **) &bp, "cclenter1"))
FATAL("out of space for character class [%.10s...] 2", p);
*bp++ = ++c;
i++;
}
continue;
}
}
if (!adjbuf((char **) &buf, &bufsz, bp-buf+2, 100, (char **) &bp, "cclenter2"))
FATAL("out of space for character class [%.10s...] 3", p);
*bp++ = c;
i++;
}
*bp = 0;
dprintf( ("cclenter: in = |%s|, out = |%s|\n", op, buf) );
xfree(op);
return (char *) tostring((char *) buf);
}
void overflo(const char *s)
{
FATAL("regular expression too big: %.30s...", s);
}
void cfoll(fa *f, Node *v) /* enter follow set of each leaf of vertex v into lfollow[leaf] */
{
int i;
int *p;
switch (type(v)) {
ELEAF
LEAF
f->re[info(v)].ltype = type(v);
f->re[info(v)].lval.np = right(v);
while (f->accept >= maxsetvec) { /* guessing here! */
maxsetvec *= 4;
setvec = (int *) realloc(setvec, maxsetvec * sizeof(int));
tmpset = (int *) realloc(tmpset, maxsetvec * sizeof(int));
if (setvec == 0 || tmpset == 0)
overflo("out of space in cfoll()");
}
for (i = 0; i <= f->accept; i++)
setvec[i] = 0;
setcnt = 0;
follow(v); /* computes setvec and setcnt */
if ((p = (int *) calloc(1, (setcnt+1)*sizeof(int))) == NULL)
overflo("out of space building follow set");
f->re[info(v)].lfollow = p;
*p = setcnt;
for (i = f->accept; i >= 0; i--)
if (setvec[i] == 1)
*++p = i;
break;
UNARY
cfoll(f,left(v));
break;
case CAT:
case OR:
cfoll(f,left(v));
cfoll(f,right(v));
break;
default: /* can't happen */
FATAL("can't happen: unknown type %d in cfoll", type(v));
}
}
int first(const Node *p) /* collects initially active leaves of p into setvec */
/* returns 0 if p matches empty string */
{
int b, lp;
switch (type(p)) {
ELEAF
LEAF
lp = info(p); /* look for high-water mark of subscripts */
while (setcnt >= maxsetvec || lp >= maxsetvec) { /* guessing here! */
maxsetvec *= 4;
setvec = (int *) realloc(setvec, maxsetvec * sizeof(int));
tmpset = (int *) realloc(tmpset, maxsetvec * sizeof(int));
if (setvec == 0 || tmpset == 0)
overflo("out of space in first()");
}
if (type(p) == EMPTYRE) {
setvec[lp] = 0;
return(0);
}
if (setvec[lp] != 1) {
setvec[lp] = 1;
setcnt++;
}
if (type(p) == CCL && (*(char *) right(p)) == '\0')
return(0); /* empty CCL */
else return(1);
case PLUS:
if (first(left(p)) == 0) return(0);
return(1);
case STAR:
case QUEST:
first(left(p));
return(0);
case CAT:
if (first(left(p)) == 0 && first(right(p)) == 0) return(0);
return(1);
case OR:
b = first(right(p));
if (first(left(p)) == 0 || b == 0) return(0);
return(1);
}
FATAL("can't happen: unknown type %d in first", type(p)); /* can't happen */
return(-1);
}
void follow(Node *v) /* collects leaves that can follow v into setvec */
{
Node *p;
if (type(v) == FINAL)
return;
p = parent(v);
switch (type(p)) {
case STAR:
case PLUS:
first(v);
follow(p);
return;
case OR:
case QUEST:
follow(p);
return;
case CAT:
if (v == left(p)) { /* v is left child of p */
if (first(right(p)) == 0) {
follow(p);
return;
}
} else /* v is right child */
follow(p);
return;
}
}
int member(int c, const char *sarg) /* is c in s? */
{
uschar *s = (uschar *) sarg;
while (*s)
if (c == *s++)
return(1);
return(0);
}
int match(fa *f, const char *p0) /* shortest match ? */
{
int s, ns;
uschar *p = (uschar *) p0;
s = f->reset ? makeinit(f,0) : f->initstat;
if (f->out[s])
return(1);
do {
/* assert(*p < NCHARS); */
if ((ns = f->gototab[s][*p]) != 0)
s = ns;
else
s = cgoto(f, s, *p);
if (f->out[s])
return(1);
} while (*p++ != 0);
return(0);
}
int pmatch(fa *f, const char *p0) /* longest match, for sub */
{
int s, ns;
uschar *p = (uschar *) p0;
uschar *q;
int i, k;
/* s = f->reset ? makeinit(f,1) : f->initstat; */
if (f->reset) {
f->initstat = s = makeinit(f,1);
} else {
s = f->initstat;
}
patbeg = (char *) p;
patlen = -1;
do {
q = p;
do {
if (f->out[s]) /* final state */
patlen = q-p;
/* assert(*q < NCHARS); */
if ((ns = f->gototab[s][*q]) != 0)
s = ns;
else
s = cgoto(f, s, *q);
if (s == 1) { /* no transition */
if (patlen >= 0) {
patbeg = (char *) p;
return(1);
}
else
goto nextin; /* no match */
}
} while (*q++ != 0);
if (f->out[s])
patlen = q-p-1; /* don't count $ */
if (patlen >= 0) {
patbeg = (char *) p;
return(1);
}
nextin:
s = 2;
if (f->reset) {
for (i = 2; i <= f->curstat; i++)
xfree(f->posns[i]);
k = *f->posns[0];
if ((f->posns[2] = (int *) calloc(1, (k+1)*sizeof(int))) == NULL)
overflo("out of space in pmatch");
for (i = 0; i <= k; i++)
(f->posns[2])[i] = (f->posns[0])[i];
f->initstat = f->curstat = 2;
f->out[2] = f->out[0];
for (i = 0; i < NCHARS; i++)
f->gototab[2][i] = 0;
}
} while (*p++ != 0);
return (0);
}
int nematch(fa *f, const char *p0) /* non-empty match, for sub */
{
int s, ns;
uschar *p = (uschar *) p0;
uschar *q;
int i, k;
/* s = f->reset ? makeinit(f,1) : f->initstat; */
if (f->reset) {
f->initstat = s = makeinit(f,1);
} else {
s = f->initstat;
}
patlen = -1;
while (*p) {
q = p;
do {
if (f->out[s]) /* final state */
patlen = q-p;
/* assert(*q < NCHARS); */
if ((ns = f->gototab[s][*q]) != 0)
s = ns;
else
s = cgoto(f, s, *q);
if (s == 1) { /* no transition */
if (patlen > 0) {
patbeg = (char *) p;
return(1);
} else
goto nnextin; /* no nonempty match */
}
} while (*q++ != 0);
if (f->out[s])
patlen = q-p-1; /* don't count $ */
if (patlen > 0 ) {
patbeg = (char *) p;
return(1);
}
nnextin:
s = 2;
if (f->reset) {
for (i = 2; i <= f->curstat; i++)
xfree(f->posns[i]);
k = *f->posns[0];
if ((f->posns[2] = (int *) calloc(1, (k+1)*sizeof(int))) == NULL)
overflo("out of state space");
for (i = 0; i <= k; i++)
(f->posns[2])[i] = (f->posns[0])[i];
f->initstat = f->curstat = 2;
f->out[2] = f->out[0];
for (i = 0; i < NCHARS; i++)
f->gototab[2][i] = 0;
}
p++;
}
return (0);
}
Node *reparse(const char *p) /* parses regular expression pointed to by p */
{ /* uses relex() to scan regular expression */
Node *np;
dprintf( ("reparse <%s>\n", p) );
lastre = prestr = (uschar *) p; /* prestr points to string to be parsed */
rtok = relex();
/* GNU compatibility: an empty regexp matches anything */
if (rtok == '\0') {
/* FATAL("empty regular expression"); previous */
return(op2(EMPTYRE, NIL, NIL));
}
np = regexp();
if (rtok != '\0')
FATAL("syntax error in regular expression %s at %s", lastre, prestr);
return(np);
}
Node *regexp(void) /* top-level parse of reg expr */
{
return (alt(concat(primary())));
}
Node *primary(void)
{
Node *np;
switch (rtok) {
case CHAR:
np = op2(CHAR, NIL, itonp(rlxval));
rtok = relex();
return (unary(np));
case ALL:
rtok = relex();
return (unary(op2(ALL, NIL, NIL)));
case EMPTYRE:
rtok = relex();
return (unary(op2(ALL, NIL, NIL)));
case DOT:
rtok = relex();
return (unary(op2(DOT, NIL, NIL)));
case CCL:
np = op2(CCL, NIL, (Node*) cclenter((char *) rlxstr));
rtok = relex();
return (unary(np));
case NCCL:
np = op2(NCCL, NIL, (Node *) cclenter((char *) rlxstr));
rtok = relex();
return (unary(np));
case '^':
rtok = relex();
return (unary(op2(CHAR, NIL, itonp(HAT))));
case '$':
rtok = relex();
return (unary(op2(CHAR, NIL, NIL)));
case '(':
rtok = relex();
if (rtok == ')') { /* special pleading for () */
rtok = relex();
return unary(op2(CCL, NIL, (Node *) tostring("")));
}
np = regexp();
if (rtok == ')') {
rtok = relex();
return (unary(np));
}
else
FATAL("syntax error in regular expression %s at %s", lastre, prestr);
default:
FATAL("illegal primary in regular expression %s at %s", lastre, prestr);
}
return 0; /*NOTREACHED*/
}
Node *concat(Node *np)
{
switch (rtok) {
case CHAR: case DOT: case ALL: case EMPTYRE: case CCL: case NCCL: case '$': case '(':
return (concat(op2(CAT, np, primary())));
}
return (np);
}
Node *alt(Node *np)
{
if (rtok == OR) {
rtok = relex();
return (alt(op2(OR, np, concat(primary()))));
}
return (np);
}
Node *unary(Node *np)
{
switch (rtok) {
case STAR:
rtok = relex();
return (unary(op2(STAR, np, NIL)));
case PLUS:
rtok = relex();
return (unary(op2(PLUS, np, NIL)));
case QUEST:
rtok = relex();
return (unary(op2(QUEST, np, NIL)));
default:
return (np);
}
}
/*
* Character class definitions conformant to the POSIX locale as
* defined in IEEE P1003.1 draft 7 of June 2001, assuming the source
* and operating character sets are both ASCII (ISO646) or supersets
* thereof.
*
* Note that to avoid overflowing the temporary buffer used in
* relex(), the expanded character class (prior to range expansion)
* must be less than twice the size of their full name.
*/
/* Because isblank doesn't show up in any of the header files on any
* system i use, it's defined here. if some other locale has a richer
* definition of "blank", define HAS_ISBLANK and provide your own
* version.
* the parentheses here are an attempt to find a path through the maze
* of macro definition and/or function and/or version provided. thanks
* to nelson beebe for the suggestion; let's see if it works everywhere.
*/
/* #define HAS_ISBLANK */
#ifndef HAS_ISBLANK
int (xisblank)(int c)
{
return c==' ' || c=='\t';
}
#endif
struct charclass {
const char *cc_name;
int cc_namelen;
int (*cc_func)(int);
} charclasses[] = {
{ "alnum", 5, isalnum },
{ "alpha", 5, isalpha },
{ "blank", 5, isspace }, /* was isblank */
{ "cntrl", 5, iscntrl },
{ "digit", 5, isdigit },
{ "graph", 5, isgraph },
{ "lower", 5, islower },
{ "print", 5, isprint },
{ "punct", 5, ispunct },
{ "space", 5, isspace },
{ "upper", 5, isupper },
{ "xdigit", 6, isxdigit },
{ NULL, 0, NULL },
};
int relex(void) /* lexical analyzer for reparse */
{
int c, n;
int cflag;
static uschar *buf = 0;
static int bufsz = 100;
uschar *bp;
struct charclass *cc;
int i;
switch (c = *prestr++) {
case '|': return OR;
case '*': return STAR;
case '+': return PLUS;
case '?': return QUEST;
case '.': return DOT;
case '\0': prestr--; return '\0';
case '^':
case '$':
case '(':
case ')':
return c;
case '\\':
rlxval = quoted((char **) &prestr);
return CHAR;
default:
rlxval = c;
return CHAR;
case '[':
if (buf == 0 && (buf = (uschar *) malloc(bufsz)) == NULL)
FATAL("out of space in reg expr %.10s..", lastre);
bp = buf;
if (*prestr == '^') {
cflag = 1;
prestr++;
}
else
cflag = 0;
n = 2 * strlen((const char *) prestr)+1;
if (!adjbuf((char **) &buf, &bufsz, n, n, (char **) &bp, "relex1"))
FATAL("out of space for reg expr %.10s...", lastre);
for (; ; ) {
if ((c = *prestr++) == '\\') {
*bp++ = '\\';
if ((c = *prestr++) == '\0')
FATAL("nonterminated character class %.20s...", lastre);
*bp++ = c;
/* } else if (c == '\n') { */
/* FATAL("newline in character class %.20s...", lastre); */
} else if (c == '[' && *prestr == ':') {
/* POSIX char class names, Dag-Erling Smorgrav, des@ofug.org */
for (cc = charclasses; cc->cc_name; cc++)
if (strncmp((const char *) prestr + 1, (const char *) cc->cc_name, cc->cc_namelen) == 0)
break;
if (cc->cc_name != NULL && prestr[1 + cc->cc_namelen] == ':' &&
prestr[2 + cc->cc_namelen] == ']') {
prestr += cc->cc_namelen + 3;
for (i = 0; i < NCHARS; i++) {
if (!adjbuf((char **) &buf, &bufsz, bp-buf+1, 100, (char **) &bp, "relex2"))
FATAL("out of space for reg expr %.10s...", lastre);
if (cc->cc_func(i)) {
*bp++ = i;
n++;
}
}
} else
*bp++ = c;
} else if (c == '\0') {
FATAL("nonterminated character class %.20s", lastre);
} else if (bp == buf) { /* 1st char is special */
*bp++ = c;
} else if (c == ']') {
*bp++ = 0;
rlxstr = (uschar *) tostring((char *) buf);
if (cflag == 0)
return CCL;
else
return NCCL;
} else
*bp++ = c;
}
}
}
int cgoto(fa *f, int s, int c)
{
int i, j, k;
int *p, *q;
assert(c == HAT || c < NCHARS);
while (f->accept >= maxsetvec) { /* guessing here! */
maxsetvec *= 4;
setvec = (int *) realloc(setvec, maxsetvec * sizeof(int));
tmpset = (int *) realloc(tmpset, maxsetvec * sizeof(int));
if (setvec == 0 || tmpset == 0)
overflo("out of space in cgoto()");
}
for (i = 0; i <= f->accept; i++)
setvec[i] = 0;
setcnt = 0;
/* compute positions of gototab[s,c] into setvec */
p = f->posns[s];
for (i = 1; i <= *p; i++) {
if ((k = f->re[p[i]].ltype) != FINAL) {
if ((k == CHAR && c == ptoi(f->re[p[i]].lval.np))
|| (k == DOT && c != 0 && c != HAT)
|| (k == ALL && c != 0)
|| (k == EMPTYRE && c != 0)
|| (k == CCL && member(c, (char *) f->re[p[i]].lval.up))
|| (k == NCCL && !member(c, (char *) f->re[p[i]].lval.up) && c != 0 && c != HAT)) {
q = f->re[p[i]].lfollow;
for (j = 1; j <= *q; j++) {
if (q[j] >= maxsetvec) {
maxsetvec *= 4;
setvec = (int *) realloc(setvec, maxsetvec * sizeof(int));
tmpset = (int *) realloc(tmpset, maxsetvec * sizeof(int));
if (setvec == 0 || tmpset == 0)
overflo("cgoto overflow");
}
if (setvec[q[j]] == 0) {
setcnt++;
setvec[q[j]] = 1;
}
}
}
}
}
/* determine if setvec is a previous state */
tmpset[0] = setcnt;
j = 1;
for (i = f->accept; i >= 0; i--)
if (setvec[i]) {
tmpset[j++] = i;
}
/* tmpset == previous state? */
for (i = 1; i <= f->curstat; i++) {
p = f->posns[i];
if ((k = tmpset[0]) != p[0])
goto different;
for (j = 1; j <= k; j++)
if (tmpset[j] != p[j])
goto different;
/* setvec is state i */
f->gototab[s][c] = i;
return i;
different:;
}
/* add tmpset to current set of states */
if (f->curstat >= NSTATES-1) {
f->curstat = 2;
f->reset = 1;
for (i = 2; i < NSTATES; i++)
xfree(f->posns[i]);
} else
++(f->curstat);
for (i = 0; i < NCHARS; i++)
f->gototab[f->curstat][i] = 0;
xfree(f->posns[f->curstat]);
if ((p = (int *) calloc(1, (setcnt+1)*sizeof(int))) == NULL)
overflo("out of space in cgoto");
f->posns[f->curstat] = p;
f->gototab[s][c] = f->curstat;
for (i = 0; i <= setcnt; i++)
p[i] = tmpset[i];
if (setvec[f->accept])
f->out[f->curstat] = 1;
else
f->out[f->curstat] = 0;
return f->curstat;
}
void freefa(fa *f) /* free a finite automaton */
{
int i;
if (f == NULL)
return;
for (i = 0; i <= f->curstat; i++)
xfree(f->posns[i]);
for (i = 0; i <= f->accept; i++) {
xfree(f->re[i].lfollow);
if (f->re[i].ltype == CCL || f->re[i].ltype == NCCL)
xfree((f->re[i].lval.np));
}
xfree(f->restr);
xfree(f);
}

View File

@@ -1,3 +0,0 @@
#!/bin/sh
make clean
make && make install

View File

@@ -1,952 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
#include <ctype.h>
#include "awk.h"
#include "regexp.h"
extern char **FS, **OFS, **ORS, **OFMT;
extern double *RSTART, *RLENGTH;
extern char record[];
extern CELL *field[];
extern int r_start, r_length;
double getfval(), atof();
char *strsave(), *getsval(), *strcat(), *strstr();
CELL *mkcell(), *mktmp();
CELL *Field(), *Split(), *Forin();
CELL *Arith(), *Assign(), *Stat(), *Mathfun(), *Strfun(), *Cond();
CELL *Print(), *Cat(), *Array(), *Element();
CELL *If(), *While(), *For(), *Do(), *Jump();
CELL *P1stat(), *P2stat(), *Print0();
CELL *Arg(), *Call(), *Ret();
CELL *Subst(), *In(), *Getline(), *Delete(), *Close();
CELL *Nulproc(), *Usrfun();
CELL *_Arg();
FILE *getfp(); /* r.c */
CELL truecell = { NUM, NULL, 1.0 };
CELL falsecell = { NUM, NULL, 0.0 };
static CELL breakcell = { BRK, NULL, 0.0 };
static CELL contcell = { CNT, NULL, 0.0 };
static CELL nextcell = { NXT, NULL, 0.0 };
static CELL retcell = { RTN, NULL, 0.0 };
static CELL *retval; /* function return value */
int pateval; /* used in P1STAT & P2STAT */
static char *r_str; /* STR in 'str ~ STR */
static regexp *r_pat; /* compiled pattern for STR */
CELL *(*proctab[])() = {
Arg, Arith, Array, Assign, Call, Cat, Cond, Delete, Do, Element,
Field, For, Forin, Getline, If, In, Jump, Mathfun, Nulproc, P1stat,
P2stat, Print, Print0, Strfun, Subst, Usrfun, While
};
CELL *
execute(p) NODE *p;
{
int type, i;
CELL *r, *(*proc)();
type = p->n_type;
if (type == VALUE) {
if ((r = (CELL *) p->n_arg[0])->c_type & PAT && pateval) {
i = match(r->c_sval, (char *)record) ? 1 : 0;
r = mktmp(NUM, NULL, (double) i);
}
return r;
}
for ( ; p != NULL; p = p->n_next) {
#if 0
if (p->n_type == VALUE) continue; /* neglect */
#endif
/*
switch ((int) p->n_type) {
case ARRAY:
r = Array(p);
break;
case ARITH:
r = Arith(p);
break;
case ASSIGN:
r = Assign(p);
break;
case PRINT:
r = Print(p);
break;
case PRINT0:
r = Print0(p);
break;
case CAT:
r = Cat(p);
break;
case MATHFUN:
r = Mathfun(p);
break;
case STRFUN:
r = Strfun(p);
break;
case COND:
r = Cond(p);
break;
case IF:
r = If(p);
break;
case P1STAT:
r = P1stat(p);
break;
case P2STAT:
r = P2stat(p);
break;
case WHILE:
r = While(p);
break;
case DO:
r = Do(p);
break;
case FOR:
r = For(p);
break;
case FORIN:
r = Forin(p);
break;
case FIELD:
r = Field(p);
break;
case JUMP:
r = Jump(p);
break;
case ARG:
r = Arg(p);
break;
case CALL:
r = Call(p);
break;
case SUBST:
r = Subst(p);
break;
case ELEMENT:
r = Element(p);
break;
case IN:
r = In(p);
break;
case GETLINE:
r = Getline(p);
break;
case DELETE:
r = Delete(p);
break;
case NULPROC:
r = &truecell;
break;
default:
printf("PROGRAM ERROR ? ILLEGAL NODE TYPE(%d)\n", type);
exit(1);
break;
}
*/
i = (int) p->n_type;
if (i < FIRSTP || i > LASTP)
error("ILLEGAL PROC (%d)", i);
proc = proctab[i - FIRSTP];
r = (*proc)(p);
if (r->c_type & (BRK|CNT|NXT|RTN))
return r;
if (p->n_next != NULL)
c_free(r);
#ifdef DOS
kbhit(); /* needs in MS-DOS */
#endif
}
return r;
}
static CELL *
Arith(p) NODE *p;
{
int op;
CELL *r, *u, *v, *execute();
double x, y, fmod(), pow();
op = (int) p->n_arg[0];
if (op == UMINUS) {
u = execute(p->n_arg[1]);
x = - getfval(u);
}
else if (op == INCDEC) {
u = execute(p->n_arg[1]);
x = getfval(u);
setfval(u, x + (int) p->n_arg[2]);
if ((int) p->n_arg[3] == PRE)
return u;
/* return dummy */
}
else {
u = execute(p->n_arg[1]);
v = execute(p->n_arg[2]);
x = getfval(u);
y = getfval(v);
if (op == DIV || op == MOD) {
if (y == 0.0)
fprintf(stderr, "divid by 0\n");
}
switch (op) {
case SUB: x -= y;break;
case ADD: x += y; break;
case MULT: x *= y; break;
case DIV:
if (y == 0.0)
error("division by zero in \"/\"", (char *)0);
x /= y; break;
case MOD:
if (y == 0.0)
error("division by zero in \"%%\"", (char *)0);
x = fmod(x, y); break;
case POWER: x = pow(x, y); break;
default: printf("UNSUPPORTED ARITH OPERATOR !\n"); break;
}
c_free(v);
}
c_free(u);
r = mktmp(NUM, NULL, x);
return r;
}
static CELL *
Assign(p) NODE *p;
{
CELL *u, *v, *execute();
int op;
double x, y, fmod(), pow();
op = (int) p->n_arg[0];
u = execute(p->n_arg[1]);
#if 0
if (u->c_type == UDF) /* fix up local var */
u->c_type |= VAR|STR;
#endif
if (!(u->c_type & (VAR|FLD|REC)) && (u->c_type != UDF))
fprintf(stderr, "ASSIGN TO NON VARIABLE (%d)\n", u->c_type);
v = execute(p->n_arg[2]);
if (u == v)
goto rtn; /* same node */
if (op == ASSIGN) {
if (v->c_type & NUM/* || isnum(v->c_sval)*/)
setfval(u, getfval(v));
else
setsval(u, getsval(v));
}
else {
x = getfval(u);
y = getfval(v);
switch (op) {
case ADDEQ: x += y; break;
case SUBEQ: x -= y; break;
case MULTEQ: x *= y; break;
case DIVEQ:
if (y == 0.0)
error("division by zero in \"/=\"", (char *)0);
x /= y; break;
case MODEQ:
if (y == 0.0)
error("division by zero in \"%=\"", (char *)0);
x = fmod(x, y); break;
case POWEQ: x = pow(x, y); break;
default:
synerr("illegal assign op (%d)", op);
break;
}
setfval(u, x);
}
rtn:
c_free(v);
return u;
}
static CELL *
Cat(p) NODE *p;
{
CELL *u;
char *s, *t, str[BUFSIZ];
u = execute(p->n_arg[0]);
s = getsval(u);
for (t = str; *s; )
*t++ = *s++;
c_free(u);
u = execute(p->n_arg[1]);
s = getsval(u);
while (*s)
*t++ = *s++;
c_free(u);
*t = '\0';
return mktmp(STR, str, 0.0);
}
static CELL *
Print(p) NODE *p;
{
register int i, redir, typ;
CELL *u;
char *s, str[BUFSIZ];
char *file;
FILE *fp;
redir = (int) p->n_arg[0];
if (typ = redir & PRMASK) { /* redirect */
u = execute(p->n_arg[1]);
file = getsval(u);
if (typ == R_PIPE)
typ = R_POUT;
fp = getfp(file, typ);
c_free(u);
}
else
fp = stdout;
if (redir & FORMAT) /* format */
format(str, p);
else {
*str = '\0';
for (i = 2; p->n_arg[i] != NULL; i++) {
if (i > 2)
strcat(str, *OFS);
u = execute(p->n_arg[i]);
s = getsval(u);
strcat(str, s);
c_free(u);
}
strcat(str, *ORS);
}
if (redir & STROUT) /* sprintf */
return mktmp(STR, str, 0.0);
fputs(str, fp);
fflush(fp);
return &truecell;
}
static CELL *
Mathfun(p) NODE *p;
{
CELL *u, *v;
double x, y;
double atan2(), cos(), exp(), log(), sin(), sqrt(), modf();
if ((int) p->n_arg[1] == 0) {
u = NULL;
x = 0.0;
}
else {
u = execute(p->n_arg[2]);
x = getfval(u);
}
switch ((int) p->n_arg[0]) {
case ATAN2:
if ((int) p->n_arg[1] == 2) {
v = execute(p->n_arg[3]);
y = getfval(v);
x = atan2(x, y);
c_free(v);
}
else
x = 0.0;
break;
case COS: x = cos(x); break;
case EXP: x = exp(x); break;
case INT: y = modf(x, &x); break;
case LOG: x = log(x); break;
case SIN: x = sin(x); break;
case SQRT: x = sqrt(x); break;
case RAND: x = (double) rand() / 32768.0; break;
case SRAND: if (x == 0.0)
x = (double) time(0);
x = (double) srand((int) x);
break;
default:
fprintf(stderr, "unknown math function (%d)\n", p->n_arg[2]);
break;
}
if (u != NULL)
c_free(u);
return mktmp(NUM, NULL, x);
}
static CELL *
Strfun(p) NODE *p;
{
CELL *u, *v, *r;
char *s, *t, str[BUFSIZ];
int i, m, n;
double x;
regexp *pat, *getpat();
n = (int) p->n_arg[1];
if (n > 0 && (int) p->n_arg[0] != SPLIT) {
u = execute(p->n_arg[2]);
s = getsval(u);
}
else {
s = "";
u = NULL;
}
switch ((int) p->n_arg[0]) {
case INDEX:
if (n > 1) {
v = execute(p->n_arg[3]);
t = getsval(v);
i = Index(s, t);
c_free(v);
}
else
i = 0;
r = mktmp(NUM, NULL, (double) i);
break;
case LENGTH:
i = (n > 0) ? jstrlen(s) : jstrlen(record);
r = mktmp(NUM, NULL, (double) i);
break;
case SPLIT:
r = Split(p);
break;
case SUBSTR:
if (n > 1) {
v = execute(p->n_arg[3]);
m = (int) getfval(v) - 1;
c_free(v);
}
else
m = 0;
if (n > 2) {
v = execute(p->n_arg[4]);
n = (int) getfval(v);
c_free(v);
}
else
n = jstrlen(s) - m;
for (t = str; *s && m-- > 0; s++)
if (isKanji(*s))
s++;
while (*s && n-- > 0) {
if (isKanji(*s))
*t++ = *s++;
*t++ = *s++;
}
*t = '\0';
r = mktmp(STR, str, 0.0);
break;
case RMATCH:
if (n > 1) {
v = execute(p->n_arg[3]);
pat = getpat(v);
match(pat, s);
c_free(v);
if (r_start) { /* change only if match */
*RSTART = (double) r_start;
*RLENGTH = (double) r_length;
}
r = mktmp(NUM, NULL, (double) r_start);
}
else
error("missing regexpr in match(str, regexpr)");
break;
case CLOSE:
r = Close(s);
break;
case SYSTEM:
r = mktmp(NUM, NULL, system(s) == -1 ? 0.0 : 1.0);
break;
default:
fprintf(stderr, "unknown string function");
break;
}
c_free(u);
return r;
}
static regexp *
getpat(r) CELL *r;
{
regexp *pat, *mkpat();
if (r->c_type & PAT)
pat = (regexp *) r->c_sval;
else {
if (r_str && strcmp(r_str, r->c_sval) == 0)
pat = r_pat;
else {
sfree(r_str); sfree(r_pat);
r_str = strsave(getsval(r));
pat = r_pat = mkpat(r_str);
}
}
return pat;
}
static CELL *
Subst(p) NODE *p;
{
CELL *u, *v, *w;
char *s, *t, *r, str[BUFSIZ], *strcpy();
int i, n;
n = (int) p->n_arg[1];
if (n > 1) {
u = execute(p->n_arg[3]); /* substitute string */
s = getsval(u);
v = execute(p->n_arg[2]); /* expr */
if (n > 2) {
w = execute(p->n_arg[4]);
t = getsval(w);
r = str;
}
else {
t = r = record;
w = NULL;
}
i = (int) p->n_arg[0] == RGSUB ? 0 : 1;
if (v->c_type & (PAT|STR))
i = Sub(r, v->c_sval, (v->c_type & STR), s, t, i);
else
error("[g]sub(PAT, .. ) must be /../ or string (%d)",
w->c_type);
if (n > 2) {
if (w->c_type & REC) {
strcpy(record, str);
mkfld(record, *FS, field);
}
else
setsval(w, str);
}
else
mkfld(record, *FS, field);
c_free(u);
c_free(v);
c_free(w);
}
else
i = 0;
return mktmp(NUM, NULL, (double) i);
}
static CELL *
Cond(p) NODE *p;
{
CELL *u, *v;
double x, y;
int op, i, j;
char *s;
int save = pateval;
op = (int) p->n_arg[0];
u = execute(p->n_arg[1]);
x = getfval(u);
/*
printf("Cond(%d)(%s)\n", u->c_type, u->c_sval);
*/
if (op == AND || op == OR || op == NOT) {
if (u->c_type & NUM)
i = (x != 0.0);
else {
s = getsval(u);
i = (s != (char *)NULL) && (*s != '\0');
}
}
if (op == AND && !i) {
c_free(u);
return &falsecell;
}
if (op == OR && i) {
c_free(u);
return &truecell;
}
if (op == NOT)
i = i == 0 ? 1 : 0;
else {
if (op == MATCH || op == NOMATCH)
pateval = 0;
v = execute(p->n_arg[2]);
y = getfval(v);
if (op == AND || op == OR || op == BINAND || op == BINOR) {
if (v->c_type & NUM)
j = (y != 0.0);
else {
s = getsval(v);
j = (s != (char *)NULL) && (*s != '\0');
}
switch (op) {
case AND: i = i && j; break;
case OR: i = i || j; break;
case BINAND: i = i & j; break;
case BINOR: i = i | j; break;
}
}
else if (op == MATCH || op == NOMATCH) {
char *s;
regexp *pat, *getpat();
s = getsval(u);
pat = getpat(v);
i = match(pat, s) == 0 ? 0 : 1;
if (op == NOMATCH)
i = i == 0 ? 1 : 0;
}
else { /* relative operator */
/*
printf("Cond(%d)(%d)(%s)(%s)\n", u->c_type, v->c_type, u->c_sval, v->c_sval);
*/
if ((u->c_type & NUM) && (v->c_type & NUM))
i = x < y ? -1 : (x > y ? 1 : 0);
else
i = strcmp(getsval(u), getsval(v));
/*
printf("Cond(%d)(%d)(%g)(%g)(%d)\n", u->c_type, v->c_type, x, y, i);
*/
switch (op) {
case LT: i = i < 0 ? 1 : 0; break;
case LE: i = i <= 0 ? 1 : 0; break;
case EQ: i = i == 0 ? 1 : 0; break;
case NE: i = i != 0 ? 1 : 0; break;
case GT: i = i > 0 ? 1 : 0; break;
case GE: i = i >= 0 ? 1 : 0; break;
default:
fprintf(stderr, "unknown relative operator (%d)\n", op);
break;
}
}
c_free(v);
}
c_free(u);
pateval = save;
return mktmp(NUM, NULL, (double) i);
}
static CELL *
If(p) NODE *p;
{
CELL *u;
int i;
char *s;
u = execute(p->n_arg[0]);
if (u->c_type & NUM)
i = (getfval(u) != 0.0);
else {
s = getsval(u);
i = (s != (char *)NULL) && (*s != '\0');
}
c_free(u);
if (i)
u = execute(p->n_arg[1]);
else if (p->n_arg[2])
u = execute(p->n_arg[2]);
else
u = &truecell;
return u;
}
static CELL *
While(p) NODE *p;
{
CELL *u;
double x;
for (;;) {
u = execute(p->n_arg[0]);
x = getfval(u);
if (x == 0.0)
break;
c_free(u);
u = execute(p->n_arg[1]);
switch (u->c_type) {
case BRK:
goto rtn;
case NXT: case EXT: case RTN:
return u;
}
c_free(u);
}
rtn:
c_free(u);
return &truecell;
}
static CELL *
Do(p) NODE *p;
{
CELL *u;
double x;
for (;;) {
u = execute(p->n_arg[0]);
switch (u->c_type) {
case BRK:
goto rtn;
case NXT: case EXT: case RTN:
return u;
}
c_free(u);
u = execute(p->n_arg[1]);
if(getfval(u) == 0.0)
break;
c_free(u);
}
rtn:
c_free(u);
return &truecell;
}
static CELL *
For(p) NODE *p;
{
CELL *u;
double x;
if (p->n_arg[0] != NULL) {
u = execute(p->n_arg[0]);
c_free(u);
}
for (;;) {
if (p->n_arg[1] != NULL) {
u = execute(p->n_arg[1]);
x = getfval(u);
c_free(u);
if (x == 0.0)
break;
}
u = execute(p->n_arg[3]);
switch (u->c_type) {
case BRK:
c_free(u);
goto rtn;
case NXT: case EXT: case RTN:
return u;
}
if (p->n_arg[2] != NULL) {
u = execute(p->n_arg[2]);
c_free(u);
}
}
rtn:
return &truecell;
}
static CELL *
Jump(p) NODE *p;
{
CELL *u;
int i;
switch ((int) p->n_arg[0]) {
case BREAK: u = &breakcell; break;
case CONTIN: u = &contcell; break;
case EXIT:
if ((int) p->n_arg[1]) {
u = execute(p->n_arg[1]);
i = (int) getfval(u);
}
else
i = 0;
closeall();
exit(i);
case RETURN:
Return(p);
u = &retcell;
break;
case NEXT: u = &nextcell; break;
}
return u;
}
static
Return(p) NODE *p;
{
CELL *u;
int i;
char *s, str[BUFSIZ];
c_free(retval);
if (p->n_arg[1] != NULL) {
if (p->n_arg[2] == NULL) {
/*
if (0) {
*/
u = execute(p->n_arg[1]);
if (u->c_type == UDF)
retval = mktmp(STR, "", 0.0);
else
retval = mktmp(u->c_type, u->c_sval, u->c_fval);
c_free(u);
}
else {
for (i = 1; p->n_arg[i] != NULL; i++) {
if (i == 1)
*str = '\0';
else
strcat(str, *OFS);
u = execute(p->n_arg[i]);
s = getsval(u);
strcat(str, s);
c_free(u);
}
/*
printf("Ret(%s)(%d)\n", str, isnum(str));
*/
if (isnum(str))
retval = mktmp(STR|NUM, str, atof(str));
else
retval = mktmp(STR, str, 0.0);
}
}
else
retval = &truecell;
}
#define MAXFRAME 100
CELL **frame[MAXFRAME];
static int framep;
static CELL *
Arg(p) NODE *p;
{
CELL *u;
int i;
u = (CELL *)p->n_arg[0];
return _Arg((int)u->c_fval);
}
CELL *
_Arg(i)
{
/*
printf("Arg(%d)\n", i);
*/
return frame[framep - 1][i];
}
static CELL *
Call(p) NODE *p;
{
CELL *u, *v, *r, **arg;
NODE *q;
int i, j, k, n;
char *emalloc();
if (framep >= MAXFRAME - 2)
error("stack frame overflow", (char *)0);
retval = &truecell;
r = (CELL *) p->n_arg[0];
if (r->c_type != FUN)
synerr("called function is not declared", (char *)0);
n = (int) r->c_fval; /* # of params */
if (n > 0) {
arg = (CELL **) emalloc(sizeof(u) * n);
for (i = 2, j = 0, k = (int) p->n_arg[1]; j < k; i++) {
u = execute(p->n_arg[i]);
/*
printf("pass, j(%d)typ(%d)\n", j, u->c_type);
*/
if (u->c_type & ARR)
v = u; /* pass by reference */
else { /* pass by value */
v = mkcell(UDF, u->c_sval, u->c_fval);
if (u->c_type != UDF) {
#if 0
v->c_type = u->c_type;
if (v->c_type & (NUM|STR))
v->c_type |= VAR;
v->c_type &= ~TMP; /* dont't free */
#else
v->c_type |= (u->c_type & (NUM|STR))|VAR;
/*v->c_type &= ~TMP;*/
#endif
/* Don't free original */
}
/*
printf("pass1, j(%d)typ(%d)\n", j, v->c_type);
*/
}
arg[j++] = v;
}
for ( ; j < n; ) /* local var */
arg[j++] = mkcell(UDF, NULL, 0.0);
}
else
arg = NULL;
frame[framep] = arg;
framep++;
r = execute(r->c_sval);
c_free(r);
framep--;
if (n > 0) {
for (j = n - 1 ; j > k; j--) { /* local var */
u = arg[j];
if (u->c_type & ARR)
a_free(u);
else
c_free(u);
}
for ( ; j >= 0; j--) {
u = arg[j];
if (!(u->c_type & ARR)) {
/* c_free(u);*/
sfree(u->c_sval);
sfree(u);
}
else {
v = execute(p->n_arg[j + 2]);
if (v->c_type == UDF) { /* copy back */
/*
printf("copy_back_UDF(%d)(%d)\n", j, u->c_type);
*/
v->c_type = u->c_type;
sfree(v->c_sval);
v->c_sval = u->c_sval;
v->c_fval = u->c_fval;
sfree(u);
}
}
}
}
sfree(arg);
/* return retval;*/
u = mktmp(retval->c_type, retval->c_sval, retval->c_fval);
return u;
}
CELL *Nulproc()
{
return &truecell;
}
CELL *
Usrfun(p) NODE *p;
{
CELL *u;
u = execute(p);
return u;
}

View File

@@ -1,43 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
isKanji(c)
{
c &= 0xff;
return (c > 0x80 && c < 0xa0 || c > 0xdf && c < 0xfd);
}
jstrlen(s) char *s;
{
int i;
for (i = 0; *s; i++, s++)
if (isKanji(*s))
s++;
return i;
}
char *
jStrchr(s, c) char *s;
{
for ( ; *s; s++)
if (isKanji(*s))
s++;
else if (*s == c)
return s;
return NULL;
}

View File

@@ -1,353 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
#include <ctype.h>
#include "awk.h"
extern char *srcprg; /* inline program */
extern FILE *pfp; /* program file */
int sym; /* lexical token */
int sym1; /* auxiliary lexical token */
int regexflg; /* set by parser (y.c) to indicate parsing REGEXPR */
int funflg; /* set by parser (y.c) to indicate parsing FUNCTION */
int printflg; /* set by parser (y.c) to indicate parsing PRINT */
int getlineflg; /* set by parser (y.c) to indicate parsing GETLINE */
char text[BUFSIZ]; /* lexical word */
char line[BUFSIZ]; /* program line for error message (ring buffer) */
char *linep = line; /* line pointer */
char funnam[128]; /* function name for error message */
int lineno = 1;
lex()
{
int c, d;
char *s;
if (regexflg)
return sym = scanreg();
next:
while ((c = Getc()) == ' ' || c == '\t')
;
while (c == '#')
for (c = Getc(); c != '\n'; c = Getc())
;
switch (c) {
case '\\':
if ((c = Getc()) == '\n') {
lineno++;
goto next;
}
break;
case '\n':
lineno++;
break;
}
switch (c) {
case EOF: return sym = 0;
case '+': return sym = follow2('=', '+', ADDEQ, INC, ADD);
case '-': return sym = follow2('=', '-', SUBEQ, DEC, SUB);
case '*': return sym = follow('=', MULTEQ, MULT);
case '/': return sym = follow('=', DIVEQ, DIV);
case '%': return sym = follow('=', MODEQ, MOD);
case '^': return sym = follow('=', POWEQ, POWER);
case '=': return sym = follow('=', EQ, ASSIGN);
case '!': return sym = follow2('=', '~', NE, NOMATCH, NOT);
case '&': return sym = follow('&', AND, BINAND);
case '|': sym = follow('|', OR, BINOR);
if (printflg && sym == BINOR)
sym = R_POUT;
return sym;
case '<': sym = follow2('=', '<', LE, SHIFTL, LT);
if (getlineflg && sym == LT)
sym = R_IN;
return sym;
case '>': sym = follow2('=', '>', GE, SHIFTR, GT);
if (printflg) {
switch (sym) {
case GT: sym = R_OUT; break;
case SHIFTR: sym = R_APD; break;
}
}
return sym;
case '~': return sym = MATCH; break;
case ';': case '\n': return sym = EOL;
}
if (isalpha(c) || c == '_') {
for (s = text; isalnum(c) || c == '_'; ) {
*s++ = c; c = Getc();
}
Ungetc(c);
*s = '\0';
if ((d = iskeywd(text)) == 0 &&
(d = isbuiltin(text, &sym1)) == 0) {
if (c == '(')
return sym = CALL;
else if (funflg) {
if ((sym1 = isarg(text)) != -1)
return sym = ARG;
}
}
return sym = d ? d : IDENT;
}
else if (c == '.' || (isdigit(c))) {
Ungetc(c);
return sym = scannum(text); /* NUMBER */
}
else if (c == '"')
return sym = scanstr(text); /* STRING */
return sym = c;
}
static
follow(c1, r1, r2)
{
register int c;
if ((c = Getc()) == c1)
return r1;
else {
Ungetc(c);
return r2;
}
}
static
follow2(c1, c2, r1, r2, r3)
{
register int c;
if ((c = Getc()) == c1)
return r1;
else if (c == c2)
return r2;
else {
Ungetc(c);
return r3;
}
}
static
iskeywd(s) char *s;
{
static struct { char *kw; int token; } tab[] = {
"BEGIN", BEGIN,
"END", END,
"break", BREAK,
"continue", CONTIN,
"delete", DELETE,
"do", DO,
"else", ELSE,
"exit", EXIT,
"for", FOR,
"func", FUNC,
"function", FUNC,
"getline", GETLINE,
"if", IF,
"in", IN,
"next", NEXT,
"print", PRINT,
"printf", PRINTF,
"return", RETURN,
"sprint", SPRINT,
"sprintf", SPRINTF,
"while", WHILE,
"", 0, 0
};
register int i;
for (i = 0; tab[i].token; i++)
if (strcmp(tab[i].kw, s) == 0)
break;
return tab[i].token;
}
static
isbuiltin(s, p) char *s; int *p;
{
static struct { char *kw; int type; int token; } tab[] = {
"atan2", MATHFUN, ATAN2,
"close", STRFUN, CLOSE,
"cos", MATHFUN, COS,
"exp", MATHFUN, EXP,
"gsub", SUBST, RGSUB,
"index", STRFUN, INDEX,
"int", MATHFUN, INT,
"length", STRFUN, LENGTH,
"log", MATHFUN, LOG,
"match", STRFUN, RMATCH,
"sin", MATHFUN, SIN,
"sqrt", MATHFUN, SQRT,
"rand", MATHFUN, RAND,
"srand", MATHFUN, SRAND,
"split", STRFUN, SPLIT,
"sub", SUBST, RSUB,
"substr", STRFUN, SUBSTR,
"system", STRFUN, SYSTEM,
"", 0, 0
};
register int i;
for (i = 0; tab[i].token; i++)
if (strcmp(tab[i].kw, s) == 0)
break;
*p = tab[i].token;
return tab[i].type;
}
static
scannum(s) char *s;
{
register int c;
char *strchr();
if ((c = Getc()) && strchr("+-", c) != NULL) {
*s++ = c; c = Getc();
}
while (isdigit(c)) {
*s++ = c; c = Getc();
}
if (c == '.') {
*s++ = c; c = Getc();
while (isdigit(c)) {
*s++ = c; c = Getc();
}
}
if (c && strchr("eE", c) != NULL) {
*s++ = c; c = Getc();
if (c && strchr("+-", c) != NULL) {
*s++ = c; c = Getc();
}
while (isdigit(c)) {
*s++ = c; c = Getc();
}
}
*s = '\0';
Ungetc(c);
return NUMBER;
}
static
scanstr(s) char *s;
{
register int c, i, j;
for (c = Getc(); c != EOF & c != '"'; ) {
if (c == '\\') {
switch (c = Getc()) {
case 'b': c = '\b'; break;
case 'f': c = '\f'; break;
case 'n': c = '\n'; break;
case 'r': c = '\r'; break;
case 't': c = '\t'; break;
default:
if (isdigit(c)) {
for (i = j = 0; i < 3 && isdigit(c); c = Getc(), i++)
j = j * 8 + c - '0';
Ungetc(c);
c = j;
}
break;
}
}
*s++ = c;
if (isKanji(c))
*s++ = Getc();
c = Getc();
}
*s = '\0';
return STRING;
}
static
scanreg()
{
register int c;
register char *s;
for (s = text; (c = Getc()) != '/'; )
if (c == '\n')
error("newline in regular expression");
else {
if (isKanji(c) || c == '\\') {
*s++ = c; c = Getc();
}
*s++ = c;
}
*s = '\0';
return REGEXP;
}
isarrayindex()
{
int c, c2;
next:
while ((c = Getc()) == ' ' || c == '\t')
;
if (c == '\\') {
if ((c2 = Getc()) == '\n') {
lineno++;
goto next;
}
Ungetc(c2);
}
if (c != '[') Ungetc(c);
return (c == '[');
}
#define UNGET_DEPTH 2
static int unget[UNGET_DEPTH], unget_depth;
Ungetc(c)
{
if (unget_depth == UNGET_DEPTH) error("unget buffer overflow");
unget[unget_depth++] = c;
if (linep > line) {
if (--linep < line)
linep == line + BUFSIZ - 1;
}
}
Getc()
{
register int c;
char *s, *t;
if (unget_depth > 0)
c = unget[--unget_depth];
else if (srcprg)
c = *srcprg ? *srcprg++ : EOF;
else
c = fgetc(pfp);
#if 0
if (linep - line == BUFSIZ) {
printf("!!!\n");
for (s = line; *s != '\n' && ((s - line) <BUFSIZ); s++)
;
printf("***(%d)***\n", *s);
for (t = line; s < linep; )
*t++ = *++s;
}
#endif
*linep++ = c;
if ((linep - line) == BUFSIZ)
linep = line;
return c;
}

582
commands/awk/lex.c Normal file
View File

@@ -0,0 +1,582 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "awk.h"
#include "awkgram.h"
extern YYSTYPE yylval;
extern int infunc;
int lineno = 1;
int bracecnt = 0;
int brackcnt = 0;
int parencnt = 0;
typedef struct Keyword {
const char *word;
int sub;
int type;
} Keyword;
Keyword keywords[] ={ /* keep sorted: binary searched */
{ "BEGIN", XBEGIN, XBEGIN },
{ "END", XEND, XEND },
{ "NF", VARNF, VARNF },
{ "atan2", FATAN, BLTIN },
{ "break", BREAK, BREAK },
{ "close", CLOSE, CLOSE },
{ "continue", CONTINUE, CONTINUE },
{ "cos", FCOS, BLTIN },
{ "delete", DELETE, DELETE },
{ "do", DO, DO },
{ "else", ELSE, ELSE },
{ "exit", EXIT, EXIT },
{ "exp", FEXP, BLTIN },
{ "fflush", FFLUSH, BLTIN },
{ "for", FOR, FOR },
{ "func", FUNC, FUNC },
{ "function", FUNC, FUNC },
{ "getline", GETLINE, GETLINE },
{ "gsub", GSUB, GSUB },
{ "if", IF, IF },
{ "in", IN, IN },
{ "index", INDEX, INDEX },
{ "int", FINT, BLTIN },
{ "length", FLENGTH, BLTIN },
{ "log", FLOG, BLTIN },
{ "match", MATCHFCN, MATCHFCN },
{ "next", NEXT, NEXT },
{ "nextfile", NEXTFILE, NEXTFILE },
{ "print", PRINT, PRINT },
{ "printf", PRINTF, PRINTF },
{ "rand", FRAND, BLTIN },
{ "return", RETURN, RETURN },
{ "sin", FSIN, BLTIN },
{ "split", SPLIT, SPLIT },
{ "sprintf", SPRINTF, SPRINTF },
{ "sqrt", FSQRT, BLTIN },
{ "srand", FSRAND, BLTIN },
{ "sub", SUB, SUB },
{ "substr", SUBSTR, SUBSTR },
{ "system", FSYSTEM, BLTIN },
{ "tolower", FTOLOWER, BLTIN },
{ "toupper", FTOUPPER, BLTIN },
{ "while", WHILE, WHILE },
};
#define RET(x) { if(dbg)printf("lex %s\n", tokname(x)); return(x); }
int peek(void)
{
int c = input();
unput(c);
return c;
}
int gettok(char **pbuf, int *psz) /* get next input token */
{
int c, retc;
char *buf = *pbuf;
int sz = *psz;
char *bp = buf;
c = input();
if (c == 0)
return 0;
buf[0] = c;
buf[1] = 0;
if (!isalnum(c) && c != '.' && c != '_')
return c;
*bp++ = c;
if (isalpha(c) || c == '_') { /* it's a varname */
for ( ; (c = input()) != 0; ) {
if (bp-buf >= sz)
if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok"))
FATAL( "out of space for name %.10s...", buf );
if (isalnum(c) || c == '_')
*bp++ = c;
else {
*bp = 0;
unput(c);
break;
}
}
*bp = 0;
retc = 'a'; /* alphanumeric */
} else { /* maybe it's a number, but could be . */
char *rem;
/* read input until can't be a number */
for ( ; (c = input()) != 0; ) {
if (bp-buf >= sz)
if (!adjbuf(&buf, &sz, bp-buf+2, 100, &bp, "gettok"))
FATAL( "out of space for number %.10s...", buf );
if (isdigit(c) || c == 'e' || c == 'E'
|| c == '.' || c == '+' || c == '-')
*bp++ = c;
else {
unput(c);
break;
}
}
*bp = 0;
strtod(buf, &rem); /* parse the number */
if (rem == buf) { /* it wasn't a valid number at all */
buf[1] = 0; /* return one character as token */
retc = buf[0]; /* character is its own type */
unputstr(rem+1); /* put rest back for later */
} else { /* some prefix was a number */
unputstr(rem); /* put rest back for later */
rem[0] = 0; /* truncate buf after number part */
retc = '0'; /* type is number */
}
}
*pbuf = buf;
*psz = sz;
return retc;
}
int word(char *);
int string(void);
int regexpr(void);
int sc = 0; /* 1 => return a } right now */
int reg = 0; /* 1 => return a REGEXPR now */
int yylex(void)
{
int c;
static char *buf = 0;
static int bufsize = 5; /* BUG: setting this small causes core dump! */
if (buf == 0 && (buf = (char *) malloc(bufsize)) == NULL)
FATAL( "out of space in yylex" );
if (sc) {
sc = 0;
RET('}');
}
if (reg) {
reg = 0;
return regexpr();
}
for (;;) {
c = gettok(&buf, &bufsize);
if (c == 0)
return 0;
if (isalpha(c) || c == '_')
return word(buf);
if (isdigit(c)) {
yylval.cp = setsymtab(buf, tostring(buf), atof(buf), CON|NUM, symtab);
/* should this also have STR set? */
RET(NUMBER);
}
yylval.i = c;
switch (c) {
case '\n': /* {EOL} */
RET(NL);
case '\r': /* assume \n is coming */
case ' ': /* {WS}+ */
case '\t':
break;
case '#': /* #.* strip comments */
while ((c = input()) != '\n' && c != 0)
;
unput(c);
break;
case ';':
RET(';');
case '\\':
if (peek() == '\n') {
input();
} else if (peek() == '\r') {
input(); input(); /* \n */
lineno++;
} else {
RET(c);
}
break;
case '&':
if (peek() == '&') {
input(); RET(AND);
} else
RET('&');
case '|':
if (peek() == '|') {
input(); RET(BOR);
} else
RET('|');
case '!':
if (peek() == '=') {
input(); yylval.i = NE; RET(NE);
} else if (peek() == '~') {
input(); yylval.i = NOTMATCH; RET(MATCHOP);
} else
RET(NOT);
case '~':
yylval.i = MATCH;
RET(MATCHOP);
case '<':
if (peek() == '=') {
input(); yylval.i = LE; RET(LE);
} else {
yylval.i = LT; RET(LT);
}
case '=':
if (peek() == '=') {
input(); yylval.i = EQ; RET(EQ);
} else {
yylval.i = ASSIGN; RET(ASGNOP);
}
case '>':
if (peek() == '=') {
input(); yylval.i = GE; RET(GE);
} else if (peek() == '>') {
input(); yylval.i = APPEND; RET(APPEND);
} else {
yylval.i = GT; RET(GT);
}
case '+':
if (peek() == '+') {
input(); yylval.i = INCR; RET(INCR);
} else if (peek() == '=') {
input(); yylval.i = ADDEQ; RET(ASGNOP);
} else
RET('+');
case '-':
if (peek() == '-') {
input(); yylval.i = DECR; RET(DECR);
} else if (peek() == '=') {
input(); yylval.i = SUBEQ; RET(ASGNOP);
} else
RET('-');
case '*':
if (peek() == '=') { /* *= */
input(); yylval.i = MULTEQ; RET(ASGNOP);
} else if (peek() == '*') { /* ** or **= */
input(); /* eat 2nd * */
if (peek() == '=') {
input(); yylval.i = POWEQ; RET(ASGNOP);
} else {
RET(POWER);
}
} else
RET('*');
case '/':
RET('/');
case '%':
if (peek() == '=') {
input(); yylval.i = MODEQ; RET(ASGNOP);
} else
RET('%');
case '^':
if (peek() == '=') {
input(); yylval.i = POWEQ; RET(ASGNOP);
} else
RET(POWER);
case '$':
/* BUG: awkward, if not wrong */
c = gettok(&buf, &bufsize);
if (isalpha(c)) {
if (strcmp(buf, "NF") == 0) { /* very special */
unputstr("(NF)");
RET(INDIRECT);
}
c = peek();
if (c == '(' || c == '[' || (infunc && isarg(buf) >= 0)) {
unputstr(buf);
RET(INDIRECT);
}
yylval.cp = setsymtab(buf, "", 0.0, STR|NUM, symtab);
RET(IVAR);
} else if (c == 0) { /* */
SYNTAX( "unexpected end of input after $" );
RET(';');
} else {
unputstr(buf);
RET(INDIRECT);
}
case '}':
if (--bracecnt < 0)
SYNTAX( "extra }" );
sc = 1;
RET(';');
case ']':
if (--brackcnt < 0)
SYNTAX( "extra ]" );
RET(']');
case ')':
if (--parencnt < 0)
SYNTAX( "extra )" );
RET(')');
case '{':
bracecnt++;
RET('{');
case '[':
brackcnt++;
RET('[');
case '(':
parencnt++;
RET('(');
case '"':
return string(); /* BUG: should be like tran.c ? */
default:
RET(c);
}
}
}
int string(void)
{
int c, n;
char *s, *bp;
static char *buf = 0;
static int bufsz = 500;
if (buf == 0 && (buf = (char *) malloc(bufsz)) == NULL)
FATAL("out of space for strings");
for (bp = buf; (c = input()) != '"'; ) {
if (!adjbuf(&buf, &bufsz, bp-buf+2, 500, &bp, "string"))
FATAL("out of space for string %.10s...", buf);
switch (c) {
case '\n':
case '\r':
case 0:
SYNTAX( "non-terminated string %.10s...", buf );
lineno++;
if (c == 0) /* hopeless */
FATAL( "giving up" );
break;
case '\\':
c = input();
switch (c) {
case '"': *bp++ = '"'; break;
case 'n': *bp++ = '\n'; break;
case 't': *bp++ = '\t'; break;
case 'f': *bp++ = '\f'; break;
case 'r': *bp++ = '\r'; break;
case 'b': *bp++ = '\b'; break;
case 'v': *bp++ = '\v'; break;
case 'a': *bp++ = '\007'; break;
case '\\': *bp++ = '\\'; break;
case '0': case '1': case '2': /* octal: \d \dd \ddd */
case '3': case '4': case '5': case '6': case '7':
n = c - '0';
if ((c = peek()) >= '0' && c < '8') {
n = 8 * n + input() - '0';
if ((c = peek()) >= '0' && c < '8')
n = 8 * n + input() - '0';
}
*bp++ = n;
break;
case 'x': /* hex \x0-9a-fA-F + */
{ char xbuf[100], *px;
for (px = xbuf; (c = input()) != 0 && px-xbuf < 100-2; ) {
if (isdigit(c)
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F'))
*px++ = c;
else
break;
}
*px = 0;
unput(c);
sscanf(xbuf, "%x", &n);
*bp++ = n;
break;
}
default:
*bp++ = c;
break;
}
break;
default:
*bp++ = c;
break;
}
}
*bp = 0;
s = tostring(buf);
*bp++ = ' '; *bp++ = 0;
yylval.cp = setsymtab(buf, s, 0.0, CON|STR|DONTFREE, symtab);
RET(STRING);
}
int binsearch(const char *w, const Keyword *kp, int n)
{
int cond, low, mid, high;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if ((cond = strcmp(w, kp[mid].word)) < 0)
high = mid - 1;
else if (cond > 0)
low = mid + 1;
else
return mid;
}
return -1;
}
int word(char *w)
{
Keyword *kp;
int c, n;
n = binsearch(w, keywords, sizeof(keywords)/sizeof(keywords[0]));
/* BUG: this ought to be inside the if; in theory could fault (daniel barrett) */
kp = keywords + n;
if (n != -1) { /* found in table */
yylval.i = kp->sub;
switch (kp->type) { /* special handling */
case BLTIN:
if (kp->sub == FSYSTEM && safe)
SYNTAX( "system is unsafe" );
RET(kp->type);
case FUNC:
if (infunc)
SYNTAX( "illegal nested function" );
RET(kp->type);
case RETURN:
if (!infunc)
SYNTAX( "return not in function" );
RET(kp->type);
case VARNF:
yylval.cp = setsymtab("NF", "", 0.0, NUM, symtab);
RET(VARNF);
default:
RET(kp->type);
}
}
c = peek(); /* look for '(' */
if (c != '(' && infunc && (n=isarg(w)) >= 0) {
yylval.i = n;
RET(ARG);
} else {
yylval.cp = setsymtab(w, "", 0.0, STR|NUM|DONTFREE, symtab);
if (c == '(') {
RET(CALL);
} else {
RET(VAR);
}
}
}
void startreg(void) /* next call to yylex will return a regular expression */
{
reg = 1;
}
int regexpr(void)
{
int c;
static char *buf = 0;
static int bufsz = 500;
char *bp;
if (buf == 0 && (buf = (char *) malloc(bufsz)) == NULL)
FATAL("out of space for rex expr");
bp = buf;
for ( ; (c = input()) != '/' && c != 0; ) {
if (!adjbuf(&buf, &bufsz, bp-buf+3, 500, &bp, "regexpr"))
FATAL("out of space for reg expr %.10s...", buf);
if (c == '\n') {
SYNTAX( "newline in regular expression %.10s...", buf );
unput('\n');
break;
} else if (c == '\\') {
*bp++ = '\\';
*bp++ = input();
} else {
*bp++ = c;
}
}
*bp = 0;
if (c == 0)
SYNTAX("non-terminated regular expression %.10s...", buf);
yylval.s = tostring(buf);
unput('/');
RET(REGEXPR);
}
/* low-level lexical stuff, sort of inherited from lex */
char ebuf[300];
char *ep = ebuf;
char yysbuf[100]; /* pushback buffer */
char *yysptr = yysbuf;
FILE *yyin = 0;
int input(void) /* get next lexical input character */
{
int c;
extern char *lexprog;
if (yysptr > yysbuf)
c = (uschar)*--yysptr;
else if (lexprog != NULL) { /* awk '...' */
if ((c = (uschar)*lexprog) != 0)
lexprog++;
} else /* awk -f ... */
c = pgetc();
if (c == '\n')
lineno++;
else if (c == EOF)
c = 0;
if (ep >= ebuf + sizeof ebuf)
ep = ebuf;
return *ep++ = c;
}
void unput(int c) /* put lexical character back on input */
{
if (c == '\n')
lineno--;
if (yysptr >= yysbuf + sizeof(yysbuf))
FATAL("pushed back too much: %.20s...", yysbuf);
*yysptr++ = c;
if (--ep < ebuf)
ep = ebuf + sizeof(ebuf) - 1;
}
void unputstr(const char *s) /* put a string back on input */
{
int i;
for (i = strlen(s)-1; i >= 0; i--)
unput(s[i]);
}

697
commands/awk/lib.c Normal file
View File

@@ -0,0 +1,697 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#define DEBUG
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <stdarg.h>
#include "awk.h"
#include "awkgram.h"
FILE *infile = NULL;
char *file = "";
char *record;
int recsize = RECSIZE;
char *fields;
int fieldssize = RECSIZE;
Cell **fldtab; /* pointers to Cells */
char inputFS[100] = " ";
#define MAXFLD 2
int nfields = MAXFLD; /* last allocated slot for $i */
int donefld; /* 1 = implies rec broken into fields */
int donerec; /* 1 = record is valid (no flds have changed) */
int lastfld = 0; /* last used field */
int argno = 1; /* current input argument number */
extern Awkfloat *ARGC;
static Cell dollar0 = { OCELL, CFLD, NULL, "", 0.0, REC|STR|DONTFREE };
static Cell dollar1 = { OCELL, CFLD, NULL, "", 0.0, FLD|STR|DONTFREE };
void recinit(unsigned int n)
{
if ( (record = (char *) malloc(n)) == NULL
|| (fields = (char *) malloc(n+1)) == NULL
|| (fldtab = (Cell **) malloc((nfields+1) * sizeof(Cell *))) == NULL
|| (fldtab[0] = (Cell *) malloc(sizeof(Cell))) == NULL )
FATAL("out of space for $0 and fields");
*fldtab[0] = dollar0;
fldtab[0]->sval = record;
fldtab[0]->nval = tostring("0");
makefields(1, nfields);
}
void makefields(int n1, int n2) /* create $n1..$n2 inclusive */
{
char temp[50];
int i;
for (i = n1; i <= n2; i++) {
fldtab[i] = (Cell *) malloc(sizeof (struct Cell));
if (fldtab[i] == NULL)
FATAL("out of space in makefields %d", i);
*fldtab[i] = dollar1;
sprintf(temp, "%d", i);
fldtab[i]->nval = tostring(temp);
}
}
void initgetrec(void)
{
int i;
char *p;
for (i = 1; i < *ARGC; i++) {
if (!isclvar(p = getargv(i))) { /* find 1st real filename */
setsval(lookup("FILENAME", symtab), getargv(i));
return;
}
setclvar(p); /* a commandline assignment before filename */
argno++;
}
infile = stdin; /* no filenames, so use stdin */
}
static int firsttime = 1;
int getrec(char **pbuf, int *pbufsize, int isrecord) /* get next input record */
{ /* note: cares whether buf == record */
int c;
char *buf = *pbuf;
uschar saveb0;
int bufsize = *pbufsize, savebufsize = bufsize;
if (firsttime) {
firsttime = 0;
initgetrec();
}
dprintf( ("RS=<%s>, FS=<%s>, ARGC=%g, FILENAME=%s\n",
*RS, *FS, *ARGC, *FILENAME) );
if (isrecord) {
donefld = 0;
donerec = 1;
}
saveb0 = buf[0];
buf[0] = 0;
while (argno < *ARGC || infile == stdin) {
dprintf( ("argno=%d, file=|%s|\n", argno, file) );
if (infile == NULL) { /* have to open a new file */
file = getargv(argno);
if (*file == '\0') { /* it's been zapped */
argno++;
continue;
}
if (isclvar(file)) { /* a var=value arg */
setclvar(file);
argno++;
continue;
}
*FILENAME = file;
dprintf( ("opening file %s\n", file) );
if (*file == '-' && *(file+1) == '\0')
infile = stdin;
else if ((infile = fopen(file, "r")) == NULL)
FATAL("can't open file %s", file);
setfval(fnrloc, 0.0);
}
c = readrec(&buf, &bufsize, infile);
if (c != 0 || buf[0] != '\0') { /* normal record */
if (isrecord) {
if (freeable(fldtab[0]))
xfree(fldtab[0]->sval);
fldtab[0]->sval = buf; /* buf == record */
fldtab[0]->tval = REC | STR | DONTFREE;
if (is_number(fldtab[0]->sval)) {
fldtab[0]->fval = atof(fldtab[0]->sval);
fldtab[0]->tval |= NUM;
}
}
setfval(nrloc, nrloc->fval+1);
setfval(fnrloc, fnrloc->fval+1);
*pbuf = buf;
*pbufsize = bufsize;
return 1;
}
/* EOF arrived on this file; set up next */
if (infile != stdin)
fclose(infile);
infile = NULL;
argno++;
}
buf[0] = saveb0;
*pbuf = buf;
*pbufsize = savebufsize;
return 0; /* true end of file */
}
void nextfile(void)
{
if (infile != NULL && infile != stdin)
fclose(infile);
infile = NULL;
argno++;
}
int readrec(char **pbuf, int *pbufsize, FILE *inf) /* read one record into buf */
{
int sep, c;
char *rr, *buf = *pbuf;
int bufsize = *pbufsize;
if (strlen(*FS) >= sizeof(inputFS))
FATAL("field separator %.10s... is too long", *FS);
strcpy(inputFS, *FS); /* for subsequent field splitting */
if ((sep = **RS) == 0) {
sep = '\n';
while ((c=getc(inf)) == '\n' && c != EOF) /* skip leading \n's */
;
if (c != EOF)
ungetc(c, inf);
}
for (rr = buf; ; ) {
for (; (c=getc(inf)) != sep && c != EOF; ) {
if (rr-buf+1 > bufsize)
if (!adjbuf(&buf, &bufsize, 1+rr-buf, recsize, &rr, "readrec 1"))
FATAL("input record `%.30s...' too long", buf);
*rr++ = c;
}
if (**RS == sep || c == EOF)
break;
if ((c = getc(inf)) == '\n' || c == EOF) /* 2 in a row */
break;
if (!adjbuf(&buf, &bufsize, 2+rr-buf, recsize, &rr, "readrec 2"))
FATAL("input record `%.30s...' too long", buf);
*rr++ = '\n';
*rr++ = c;
}
if (!adjbuf(&buf, &bufsize, 1+rr-buf, recsize, &rr, "readrec 3"))
FATAL("input record `%.30s...' too long", buf);
*rr = 0;
dprintf( ("readrec saw <%s>, returns %d\n", buf, c == EOF && rr == buf ? 0 : 1) );
*pbuf = buf;
*pbufsize = bufsize;
return c == EOF && rr == buf ? 0 : 1;
}
char *getargv(int n) /* get ARGV[n] */
{
Cell *x;
char *s, temp[50];
extern Array *ARGVtab;
sprintf(temp, "%d", n);
x = setsymtab(temp, "", 0.0, STR, ARGVtab);
s = getsval(x);
dprintf( ("getargv(%d) returns |%s|\n", n, s) );
return s;
}
void setclvar(char *s) /* set var=value from s */
{
char *p;
Cell *q;
for (p=s; *p != '='; p++)
;
*p++ = 0;
p = qstring(p, '\0');
q = setsymtab(s, p, 0.0, STR, symtab);
setsval(q, p);
if (is_number(q->sval)) {
q->fval = atof(q->sval);
q->tval |= NUM;
}
dprintf( ("command line set %s to |%s|\n", s, p) );
}
void fldbld(void) /* create fields from current record */
{
/* this relies on having fields[] the same length as $0 */
/* the fields are all stored in this one array with \0's */
char *r, *fr, sep;
Cell *p;
int i, j, n;
if (donefld)
return;
if (!isstr(fldtab[0]))
getsval(fldtab[0]);
r = fldtab[0]->sval;
n = strlen(r);
if (n > fieldssize) {
xfree(fields);
if ((fields = (char *) malloc(n+1)) == NULL)
FATAL("out of space for fields in fldbld %d", n);
fieldssize = n;
}
fr = fields;
i = 0; /* number of fields accumulated here */
strcpy(inputFS, *FS);
if (strlen(inputFS) > 1) { /* it's a regular expression */
i = refldbld(r, inputFS);
} else if ((sep = *inputFS) == ' ') { /* default whitespace */
for (i = 0; ; ) {
while (*r == ' ' || *r == '\t' || *r == '\n')
r++;
if (*r == 0)
break;
i++;
if (i > nfields)
growfldtab(i);
if (freeable(fldtab[i]))
xfree(fldtab[i]->sval);
fldtab[i]->sval = fr;
fldtab[i]->tval = FLD | STR | DONTFREE;
do
*fr++ = *r++;
while (*r != ' ' && *r != '\t' && *r != '\n' && *r != '\0');
*fr++ = 0;
}
*fr = 0;
} else if ((sep = *inputFS) == 0) { /* new: FS="" => 1 char/field */
for (i = 0; *r != 0; r++) {
char buf[2];
i++;
if (i > nfields)
growfldtab(i);
if (freeable(fldtab[i]))
xfree(fldtab[i]->sval);
buf[0] = *r;
buf[1] = 0;
fldtab[i]->sval = tostring(buf);
fldtab[i]->tval = FLD | STR;
}
*fr = 0;
} else if (*r != 0) { /* if 0, it's a null field */
/* subtlecase : if length(FS) == 1 && length(RS > 0)
* \n is NOT a field separator (cf awk book 61,84).
* this variable is tested in the inner while loop.
*/
int rtest = '\n'; /* normal case */
if (strlen(*RS) > 0)
rtest = '\0';
for (;;) {
i++;
if (i > nfields)
growfldtab(i);
if (freeable(fldtab[i]))
xfree(fldtab[i]->sval);
fldtab[i]->sval = fr;
fldtab[i]->tval = FLD | STR | DONTFREE;
while (*r != sep && *r != rtest && *r != '\0') /* \n is always a separator */
*fr++ = *r++;
*fr++ = 0;
if (*r++ == 0)
break;
}
*fr = 0;
}
if (i > nfields)
FATAL("record `%.30s...' has too many fields; can't happen", r);
cleanfld(i+1, lastfld); /* clean out junk from previous record */
lastfld = i;
donefld = 1;
for (j = 1; j <= lastfld; j++) {
p = fldtab[j];
if(is_number(p->sval)) {
p->fval = atof(p->sval);
p->tval |= NUM;
}
}
setfval(nfloc, (Awkfloat) lastfld);
if (dbg) {
for (j = 0; j <= lastfld; j++) {
p = fldtab[j];
printf("field %d (%s): |%s|\n", j, p->nval, p->sval);
}
}
}
void cleanfld(int n1, int n2) /* clean out fields n1 .. n2 inclusive */
{ /* nvals remain intact */
Cell *p;
int i;
for (i = n1; i <= n2; i++) {
p = fldtab[i];
if (freeable(p))
xfree(p->sval);
p->sval = "";
p->tval = FLD | STR | DONTFREE;
}
}
void newfld(int n) /* add field n after end of existing lastfld */
{
if (n > nfields)
growfldtab(n);
cleanfld(lastfld+1, n);
lastfld = n;
setfval(nfloc, (Awkfloat) n);
}
Cell *fieldadr(int n) /* get nth field */
{
if (n < 0)
FATAL("trying to access out of range field %d", n);
if (n > nfields) /* fields after NF are empty */
growfldtab(n); /* but does not increase NF */
return(fldtab[n]);
}
void growfldtab(int n) /* make new fields up to at least $n */
{
int nf = 2 * nfields;
size_t s;
if (n > nf)
nf = n;
s = (nf+1) * (sizeof (struct Cell *)); /* freebsd: how much do we need? */
if (s / sizeof(struct Cell *) - 1 == nf) /* didn't overflow */
fldtab = (Cell **) realloc(fldtab, s);
else /* overflow sizeof int */
xfree(fldtab); /* make it null */
if (fldtab == NULL)
FATAL("out of space creating %d fields", nf);
makefields(nfields+1, nf);
nfields = nf;
}
int refldbld(const char *rec, const char *fs) /* build fields from reg expr in FS */
{
/* this relies on having fields[] the same length as $0 */
/* the fields are all stored in this one array with \0's */
char *fr;
int i, tempstat, n;
fa *pfa;
n = strlen(rec);
if (n > fieldssize) {
xfree(fields);
if ((fields = (char *) malloc(n+1)) == NULL)
FATAL("out of space for fields in refldbld %d", n);
fieldssize = n;
}
fr = fields;
*fr = '\0';
if (*rec == '\0')
return 0;
pfa = makedfa(fs, 1);
dprintf( ("into refldbld, rec = <%s>, pat = <%s>\n", rec, fs) );
tempstat = pfa->initstat;
for (i = 1; ; i++) {
if (i > nfields)
growfldtab(i);
if (freeable(fldtab[i]))
xfree(fldtab[i]->sval);
fldtab[i]->tval = FLD | STR | DONTFREE;
fldtab[i]->sval = fr;
dprintf( ("refldbld: i=%d\n", i) );
if (nematch(pfa, rec)) {
pfa->initstat = 2; /* horrible coupling to b.c */
dprintf( ("match %s (%d chars)\n", patbeg, patlen) );
strncpy(fr, rec, patbeg-rec);
fr += patbeg - rec + 1;
*(fr-1) = '\0';
rec = patbeg + patlen;
} else {
dprintf( ("no match %s\n", rec) );
strcpy(fr, rec);
pfa->initstat = tempstat;
break;
}
}
return i;
}
void recbld(void) /* create $0 from $1..$NF if necessary */
{
int i;
char *r, *p;
if (donerec == 1)
return;
r = record;
for (i = 1; i <= *NF; i++) {
p = getsval(fldtab[i]);
if (!adjbuf(&record, &recsize, 1+strlen(p)+r-record, recsize, &r, "recbld 1"))
FATAL("created $0 `%.30s...' too long", record);
while ((*r = *p++) != 0)
r++;
if (i < *NF) {
if (!adjbuf(&record, &recsize, 2+strlen(*OFS)+r-record, recsize, &r, "recbld 2"))
FATAL("created $0 `%.30s...' too long", record);
for (p = *OFS; (*r = *p++) != 0; )
r++;
}
}
if (!adjbuf(&record, &recsize, 2+r-record, recsize, &r, "recbld 3"))
FATAL("built giant record `%.30s...'", record);
*r = '\0';
dprintf( ("in recbld inputFS=%s, fldtab[0]=%p\n", inputFS, fldtab[0]) );
if (freeable(fldtab[0]))
xfree(fldtab[0]->sval);
fldtab[0]->tval = REC | STR | DONTFREE;
fldtab[0]->sval = record;
dprintf( ("in recbld inputFS=%s, fldtab[0]=%p\n", inputFS, fldtab[0]) );
dprintf( ("recbld = |%s|\n", record) );
donerec = 1;
}
int errorflag = 0;
void yyerror(const char *s)
{
SYNTAX("%s", s);
}
void SYNTAX(const char *fmt, ...)
{
extern char *cmdname, *curfname;
static int been_here = 0;
va_list varg;
if (been_here++ > 2)
return;
fprintf(stderr, "%s: ", cmdname);
va_start(varg, fmt);
vfprintf(stderr, fmt, varg);
va_end(varg);
fprintf(stderr, " at source line %d", lineno);
if (curfname != NULL)
fprintf(stderr, " in function %s", curfname);
if (compile_time == 1 && cursource() != NULL)
fprintf(stderr, " source file %s", cursource());
fprintf(stderr, "\n");
errorflag = 2;
eprint();
}
void fpecatch(int n)
{
FATAL("floating point exception %d", n);
}
extern int bracecnt, brackcnt, parencnt;
void bracecheck(void)
{
int c;
static int beenhere = 0;
if (beenhere++)
return;
while ((c = input()) != EOF && c != '\0')
bclass(c);
bcheck2(bracecnt, '{', '}');
bcheck2(brackcnt, '[', ']');
bcheck2(parencnt, '(', ')');
}
void bcheck2(int n, int c1, int c2)
{
if (n == 1)
fprintf(stderr, "\tmissing %c\n", c2);
else if (n > 1)
fprintf(stderr, "\t%d missing %c's\n", n, c2);
else if (n == -1)
fprintf(stderr, "\textra %c\n", c2);
else if (n < -1)
fprintf(stderr, "\t%d extra %c's\n", -n, c2);
}
void FATAL(const char *fmt, ...)
{
extern char *cmdname;
va_list varg;
fflush(stdout);
fprintf(stderr, "%s: ", cmdname);
va_start(varg, fmt);
vfprintf(stderr, fmt, varg);
va_end(varg);
error();
if (dbg > 1) /* core dump if serious debugging on */
abort();
exit(2);
}
void WARNING(const char *fmt, ...)
{
extern char *cmdname;
va_list varg;
fflush(stdout);
fprintf(stderr, "%s: ", cmdname);
va_start(varg, fmt);
vfprintf(stderr, fmt, varg);
va_end(varg);
error();
}
void error()
{
extern Node *curnode;
fprintf(stderr, "\n");
if (compile_time != 2 && NR && *NR > 0) {
fprintf(stderr, " input record number %d", (int) (*FNR));
if (strcmp(*FILENAME, "-") != 0)
fprintf(stderr, ", file %s", *FILENAME);
fprintf(stderr, "\n");
}
if (compile_time != 2 && curnode)
fprintf(stderr, " source line number %d", curnode->lineno);
else if (compile_time != 2 && lineno)
fprintf(stderr, " source line number %d", lineno);
if (compile_time == 1 && cursource() != NULL)
fprintf(stderr, " source file %s", cursource());
fprintf(stderr, "\n");
eprint();
}
void eprint(void) /* try to print context around error */
{
char *p, *q;
int c;
static int been_here = 0;
extern char ebuf[], *ep;
if (compile_time == 2 || compile_time == 0 || been_here++ > 0)
return;
p = ep - 1;
if (p > ebuf && *p == '\n')
p--;
for ( ; p > ebuf && *p != '\n' && *p != '\0'; p--)
;
while (*p == '\n')
p++;
fprintf(stderr, " context is\n\t");
for (q=ep-1; q>=p && *q!=' ' && *q!='\t' && *q!='\n'; q--)
;
for ( ; p < q; p++)
if (*p)
putc(*p, stderr);
fprintf(stderr, " >>> ");
for ( ; p < ep; p++)
if (*p)
putc(*p, stderr);
fprintf(stderr, " <<< ");
if (*ep)
while ((c = input()) != '\n' && c != '\0' && c != EOF) {
putc(c, stderr);
bclass(c);
}
putc('\n', stderr);
ep = ebuf;
}
void bclass(int c)
{
switch (c) {
case '{': bracecnt++; break;
case '}': bracecnt--; break;
case '[': brackcnt++; break;
case ']': brackcnt--; break;
case '(': parencnt++; break;
case ')': parencnt--; break;
}
}
double errcheck(double x, const char *s)
{
if (errno == EDOM) {
errno = 0;
WARNING("%s argument out of domain", s);
x = 1;
} else if (errno == ERANGE) {
errno = 0;
WARNING("%s result out of range", s);
x = 1;
}
return x;
}
int isclvar(const char *s) /* is s of form var=something ? */
{
const char *os = s;
if (!isalpha((uschar) *s) && *s != '_')
return 0;
for ( ; *s; s++)
if (!(isalnum((uschar) *s) || *s == '_'))
break;
return *s == '=' && s > os && *(s+1) != '=';
}
/* strtod is supposed to be a proper test of what's a valid number */
/* appears to be broken in gcc on linux: thinks 0x123 is a valid FP number */
/* wrong: violates 4.10.1.4 of ansi C standard */
#include <math.h>
int is_number(const char *s)
{
double r;
char *ep;
errno = 0;
r = strtod(s, &ep);
if (ep == s || r == HUGE_VAL || errno == ERANGE)
return 0;
while (*ep == ' ' || *ep == '\t' || *ep == '\n')
ep++;
if (*ep == '\0')
return 1;
else
return 0;
}

View File

@@ -1,153 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
#include <sys/types.h>
#include <signal.h>
#include "awk.h"
extern char **FS, **FILENAME;
extern char record[];
extern FILE *ifp;
NODE *parse();
CELL *execute();
FILE *efopen(), *fopen();
char *strsave();
int xargc;
char **xargv;
char *srcprg;
FILE *pfp;
char *cmd;
#if 0
int iflg; /* interactive mode */
#endif
main(argc, argv, envp) char **argv, *envp;
{
char *s, *strpbrk(), *strchr();
void onint();
#ifdef DOS
_sharg(&argc, &argv);
#endif
signal(SIGINT, onint);
signal(SIGFPE, onint);
cmd = argv[0];
init();
while (--argc > 0 && (*++argv)[0] == '-')
for (s = argv[0]+1; *s; s++)
if (strcmp(argv[0], "-") == 0)
break;
else
switch (*s) {
#if 0
case 'i':
iflg++;
pfp = stdin;
interactive();
/* no return */
#endif
case 'F':
*FS = ++s;
break;
case 'f':
if (*(s+1))
s++;
else {
argc--; s = *++argv;
}
if (s == NULL) usage();
pfp = efopen(s, "r");
s += strlen(s) - 1;
break;
}
xargc = argc; xargv = argv;
if (pfp == NULL && xargc > 0) {
srcprg = *xargv++; xargc--;
}
/*
if (pfp == NULL && xargc > 0) {
if (strpbrk(xargv[0], " !$^()={}[];<>,/~") != NULL) {
sprintf(record, "%s\n", xargv[0]);
srcprg = strsave(record);
}
else {
sprintf(record, "%s.awk", xargv[0]);
if ((pfp = fopen(record, "r")) == NULL)
error("can't open %s", record);
}
xargc--; xargv++;
}
*/
if (pfp == NULL && srcprg == NULL) usage();
while (*xargv != NULL && strchr(*xargv, '=') != NULL) {
setvar(*xargv++);
xargc--;
}
initarg(cmd, xargc, xargv, envp);
if (xargc == 0) {
ifp = stdin; *FILENAME = "-";
}
parse();
closeall();
exit(0);
}
FILE *
efopen(file, mode) char *file, *mode;
{
FILE *fp, *fopen();
if ((fp = fopen(file, mode)) == NULL)
error("cannot open %s", file);
return fp;
}
error(s, t) char *s, *t;
{
extern double *NR;
fprintf(stderr, "awk: ");
fprintf(stderr, s, t);
fprintf(stderr, "\n");
if (NR != NULL) {
fprintf(stderr, "record number %g\n", *NR);
}
#ifdef DOS
closeall();
#endif
exit(1);
}
void
onint(i)
{
closeall();
exit(0x80 | i);
}
void
usage()
{
fprintf(stderr,
"usage: %s [options] [-f <rulefile> | <rules>] [inputfiles]\n", cmd);
closeall();
exit(1);
}

192
commands/awk/main.c Normal file
View File

@@ -0,0 +1,192 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
const char *version = "version 20100208";
#define DEBUG
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "awk.h"
#include "awkgram.h"
extern char **environ;
extern int nfields;
int dbg = 0;
char *cmdname; /* gets argv[0] for error messages */
extern FILE *yyin; /* lex input file */
char *lexprog; /* points to program argument if it exists */
extern int errorflag; /* non-zero if any syntax errors; set by yyerror */
int compile_time = 2; /* for error printing: */
/* 2 = cmdline, 1 = compile, 0 = running */
#define MAX_PFILE 20 /* max number of -f's */
char *pfile[MAX_PFILE]; /* program filenames from -f's */
int npfile = 0; /* number of filenames */
int curpfile = 0; /* current filename */
int safe = 0; /* 1 => "safe" mode */
int main(int argc, char *argv[])
{
const char *fs = NULL;
setlocale(LC_CTYPE, "");
setlocale(LC_NUMERIC, "C"); /* for parsing cmdline & prog */
cmdname = argv[0];
if (argc == 1) {
fprintf(stderr,
"usage: %s [-F fs] [-v var=value] [-f progfile | 'prog'] [file ...]\n",
cmdname);
exit(1);
}
signal(SIGFPE, fpecatch);
yyin = NULL;
symtab = makesymtab(NSYMTAB/NSYMTAB);
while (argc > 1 && argv[1][0] == '-' && argv[1][1] != '\0') {
if (strcmp(argv[1],"-version") == 0 || strcmp(argv[1],"--version") == 0) {
printf("awk %s\n", version);
exit(0);
break;
}
if (strncmp(argv[1], "--", 2) == 0) { /* explicit end of args */
argc--;
argv++;
break;
}
switch (argv[1][1]) {
case 's':
if (strcmp(argv[1], "-safe") == 0)
safe = 1;
break;
case 'f': /* next argument is program filename */
argc--;
argv++;
if (argc <= 1)
FATAL("no program filename");
if (npfile >= MAX_PFILE - 1)
FATAL("too many -f options");
pfile[npfile++] = argv[1];
break;
case 'F': /* set field separator */
if (argv[1][2] != 0) { /* arg is -Fsomething */
if (argv[1][2] == 't' && argv[1][3] == 0) /* wart: t=>\t */
fs = "\t";
else if (argv[1][2] != 0)
fs = &argv[1][2];
} else { /* arg is -F something */
argc--; argv++;
if (argc > 1 && argv[1][0] == 't' && argv[1][1] == 0) /* wart: t=>\t */
fs = "\t";
else if (argc > 1 && argv[1][0] != 0)
fs = &argv[1][0];
}
if (fs == NULL || *fs == '\0')
WARNING("field separator FS is empty");
break;
case 'v': /* -v a=1 to be done NOW. one -v for each */
if (argv[1][2] == '\0' && --argc > 1 && isclvar((++argv)[1]))
setclvar(argv[1]);
break;
case 'd':
dbg = atoi(&argv[1][2]);
if (dbg == 0)
dbg = 1;
printf("awk %s\n", version);
break;
default:
WARNING("unknown option %s ignored", argv[1]);
break;
}
argc--;
argv++;
}
/* argv[1] is now the first argument */
if (npfile == 0) { /* no -f; first argument is program */
if (argc <= 1) {
if (dbg)
exit(0);
FATAL("no program given");
}
dprintf( ("program = |%s|\n", argv[1]) );
lexprog = argv[1];
argc--;
argv++;
}
recinit(recsize);
syminit();
compile_time = 1;
argv[0] = cmdname; /* put prog name at front of arglist */
dprintf( ("argc=%d, argv[0]=%s\n", argc, argv[0]) );
arginit(argc, argv);
if (!safe)
envinit(environ);
yyparse();
setlocale(LC_NUMERIC, ""); /* back to whatever it is locally */
if (fs)
*FS = qstring(fs, '\0');
dprintf( ("errorflag=%d\n", errorflag) );
if (errorflag == 0) {
compile_time = 0;
run(winner);
} else
bracecheck();
return(errorflag);
}
int pgetc(void) /* get 1 character from awk program */
{
int c;
for (;;) {
if (yyin == NULL) {
if (curpfile >= npfile)
return EOF;
if (strcmp(pfile[curpfile], "-") == 0)
yyin = stdin;
else if ((yyin = fopen(pfile[curpfile], "r")) == NULL)
FATAL("can't open file %s", pfile[curpfile]);
lineno = 1;
}
if ((c = getc(yyin)) != EOF)
return c;
if (yyin != stdin)
fclose(yyin);
yyin = NULL;
curpfile++;
}
}
char *cursource(void) /* current source file name */
{
if (npfile > 0)
return pfile[curpfile];
else
return NULL;
}

168
commands/awk/maketab.c Normal file
View File

@@ -0,0 +1,168 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
/*
* this program makes the table to link function names
* and type indices that is used by execute() in run.c.
* it finds the indices in awkgram.h, produced by yacc.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "awk.h"
#include "awkgram.h"
struct xx
{ int token;
const char *name;
const char *pname;
} proc[] = {
{ PROGRAM, "program", NULL },
{ BOR, "boolop", " || " },
{ AND, "boolop", " && " },
{ NOT, "boolop", " !" },
{ NE, "relop", " != " },
{ EQ, "relop", " == " },
{ LE, "relop", " <= " },
{ LT, "relop", " < " },
{ GE, "relop", " >= " },
{ GT, "relop", " > " },
{ ARRAY, "array", NULL },
{ INDIRECT, "indirect", "$(" },
{ SUBSTR, "substr", "substr" },
{ SUB, "sub", "sub" },
{ GSUB, "gsub", "gsub" },
{ INDEX, "sindex", "sindex" },
{ SPRINTF, "awksprintf", "sprintf " },
{ ADD, "arith", " + " },
{ MINUS, "arith", " - " },
{ MULT, "arith", " * " },
{ DIVIDE, "arith", " / " },
{ MOD, "arith", " % " },
{ UMINUS, "arith", " -" },
{ POWER, "arith", " **" },
{ PREINCR, "incrdecr", "++" },
{ POSTINCR, "incrdecr", "++" },
{ PREDECR, "incrdecr", "--" },
{ POSTDECR, "incrdecr", "--" },
{ CAT, "cat", " " },
{ PASTAT, "pastat", NULL },
{ PASTAT2, "dopa2", NULL },
{ MATCH, "matchop", " ~ " },
{ NOTMATCH, "matchop", " !~ " },
{ MATCHFCN, "matchop", "matchop" },
{ INTEST, "intest", "intest" },
{ PRINTF, "awkprintf", "printf" },
{ PRINT, "printstat", "print" },
{ CLOSE, "closefile", "closefile" },
{ DELETE, "awkdelete", "awkdelete" },
{ SPLIT, "split", "split" },
{ ASSIGN, "assign", " = " },
{ ADDEQ, "assign", " += " },
{ SUBEQ, "assign", " -= " },
{ MULTEQ, "assign", " *= " },
{ DIVEQ, "assign", " /= " },
{ MODEQ, "assign", " %= " },
{ POWEQ, "assign", " ^= " },
{ CONDEXPR, "condexpr", " ?: " },
{ IF, "ifstat", "if(" },
{ WHILE, "whilestat", "while(" },
{ FOR, "forstat", "for(" },
{ DO, "dostat", "do" },
{ IN, "instat", "instat" },
{ NEXT, "jump", "next" },
{ NEXTFILE, "jump", "nextfile" },
{ EXIT, "jump", "exit" },
{ BREAK, "jump", "break" },
{ CONTINUE, "jump", "continue" },
{ RETURN, "jump", "ret" },
{ BLTIN, "bltin", "bltin" },
{ CALL, "call", "call" },
{ ARG, "arg", "arg" },
{ VARNF, "getnf", "NF" },
{ GETLINE, "awkgetline", "getline" },
{ 0, "", "" },
};
#define SIZE (LASTTOKEN - FIRSTTOKEN + 1)
const char *table[SIZE];
char *names[SIZE];
int main(int argc, char *argv[])
{
const struct xx *p;
int i, n, tok;
char c;
FILE *fp;
char buf[200], name[200], def[200];
printf("#include <stdio.h>\n");
printf("#include \"awk.h\"\n");
printf("#include \"awkgram.h\"\n\n");
for (i = SIZE; --i >= 0; )
names[i] = "";
if ((fp = fopen("awkgram.h", "r")) == NULL) {
fprintf(stderr, "maketab can't open awkgram.h!\n");
exit(1);
}
printf("static char *printname[%d] = {\n", SIZE);
i = 0;
while (fgets(buf, sizeof buf, fp) != NULL) {
n = sscanf(buf, "%1c %s %s %d", &c, def, name, &tok);
if (c != '#' || (n != 4 && strcmp(def,"define") != 0)) /* not a valid #define */
continue;
if (tok < FIRSTTOKEN || tok > LASTTOKEN) {
/* fprintf(stderr, "maketab funny token %d %s ignored\n", tok, buf); */
continue;
}
names[tok-FIRSTTOKEN] = (char *) malloc(strlen(name)+1);
strcpy(names[tok-FIRSTTOKEN], name);
printf("\t(char *) \"%s\",\t/* %d */\n", name, tok);
i++;
}
printf("};\n\n");
for (p=proc; p->token!=0; p++)
table[p->token-FIRSTTOKEN] = p->name;
printf("\nCell *(*proctab[%d])(Node **, int) = {\n", SIZE);
for (i=0; i<SIZE; i++)
if (table[i]==0)
printf("\tnullproc,\t/* %s */\n", names[i]);
else
printf("\t%s,\t/* %s */\n", table[i], names[i]);
printf("};\n\n");
printf("char *tokname(int n)\n"); /* print a tokname() function */
printf("{\n");
printf(" static char buf[100];\n\n");
printf(" if (n < FIRSTTOKEN || n > LASTTOKEN) {\n");
printf(" sprintf(buf, \"token %%d\", n);\n");
printf(" return buf;\n");
printf(" }\n");
printf(" return printname[n-FIRSTTOKEN];\n");
printf("}\n");
return 0;
}

View File

@@ -1,149 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
#include "awk.h"
NODE *
node0(type)
{
NODE *p;
char *emalloc();
p = (NODE *) emalloc(sizeof(*p) - sizeof(p));
p->n_type = type;
p->n_next = NULL;
return p;
}
NODE *
node1(type, arg0) NODE *arg0;
{
NODE *p;
char *emalloc();
p = (NODE *) emalloc(sizeof(*p));
p->n_type = type;
p->n_next = NULL;
p->n_arg[0] = (NODE *) arg0;
return p;
}
NODE *
node2(type, arg0, arg1) NODE *arg0, *arg1;
{
NODE *p;
char *emalloc();
p = (NODE *) emalloc(sizeof(*p) + sizeof(p) * 1);
p->n_type = type;
p->n_next = NULL;
p->n_arg[0] = (NODE *) arg0;
p->n_arg[1] = (NODE *) arg1;
return p;
}
NODE *
node3(type, arg0, arg1, arg2) NODE *arg0, *arg1, *arg2;
{
NODE *p;
char *emalloc();
p = (NODE *) emalloc(sizeof(*p) + sizeof(p) * 2);
p->n_type = type;
p->n_next = NULL;
p->n_arg[0] = (NODE *) arg0;
p->n_arg[1] = (NODE *) arg1;
p->n_arg[2] = (NODE *) arg2;
return p;
}
NODE *
node4(type, arg0, arg1, arg2, arg3) NODE *arg0, *arg1, *arg2, *arg3;
{
NODE *p;
char *emalloc();
p = (NODE *) emalloc(sizeof(*p) + sizeof(p) * 3);
p->n_type = type;
p->n_next = NULL;
p->n_arg[0] = (NODE *) arg0;
p->n_arg[1] = (NODE *) arg1;
p->n_arg[2] = (NODE *) arg2;
p->n_arg[3] = (NODE *) arg3;
return p;
}
CELL *
mkcell(type, sval, fval) char *sval; double fval;
{
CELL *p;
char *emalloc(), *strsave();
p = (CELL *) emalloc(sizeof(*p));
p->c_type = type;
if (sval == NULL)
p->c_sval = NULL;
else
p->c_sval = strsave(sval);
p->c_fval = fval;
return p;
}
#ifdef TMPCELL
#define MAXTMP 25
CELL tmpcell[MAXTMP];
#endif
CELL *
mktmp(type, sval, fval) char *sval; double fval;
{
register int i;
char *strsave();
#ifdef TMPCELL
for (i = 0; i < MAXTMP; i++)
if (tmpcell[i].c_type == 0) {
tmpcell[i].c_type = type | TMP;
tmpcell[i].c_sval = strsave(sval);
tmpcell[i].c_fval = fval;
return &tmpcell[i];
}
error("formula too complex", (char *) 0);
#else
return mkcell(type | TMP, sval, fval);
#endif
}
c_free(p) CELL *p;
{
if ((p != NULL) && (p->c_type & TMP)) {
#ifdef TMPCELL
p->c_type = 0;
sfree(p->c_sval);
p->c_sval = (char *)NULL;
p->c_fval = 0.0;
#else
if (p->c_sval != NULL) {
Free(p->c_sval);
p->c_sval = NULL;
}
p->c_type = 0;
Free(p);
p = NULL;
#endif
}
}

276
commands/awk/parse.c Normal file
View File

@@ -0,0 +1,276 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
#define DEBUG
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "awk.h"
#include "awkgram.h"
Node *nodealloc(int n)
{
Node *x;
x = (Node *) malloc(sizeof(Node) + (n-1)*sizeof(Node *));
if (x == NULL)
FATAL("out of space in nodealloc");
x->nnext = NULL;
x->lineno = lineno;
return(x);
}
Node *exptostat(Node *a)
{
a->ntype = NSTAT;
return(a);
}
Node *node1(int a, Node *b)
{
Node *x;
x = nodealloc(1);
x->nobj = a;
x->narg[0]=b;
return(x);
}
Node *node2(int a, Node *b, Node *c)
{
Node *x;
x = nodealloc(2);
x->nobj = a;
x->narg[0] = b;
x->narg[1] = c;
return(x);
}
Node *node3(int a, Node *b, Node *c, Node *d)
{
Node *x;
x = nodealloc(3);
x->nobj = a;
x->narg[0] = b;
x->narg[1] = c;
x->narg[2] = d;
return(x);
}
Node *node4(int a, Node *b, Node *c, Node *d, Node *e)
{
Node *x;
x = nodealloc(4);
x->nobj = a;
x->narg[0] = b;
x->narg[1] = c;
x->narg[2] = d;
x->narg[3] = e;
return(x);
}
Node *stat1(int a, Node *b)
{
Node *x;
x = node1(a,b);
x->ntype = NSTAT;
return(x);
}
Node *stat2(int a, Node *b, Node *c)
{
Node *x;
x = node2(a,b,c);
x->ntype = NSTAT;
return(x);
}
Node *stat3(int a, Node *b, Node *c, Node *d)
{
Node *x;
x = node3(a,b,c,d);
x->ntype = NSTAT;
return(x);
}
Node *stat4(int a, Node *b, Node *c, Node *d, Node *e)
{
Node *x;
x = node4(a,b,c,d,e);
x->ntype = NSTAT;
return(x);
}
Node *op1(int a, Node *b)
{
Node *x;
x = node1(a,b);
x->ntype = NEXPR;
return(x);
}
Node *op2(int a, Node *b, Node *c)
{
Node *x;
x = node2(a,b,c);
x->ntype = NEXPR;
return(x);
}
Node *op3(int a, Node *b, Node *c, Node *d)
{
Node *x;
x = node3(a,b,c,d);
x->ntype = NEXPR;
return(x);
}
Node *op4(int a, Node *b, Node *c, Node *d, Node *e)
{
Node *x;
x = node4(a,b,c,d,e);
x->ntype = NEXPR;
return(x);
}
Node *celltonode(Cell *a, int b)
{
Node *x;
a->ctype = OCELL;
a->csub = b;
x = node1(0, (Node *) a);
x->ntype = NVALUE;
return(x);
}
Node *rectonode(void) /* make $0 into a Node */
{
extern Cell *literal0;
return op1(INDIRECT, celltonode(literal0, CUNK));
}
Node *makearr(Node *p)
{
Cell *cp;
if (isvalue(p)) {
cp = (Cell *) (p->narg[0]);
if (isfcn(cp))
SYNTAX( "%s is a function, not an array", cp->nval );
else if (!isarr(cp)) {
xfree(cp->sval);
cp->sval = (char *) makesymtab(NSYMTAB);
cp->tval = ARR;
}
}
return p;
}
#define PA2NUM 50 /* max number of pat,pat patterns allowed */
int paircnt; /* number of them in use */
int pairstack[PA2NUM]; /* state of each pat,pat */
Node *pa2stat(Node *a, Node *b, Node *c) /* pat, pat {...} */
{
Node *x;
x = node4(PASTAT2, a, b, c, itonp(paircnt));
if (paircnt++ >= PA2NUM)
SYNTAX( "limited to %d pat,pat statements", PA2NUM );
x->ntype = NSTAT;
return(x);
}
Node *linkum(Node *a, Node *b)
{
Node *c;
if (errorflag) /* don't link things that are wrong */
return a;
if (a == NULL)
return(b);
else if (b == NULL)
return(a);
for (c = a; c->nnext != NULL; c = c->nnext)
;
c->nnext = b;
return(a);
}
void defn(Cell *v, Node *vl, Node *st) /* turn on FCN bit in definition, */
{ /* body of function, arglist */
Node *p;
int n;
if (isarr(v)) {
SYNTAX( "`%s' is an array name and a function name", v->nval );
return;
}
if (isarg(v->nval) != -1) {
SYNTAX( "`%s' is both function name and argument name", v->nval );
return;
}
v->tval = FCN;
v->sval = (char *) st;
n = 0; /* count arguments */
for (p = vl; p; p = p->nnext)
n++;
v->fval = n;
dprintf( ("defining func %s (%d args)\n", v->nval, n) );
}
int isarg(const char *s) /* is s in argument list for current function? */
{ /* return -1 if not, otherwise arg # */
extern Node *arglist;
Node *p = arglist;
int n;
for (n = 0; p != 0; p = p->nnext, n++)
if (strcmp(((Cell *)(p->narg[0]))->nval, s) == 0)
return n;
return -1;
}
int ptoi(void *p) /* convert pointer to integer */
{
return (int) (long) p; /* swearing that p fits, of course */
}
Node *itonp(int i) /* and vice versa */
{
return (Node *) (long) i;
}

195
commands/awk/proto.h Normal file
View File

@@ -0,0 +1,195 @@
/****************************************************************
Copyright (C) Lucent Technologies 1997
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name Lucent Technologies or any of
its entities not be used in advertising or publicity pertaining
to distribution of the software without specific, written prior
permission.
LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
****************************************************************/
extern int yywrap(void);
extern void setfname(Cell *);
extern int constnode(Node *);
extern char *strnode(Node *);
extern Node *notnull(Node *);
extern int yyparse(void);
extern int yylex(void);
extern void startreg(void);
extern int input(void);
extern void unput(int);
extern void unputstr(const char *);
extern int yylook(void);
extern int yyback(int *, int);
extern int yyinput(void);
extern fa *makedfa(const char *, int);
extern fa *mkdfa(const char *, int);
extern int makeinit(fa *, int);
extern void penter(Node *);
extern void freetr(Node *);
extern int hexstr(char **);
extern int quoted(char **);
extern char *cclenter(const char *);
extern void overflo(const char *);
extern void cfoll(fa *, Node *);
extern int first(const Node *);
extern void follow(Node *);
extern int member(int, const char *);
extern int match(fa *, const char *);
extern int pmatch(fa *, const char *);
extern int nematch(fa *, const char *);
extern Node *reparse(const char *);
extern Node *regexp(void);
extern Node *primary(void);
extern Node *concat(Node *);
extern Node *alt(Node *);
extern Node *unary(Node *);
extern int relex(void);
extern int cgoto(fa *, int, int);
extern void freefa(fa *);
extern int pgetc(void);
extern char *cursource(void);
extern Node *nodealloc(int);
extern Node *exptostat(Node *);
extern Node *node1(int, Node *);
extern Node *node2(int, Node *, Node *);
extern Node *node3(int, Node *, Node *, Node *);
extern Node *node4(int, Node *, Node *, Node *, Node *);
extern Node *stat3(int, Node *, Node *, Node *);
extern Node *op2(int, Node *, Node *);
extern Node *op1(int, Node *);
extern Node *stat1(int, Node *);
extern Node *op3(int, Node *, Node *, Node *);
extern Node *op4(int, Node *, Node *, Node *, Node *);
extern Node *stat2(int, Node *, Node *);
extern Node *stat4(int, Node *, Node *, Node *, Node *);
extern Node *celltonode(Cell *, int);
extern Node *rectonode(void);
extern Node *makearr(Node *);
extern Node *pa2stat(Node *, Node *, Node *);
extern Node *linkum(Node *, Node *);
extern void defn(Cell *, Node *, Node *);
extern int isarg(const char *);
extern char *tokname(int);
extern Cell *(*proctab[])(Node **, int);
extern int ptoi(void *);
extern Node *itonp(int);
extern void syminit(void);
extern void arginit(int, char **);
extern void envinit(char **);
extern Array *makesymtab(int);
extern void freesymtab(const Cell *);
extern void freeelem(const Cell *, const char *);
extern Cell *setsymtab(const char *, const char *, double, unsigned int, Array *);
extern int hash(const char *, int);
extern void rehash(Array *);
extern Cell *lookup(const char *, const Array *);
extern double setfval(Cell *, double);
extern void funnyvar(Cell *, const char *);
extern char *setsval(Cell *, const char *);
extern double getfval(Cell *);
extern char *getsval(Cell *);
extern char *getpssval(Cell *); /* for print */
extern char *tostring(const char *);
extern char *qstring(const char *, int);
extern void recinit(unsigned int);
extern void initgetrec(void);
extern void makefields(int, int);
extern void growfldtab(int n);
extern int getrec(char **, int *, int);
extern void nextfile(void);
extern int readrec(char **buf, int *bufsize, FILE *inf);
extern char *getargv(int);
extern void setclvar(char *);
extern void fldbld(void);
extern void cleanfld(int, int);
extern void newfld(int);
extern int refldbld(const char *, const char *);
extern void recbld(void);
extern Cell *fieldadr(int);
extern void yyerror(const char *);
extern void fpecatch(int);
extern void bracecheck(void);
extern void bcheck2(int, int, int);
extern void SYNTAX(const char *, ...);
extern void FATAL(const char *, ...);
extern void WARNING(const char *, ...);
extern void error(void);
extern void eprint(void);
extern void bclass(int);
extern double errcheck(double, const char *);
extern int isclvar(const char *);
extern int is_number(const char *);
extern int adjbuf(char **pb, int *sz, int min, int q, char **pbp, const char *what);
extern void run(Node *);
extern Cell *execute(Node *);
extern Cell *program(Node **, int);
extern Cell *call(Node **, int);
extern Cell *copycell(Cell *);
extern Cell *arg(Node **, int);
extern Cell *jump(Node **, int);
extern Cell *awkgetline(Node **, int);
extern Cell *getnf(Node **, int);
extern Cell *array(Node **, int);
extern Cell *awkdelete(Node **, int);
extern Cell *intest(Node **, int);
extern Cell *matchop(Node **, int);
extern Cell *boolop(Node **, int);
extern Cell *relop(Node **, int);
extern void tfree(Cell *);
extern Cell *gettemp(void);
extern Cell *field(Node **, int);
extern Cell *indirect(Node **, int);
extern Cell *substr(Node **, int);
extern Cell *sindex(Node **, int);
extern int format(char **, int *, const char *, Node *);
extern Cell *awksprintf(Node **, int);
extern Cell *awkprintf(Node **, int);
extern Cell *arith(Node **, int);
extern double ipow(double, int);
extern Cell *incrdecr(Node **, int);
extern Cell *assign(Node **, int);
extern Cell *cat(Node **, int);
extern Cell *pastat(Node **, int);
extern Cell *dopa2(Node **, int);
extern Cell *split(Node **, int);
extern Cell *condexpr(Node **, int);
extern Cell *ifstat(Node **, int);
extern Cell *whilestat(Node **, int);
extern Cell *dostat(Node **, int);
extern Cell *forstat(Node **, int);
extern Cell *instat(Node **, int);
extern Cell *bltin(Node **, int);
extern Cell *printstat(Node **, int);
extern Cell *nullproc(Node **, int);
extern FILE *redirect(int, Node *);
extern FILE *openfile(int, const char *);
extern const char *filename(FILE *);
extern Cell *closefile(Node **, int);
extern void closeall(void);
extern Cell *sub(Node **, int);
extern Cell *gsub(Node **, int);
extern FILE *popen(const char *, const char *);
extern int pclose(FILE *);

View File

@@ -1,627 +0,0 @@
/*
* a small awk clone
*
* (C) 1989 Saeko Hirabauashi & Kouichi Hirabayashi
*
* Absolutely no warranty. Use this software with your own risk.
*
* Permission to use, copy, modify and distribute this software for any
* purpose and without fee is hereby granted, provided that the above
* copyright and disclaimer notice.
*
* This program was written to fit into 64K+64K memory of the Minix 1.2.
*/
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef DOS
#include <process.h>
#endif
#include "awk.h"
#include "regexp.h"
#define MAXFLD 100
extern char **FS, **RS, **OFS, **ORS, **FILENAME;
extern double *NF, *NR;
extern double *FNR;
extern double *ARGC;
extern SYMBOL *argtab[];
extern CELL *getvar();
char *strsave(), *strcpy(), *getsval(), *jStrchr(), *strchr();
double getfval(), atof();
CELL *mkcell(), *mktmp(), *execute(), *patexec();
FILE *efopen();
extern CELL truecell, falsecell;
extern int pateval;
int infileno = 1;
FILE *ifp;
char record[BUFSIZ];
CELL *field[MAXFLD];
char *fs_str;
regexp *fs_pat;
CELL *
Getline(p) NODE *p;
{
CELL *u;
char *fnam, *s, str[BUFSIZ];
int i;
FILE *fp, *getfp();
if ((int) p->n_arg[0]) /* read into var */
s = str;
else
s = NULL;
if ((int) p->n_arg[1]) { /* file name */
u = execute(p->n_arg[1]);
fnam = getsval(u);
fp = getfp(fnam, (int) p->n_arg[2]);
c_free(u);
i = get1rec(s, fp);
}
else
i = Getrec(s);
if (s == str) {
u = execute(p->n_arg[0]);
setsval(u, str);
}
return mktmp(NUM, NULL, (double) i);
}
static
get1rec(buf, fp) char *buf; FILE *fp;
{
register int c;
register char rs, *s;
int mflg;
if (buf == NULL)
buf = record;
if ((rs = **RS) == '\0') { /* multi line record */
mflg = 1;
rs = '\n';
}
else
mflg = 0;
if (feof(fp) || (c = getc(fp)) == EOF)
return 0;
for (s = buf; ; ) {
for ( ; c != rs && c != EOF; c = getc(fp)) {
if (isKanji(c)) {
*s++ = c; c = getc(fp);
}
*s++ = c;
}
if (mflg) {
if ((c = getc(fp)) == '\n' || c == EOF)
break;
*s++ = '\n';
}
else
break;
}
*s = '\0';
#if 1
if (buf == record) {
#else
if (buf == record && c != EOF) {
#endif
mkfld(record, *FS, field);
(*NR)++;
(*FNR)++;
}
return s > buf || c != EOF ? 1 : 0;
}
Getrec(s) char *s;
{
CELL *u;
char *file, str[8];
while (ifp == stdin || infileno < (int)*ARGC) {
if (ifp == NULL) {
*FNR = 0.0;
if (infileno == (int)*ARGC)
break;
sprintf(str, "%d", infileno);
u = getvar(str, argtab);
file = getsval(u);
if (strchr(file, '=') != NULL) {
setvar(file);
infileno++;
continue;
}
else if (strcmp(file, "") == 0) {
/*
if (infileno == (int)*ARGC - 1)
ifp = stdin;
*/
infileno++;
continue;
}
else {
if (strcmp(file, "-") == 0)
ifp = stdin;
else
ifp = efopen(file, "r");
*FILENAME = file;
}
}
if (get1rec(s, ifp))
return 1;
else {
if (ifp != stdin)
fclose(ifp);
ifp = NULL;
infileno++;
}
}
ifp = stdin; /* for further "getline" */
*FILENAME = "-";
return 0; /* EOF */
}
mkfld(rec, sep, fld) char *rec, *sep; CELL *fld[];
{
char *s, *t;
char str[BUFSIZ];
int i, j, n;
int skip = 0;
if (strlen(sep) > 1)
return r_mkfld(rec, sep, fld);
if (*sep == ' ' || *sep == '\0') {
sep = " \t\n"; skip++;
}
for (i = 1, n = (int) *NF; i <= n; i++) {
sfree(fld[i]->c_sval);
sfree(fld[i]);
fld[i] = NULL;
}
for (i = 0, s = rec; ; ) {
t = str;
if (skip) {
while (*s && strchr(" \t\n", *s))
s++;
if (*s == '\0')
break;
}
while (*s && !jStrchr(sep, *s)) {
if (isKanji(*s))
*t++ = *s++;
*t++ = *s++;
}
*t = '\0';
if (isnum(str))
fld[++i] = mkcell(FLD|STR|NUM, str, atof(str));
else
fld[++i] = mkcell(FLD|STR, str, 0.0);
if (*s)
s++;
else
break;
}
*NF = (double) i;
return i;
}
static
r_mkfld(rec, sep, fld) char *rec, *sep; CELL *fld[];
{
char *s, *t;
char str[BUFSIZ];
int i, n;
regexp *mkpat();
extern int r_start, r_length;
if (strcmp(*FS, fs_str) != 0) {
sfree(fs_str); sfree(fs_pat);
fs_str = strsave(*FS);
fs_pat = mkpat(fs_str);
}
for (i = 1, n = (int) *NF; i <= n; i++) {
sfree(fld[i]->c_sval);
sfree(fld[i]);
fld[i] = NULL;
}
for (i = 0, s = rec, t = str; *s; ) {
if (match(fs_pat, s)) {
for (n = r_start; --n > 0; )
*t++ = *s++;
}
else {
while (*s)
*t++ = *s++;
}
*t = '\0';
t = str;
fld[++i] = mkcell(FLD|STR, str, 0.0);
if (*s)
s += r_length;
}
*NF = (double) i;
return i;
}
mkrec(u) CELL *u;
{
register char *s, *t;
register int i, j;
for (j = (int)*NF, i = 1; i <= j; i++)
if (field[i] == u)
break;
if (i > j) {
for ( ; i < MAXFLD; i++)
if (field[i] == u)
break;
if (i == MAXFLD)
error("too many field (%d)", i);
*NF = (double)i;
}
for (t = record, i = 1, j = (int) *NF; i <= j; i++) {
if (i > 1)
*t++ = **OFS;
for (s = getsval(field[i]); *s; )
*t++ = *s++;
}
*t++ = '\0';
}
CELL *
Field(p) NODE *p;
{
CELL *u;
int i, j;
u = execute(p->n_arg[0]);
i = (int) getfval(u);
c_free(u);
j = (int)*NF;
if (i > j)
for (++j; j <= i; j++) {
if (field[j] == NULL)
field[j] = mkcell(FLD|STR, "", 0.0);
}
return field[i];
}
CELL *
P1stat(p) NODE *p;
{
CELL *u;
double x;
pateval++;
u = execute(p->n_arg[0]);
pateval = 0;
x = getfval(u);
c_free(u);
if (x != 0.0)
u = execute(p->n_arg[1]);
else
u = &truecell;
return u;
}
CELL *
P2stat(p) NODE *p;
{
static stat = 0;
CELL *u, *v;
double x;
switch (stat) {
case 0:
pateval++;
u = execute(p->n_arg[0]);
pateval = 0;
x = getfval(u);
c_free(u);
if (x == 0.0) {
u = &truecell; break;
}
else
stat++;
/* fall through */
case 1:
u = execute(p->n_arg[2]);
c_free(u);
pateval++;
u = execute(p->n_arg[1]);
pateval = 0;
x = getfval(u);
if (x != 0.0)
stat = 0;
break;
default:
u = &truecell;
break;
}
return u;
}
CELL *
Print0()
{
/*
int i, j;
char *s, str[BUFSIZ];
for (*str = '\0', i = 1, j = (int) *NF; i <= j; i++) {
if (i > 1)
strcat(str, *OFS);
s = getsval(field[i]);
strcat(str, s);
}
strcat(str, *ORS);
fputs(str, stdout);
*/
fprintf(stdout, "%s%s", record, *ORS);
return &truecell;
}
char *
format(t, p) char *t; NODE *p;
{
CELL *u, *v;
char *r, *s, *s0, fmt[BUFSIZ];
double x;
int i;
u = execute(p->n_arg[2]);
s = s0 = getsval(u);
/*
printf("fmt(%s)\n", s);
*/
for (i = 3; *s; s++) {
if (isKanji(*s)) {
*t++ = *s++; *t++ = *s; continue;
}
if (*s != '%') {
*t++ = *s; continue;
}
else if (*(s + 1) == '%') {
*t++ = *s++; continue;
}
for (r = fmt, *r++ = *s++; *r++ = *s; s++) {
if (strchr("%cdefgosux", *s))
break;
}
*r = '\0';
if (p->n_arg[i] == NULL)
error("not enough args in printf(%s)", s0);
v = execute(p->n_arg[i++]);
if (*s == 's')
r = getsval(v);
else
x = getfval(v);
/*
printf("val(%d)(%s)\n", v->c_type, v->c_sval);
*/
switch (*s) {
case 'c':
sprintf(t, fmt, (int) x);
break;
case 'd':
if (*(s - 1) != 'l') {
*--r = 'l'; *++r = 'd'; *++r = '\0';
}
sprintf(t, fmt, (long) x);
break;
case 'e': case 'f': case 'g':
sprintf(t, fmt, x);
break;
case 'o': case 'u': case 'x':
if (*(s - 1) == 'l')
sprintf(t, fmt, (long) x);
else
sprintf(t, fmt, (int) x);
break;
case 's':
/*r = getsval(v);*/
sprintf(t, fmt, r);
break;
default:
strcpy(t, fmt);
break;
}
c_free(v);
t += strlen(t);
}
c_free(u);
*t = '\0';
}
#define MAXFILE 10
struct {
char *f_name; /* file name */
FILE *f_fp;
int f_type;
} filetab[MAXFILE];
FILE *
getfp(file, type) char *file;
{
register int i;
register char *name, *mode;
char *awktmp();
FILE *fp, *efopen(), *epopen();
for (i = 0; i < MAXFILE; i++)
if (filetab[i].f_name && strcmp(filetab[i].f_name, file) == 0)
return filetab[i].f_fp;
for (i = 0; i < MAXFILE; i++)
if (!filetab[i].f_fp)
break;
if (i == MAXFILE)
error("too many files to open");
name = file;
switch (type) {
case R_OUT: mode = "w"; break;
case R_APD: mode = "a"; break;
case R_POUT:
#ifdef DOS
name = awktmp(i); mode = "w"; /* MS-DOS */
#else
fp = epopen(file, "w");
goto g1;
#endif
break;
case R_IN: mode = "r"; break;
case R_PIN:
#ifdef DOS
{
int savefd, fd, result;
name = awktmp(i);
if ((fd = open(name,
O_WRONLY|O_TEXT|O_CREAT|O_TRUNC,S_IREAD|S_IWRITE)) == -1)
error("can't open %s", name);
savefd = dup(1); dup2(fd, 1); close(fd);
if ((result =
system(file)) == -1)
error("can't exec %s", file);
dup2(savefd, 1); close(savefd); close(fd);
mode = "r";
}
#else
fp = epopen(file,"r");
goto g1;
#endif
break;
}
fp = efopen(name, mode);
g1:
filetab[i].f_name = strsave(file);
filetab[i].f_type = type;
filetab[i].f_fp = fp;
return fp;
}
closeall()
{
register int i;
for (i = 0; i < MAXFILE; i++)
close1(i);
}
CELL *
Close(s) char *s;
{
register int i;
for (i = 0; i < MAXFILE; i++)
if (strcmp(s, filetab[i].f_name) == 0) {
close1(i);
break;
}
i = (i == MAXFILE) ? 0 : 1;
return mktmp(NUM, NULL, (double) i);
}
static
close1(i)
{
int fd, result, savefd;
char *awktmp();
if (filetab[i].f_fp == NULL)
return;
switch (filetab[i].f_type) {
case R_PIN:
#ifdef DOS
fclose(filetab[i].f_fp);
unlink(awktmp(i));
#else
pclose(filetab[i].f_fp);
#endif
break;
case R_IN: case R_OUT: case R_APD:
fclose(filetab[i].f_fp);
break;
case R_POUT:
#ifdef DOS
fclose(filetab[i].f_fp);
if ((fd = open(awktmp(i), O_RDONLY)) == NULL)
error("can't open %s", awktmp(i));
savefd = dup(0);
dup2(fd, 0);
close(fd);
if ((result =
system(filetab[i].f_name)) == -1)
/*
spawnl(P_WAIT, "/usr/bin/sh", "sh", "-c", filetab[i].f_name, (char *) 0)) == -1)
fprintf(stderr, "can't spawn /bin/sh\n");
*/
error("can't exec %s", filetab[i].f_name);
dup2(savefd, 0);
close(savefd);
unlink(awktmp(i));
#else
pclose(filetab[i].f_fp);
#endif
break;
}
sfree(filetab[i].f_name);
filetab[i].f_type = 0;
filetab[i].f_name = NULL;
filetab[i].f_fp = NULL;
}
#ifndef DOS
FILE *
epopen(file, mod) char *file, *mod;
{
FILE *fp, *popen();
if ((fp = popen(file, mod)) == NULL)
error("can't poen %s", file);
return fp;
}
#endif
static char *
awktmp(i)
{
static char str[16];
sprintf(str, "awk000%02d.tmp", i);
return str;
}
Index(s, t) char *s, *t;
{
register char *u, *v;
register int i;
for (i = 1; *s; s++, i++) {
for (u = s, v = t; *v; u++, v++) {
if (isKanji(*v)) {
if (*u != *v)
break;
u++; v++;
}
if (*u != *v)
break;
}
if (*v == '\0')
return i;
if (isKanji(*s))
s++;
}
return 0;
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More