philburk / pforth

Portable Forth in C
BSD Zero Clause License
602 stars 99 forks source link

issuing a '?' at the forth prompt crashes interpreter #154

Closed reeskm closed 1 year ago

reeskm commented 1 year ago

As a total Forth n00b, I managed to build pforth 2.0.1 release on Solaris 11.3 SPARC. Not knowing what to do at the prompt, I typed '?' for help. I've been able to crash both pforth and pforth_standalone, resulting in a SIGV and core dump. Here's the output of 'dbx':

user@t3:~/src/pforth-2.0.1/platforms/unix$ dbx ./pforth_standalone
For information about new features see `help changes'
To remove this message, put `dbxenv suppress_startup_message 8.2' in your .dbxrc
Reading pforth_standalone
Reading ld.so.1
Reading libm.so.2
Reading libc.so.1
(dbx) run
Running: pforth_standalone 
(process id 15427)
PForth V2.0.0, BE/32, built Oct  9 2023 01:31:07 (static)

? signal SEGV (no mapping at the fault address) in pfCatch at line 962 in file "pf_inner.c"
  962               TOS = *((cell_t *)TOS);
philburk commented 1 year ago

Welcome to the exciting world of Forth. It can be a bit like juggling chain-saws. Things can go wrong.

In Forth, a ? will read an address off the stack and then fetch from the address. But there was no address on the stack. So you fetched from an undefined address. Boom.

A C equivalent might be:

*((char *)lrand48());

As you can see, Forth is more concise.

You might enjoy this Forth tutorial: https://www.softsynth.com/pforth/pf_tut.php

reeskm commented 1 year ago

Just curious why this would not be trapped by the interpreter and a general error issued, instead of a segfault? Is this by design or deliberately not implemented?

philburk commented 1 year ago

By design. Forth is often used as an embedded language where you need to be able to access any address when there is no OS. So Forth typically does not validate addresses.

reeskm commented 1 year ago

That makes a lot of sense Phil! Thanks for your awesome support.