1
0
mirror of https://github.com/elua/elua.git synced 2025-01-08 20:56:17 +08:00

Merge branch 'shellfs'

This commit is contained in:
Bogdan Marinescu 2013-01-22 01:10:31 +02:00
commit 16b5967b64
34 changed files with 2603 additions and 975 deletions

3
.gitignore vendored
View File

@ -19,3 +19,6 @@ inc/git_version.h
*~
*.*~
luac.cross*
sdcard.img
core

View File

@ -385,8 +385,13 @@ if not GetOption( 'help' ):
# Additional libraries
local_libs = ''
# Shell files
shell_files = """ src/shell/shell.c src/shell/shell_adv_cp_mv.c src/shell/shell_adv_rm.c src/shell/shell_cat.c src/shell/shell_help.c
src/shell/shell_ls.c src/shell/shell_lua.c src/shell/shell_mkdir.c src/shell/shell_recv.c src/shell/shell_ver.c
src/shell/shell_wofmt.c """
# Application files
app_files = """ src/main.c src/romfs.c src/semifs.c src/xmodem.c src/shell.c src/term.c src/common.c src/common_tmr.c src/buf.c src/elua_adc.c src/dlmalloc.c
app_files = """ src/main.c src/romfs.c src/semifs.c src/xmodem.c src/term.c src/common.c src/common_tmr.c src/buf.c src/elua_adc.c src/dlmalloc.c
src/salloc.c src/luarpc_elua_uart.c src/elua_int.c src/linenoise.c src/common_uart.c src/eluarpc.c """
# Newlib related files
@ -421,7 +426,7 @@ if not GetOption( 'help' ):
execfile( "src/platform/%s/conf.py" % platform )
# Complete file list
source_files = Split( app_files + specific_files + newlib_files + uip_files + lua_full_files + module_files + rfs_files )
source_files = Split( app_files + specific_files + newlib_files + uip_files + lua_full_files + module_files + rfs_files + shell_files )
comp = conf.Finish()

View File

@ -130,7 +130,9 @@ local menu =
{ "Linenoise", "linenoise.html" },
{ "Cross-compiling", "using.html#cross" },
{ "LuaRPC", "using.html#rpc" },
{ "The serial multiplexer", "sermux.html" }
{ "The serial multiplexer", "sermux.html" },
{ nil, "simple_shell.html", nil, "Simple shell" },
{ nil, "advanced_shell.html", nil, "Advanced shell" },
},
},
{ { "Code examples", "Exemplos de Código" }, "examples.html" },

217
doc/en/advanced_shell.txt Normal file
View File

@ -0,0 +1,217 @@
// $$HEADER$$
The advanced shell
------------------
The advanced shell is an extension to the link:simple_shell.html[simple shell]. It adds some new
features to the simple shell:
- file masks
- more file operations (rename and move)
- recursive operations (for example recursive copies of directories)
A detailed description of the advanced shell commands and the structure of the file masks are given below.
[width="90%", cols="^, ^, ^, ^", grid="none"]
|==============================================================================================
| link:#cmd_help[help] | link:#cmd_ver[ver] | link:#cmd_recv[recv] | link:#cmd_lua[lua]
| link:#cmd_ls[ls] | link:#cmd_ls[dir] | link:#cmd_cat[cat] | link:#cmd_cat[type]
| link:#cmd_cp[cp] | link:#cmd_exit[exit] | link:#cmd_wofmt[wofmt] | link:#cmd_mkdir[mkdir]
| link:#cmd_rm[rm] | link:#cmd_mv[mv] | |
|==============================================================================================
File masks
----------
WARNING: Read this section carefully, eLua's idea of file masks ia different from what you might have
encountered in various operating systems.
The advanced shell supports file masks for various file operations (for example _cp_). A file mask can
match zero, one or more files. In order to match more than one file, it uses two special characters:
- _?_: this matches *exactly one character*
- _*_: this matches *zero or more characters*, non-greedy (it stops at the first non-special character).
Any *?* characters immediately following the *** will be ignored.
This is probably best understood by some examples. Given the filenames below:
-----
a
ab
abcd
abba
aaba
aaab
bbbcd
dccdb
-----
this is how various file masks work:
- _*_ : all the files above
- _a*_ : a, ab, abcd, abba, aaba, aaab
- _a*b_ : ab, aaab
- _a*?b_ : ab, aaab
- _a*b?_ : aaba
- _*b*_ : ab, abcd, abba, aaba, aaab, bbbcd, dccdb
- _????_ : abcd, abba, aaba, aaab
- _a?*b_ : aaab
[[cmd_help]]
help
~~~~
By itself, it shows a list of all shell commands. If a shell command is given after *help*, it displays
detailed information about the given command. Examples:
------
# help
# help ls
------
[[cmd_ver]]
ver
~~~
Print the version of the eLua image installed on the board. If the image is not an official one, an
abbreviation of the git SHA1 revision used for building the image will be shown in the version number.
[[cmd_recv]]
recv
~~~~
Allows you to receive from the PC running the terminal emulator program, a Lua file (either source or compiled
bytecode) via XMODEM and either execute it on your board or save it to a file. To use this feature, your eLua
target image must be built with support for XMODEM (see link:building.html[building] for details). Also, your
terminal emulation program must support sending files via the XMODEM protocol. Both XMODEM with checksum
and XMODEM with CRC are supported, but only XMODEM with 128 byte packets is allowed (XMODEM with 1K packets won't work).
To start the transfer, enter *recv* at the shell prompt. eLua will respond with "Waiting for file ...". At this point
you can send the file to the eLua board via XMODEM. eLua will receive and execute the file. Don't worry when you
see 'C' characters suddenly appearing on your terminal after you enter this command, this is how the XMODEM transfer
is initiated. If you want to save the data to a file instead of executing it, use *recv <filename>* instead.
Since XMODEM is a protocol that uses serial lines, this command is not available if you're running your console
over TCP/IP instead of a serial link. If you'd like to send compiled bytecode to eLua instead of source code,
please check link:using.html#cross[this section] first. Examples:
--------------------
# recv
# recv /mmc/temp.lua
--------------------
[[cmd_lua]]
lua
~~~
This command allows you to start the Lua interpreter, optionally passing command line parameters, just as you would do
from a desktop machine. There are some differences from the desktop Lua version in command line parsing:
- the command line can't be longer than 50 chars
- character escaping is not implemented. For example, the next command won't work because of the ' (simple quotes) escape sequences:
eLua# lua -e 'print(\'Hello, World!\')' -i
Press CTRL+Z to exit Lua
lua: (command line):1: unexpected symbol near ''
+
However, if you use both '' (simple quotes) and "" (double quotes) for string quoting, it will work:
eLua# lua -e 'print("Hello, World")' -i
Press CTRL+Z to exit Lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
Hello, World
- if you want to execute a file from the link:"arch_romfs.html"[ROM file system] (or from another file system), remember to prefix it
with _/rom_. For example, to execute *hello.lua*, do this:
eLua# lua /rom/hello.lua
[[cmd_ls]]
ls or dir
~~~~~~~~~
Shows a list of all the files in the file systems used by eLua, as well as their size and the total size of the given file system.
Syntax:
------------------
# ls [<path>] [-R]
------------------
If *path* is given, the listing is restricted to the file mask specified by *path*. If *-R* is given, *ls* will recurse through all
the directories in *path* or through all the directories in all the available filesystems if *path* is not specified.
[[cmd_cat]]
cat or type
~~~~~~~~~~~
Prints the content of (usually text) files on the console. Examples:
-------------------------------------
eLua# cat /rom/test.lua /mmc/temp.txt
eLua# cat /mmc/autorun.lua
-------------------------------------
[[cmd_cp]]
cp
~~
Copies a file or a directory. This command can be used to copy data between different file systems (for example between the MMC file
system and the RFS file system). Syntax:
-------------------------------------
# cp <src> <dest> [-R] [-f] [-c] [-s]
-------------------------------------
- *<src>* is the source file or directory. It can be a file mask.
- *<dest>* is the destination. If it does not exist, it will be created. It can't be a file mask.
- *-R*: (optional) copy files and directories recursively.
- *-f*: (optional) force file overwrite on *<dest>*. The default is to ask for confirmation before overriding.
- *-c*: (optional) confirm each file copy operation.
- *-s*: (optional) run the command normally, but don't actually copy anything. Useful to check the outcome of the operation before
actually executing it.
[[cmd_exit]]
exit
~~~~
Exits the shell. This only makes sense if eLua is compiled with terminal support over TCP/IP , as it closes the telnet session to the
eLua board. Otherwise it just terminates the shell and blocks forever until you reset your board.
[[cmd_wofmt]]
wofmt
~~~~~
"Formats" the link:arch_wofs.html[WOFS file system], erasing its current contents. The user is asked to confirm this operation.
[[cmd_mkdir]]
mkdir
~~~~~
Creates a new directory. The filesystem must have directory support in order fir this to work. Example:
----------------
# mkdir /mmc/dir
----------------
[[cmd_rm]]
rm
~~
Removes files and directories. Syntax:
------------------------------
# rm <filemask> [-R] [-c] [-s]
------------------------------
- *<filemask>*: specify the file(s) or directories that are to be removed
- *-R*: (optional) remove directories recursively. Use this flag to remove a directory with *rm*
- *-c*: (optional) confirm each remove operation.
- *-s*: (optional) run the command normally, but don't actually remove anything. Useful to check the outcome of the operation before
actually executing it.
[[cmd_mv]]
mv
~~
Moves a file or a directory. This command can be used to move data between different file systems (for example between the MMC file
system and the RFS file system). Syntax:
-------------------------------------
# mv <src> <dest> [-R] [-f] [-c] [-s]
-------------------------------------
- *<src>* is the source file or directory. It can be a file mask.
- *<dest>* is the destination. If it does not exist, it will be created. It can't be a file mask.
- *-R*: (optional) move files and directories recursively.
- *-f*: (optional) force file overwrite on *<dest>*. The default is to ask for confirmation before overriding.
- *-c*: (optional) confirm each file move operation.
- *-s*: (optional) run the command normally, but don't actually move anything. Useful to check the outcome of the operation before
actually executing it.
// $$FOOTER$$

127
doc/en/simple_shell.txt Normal file
View File

@ -0,0 +1,127 @@
// $$HEADER$$
The simple shell
----------------
The simple shell is a good compromise between functionality and the size of the eLua firmware image.
A detailed description of the shell commands is given below.
[width="90%", cols="^, ^, ^, ^", grid="none"]
|=============
| link:#cmd_help[help] | link:#cmd_ver[ver] | link:#cmd_recv[recv] | link:#cmd_lua[lua]
| link:#cmd_ls[ls] | link:#cmd_ls[dir] | link:#cmd_cat[cat] | link:#cmd_cat[type]
| link:#cmd_cp[cp] | link:#cmd_exit[exit] | link:#cmd_wofmt[wofmt] | link:#cmd_mkdir[mkdir]
|=============
[[cmd_help]]
help
~~~~
By itself, it shows a list of all shell commands. If a shell command is given after *help*, it displays
detailed information about the given command. Examples:
------
# help
# help ls
------
[[cmd_ver]]
ver
~~~
Print the version of the eLua image installed on the board. If the image is not an official one, an
abbreviation of the git SHA1 revision used for building the image will be shown in the version number.
[[cmd_recv]]
recv
~~~~
Allows you to receive from the PC running the terminal emulator program, a Lua file (either source or compiled
bytecode) via XMODEM and either execute it on your board or save it to a file. To use this feature, your eLua
target image must be built with support for XMODEM (see link:building.html[building] for details). Also, your
terminal emulation program must support sending files via the XMODEM protocol. Both XMODEM with checksum
and XMODEM with CRC are supported, but only XMODEM with 128 byte packets is allowed (XMODEM with 1K packets won't work).
To start the transfer, enter *recv* at the shell prompt. eLua will respond with "Waiting for file ...". At this point
you can send the file to the eLua board via XMODEM. eLua will receive and execute the file. Don't worry when you
see 'C' characters suddenly appearing on your terminal after you enter this command, this is how the XMODEM transfer
is initiated. If you want to save the data to a file instead of executing it, use *recv <filename>* instead.
Since XMODEM is a protocol that uses serial lines, this command is not available if you're running your console
over TCP/IP instead of a serial link. If you'd like to send compiled bytecode to eLua instead of source code,
please check link:using.html#cross[this section] first. Examples:
--------------------
$ recv
$ recv /mmc/temp.lua
--------------------
[[cmd_lua]]
lua
~~~
This command allows you to start the Lua interpreter, optionally passing command line parameters, just as you would do
from a desktop machine. There are some differences from the desktop Lua version in command line parsing:
- the command line can't be longer than 50 chars
- character escaping is not implemented. For example, the next command won't work because of the ' (simple quotes) escape sequences:
eLua# lua -e 'print(\'Hello, World!\')' -i
Press CTRL+Z to exit Lua
lua: (command line):1: unexpected symbol near ''
+
However, if you use both '' (simple quotes) and "" (double quotes) for string quoting, it will work:
eLua# lua -e 'print("Hello, World")' -i
Press CTRL+Z to exit Lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
Hello, World
- if you want to execute a file from the link:"arch_romfs.html"[ROM file system] (or from another file system), remember to prefix it
with _/rom_. For example, to execute *hello.lua*, do this:
eLua# lua /rom/hello.lua
[[cmd_ls]]
ls or dir
~~~~~~~~~
Shows a list of all the files in the file systems used by eLua, as well as their size and the total size of the given file system.
[[cmd_cat]]
cat or type
~~~~~~~~~~~
Prints the content of (usually text) files on the console. Examples:
-------------------------------------
eLua# cat /rom/test.lua /mmc/temp.txt
eLua# cat /mmc/autorun.lua
-------------------------------------
[[cmd_cp]]
cp
~~
Copies a file to another file. This command can be used to copy files between different file systems (for example between the MMC file
system and the RFS file system). The first argument is the source, the second one is the destination. Example:
------------------------------------
eLua# cp /rom/data.bin /rfs/data.bin
------------------------------------
Note that both *source* and *destination* must be file names (for example, _cp /rom/data.bin /rfs_ will not work, since _/rfs_ is not
a valid file name).
[[cmd_exit]]
exit
~~~~
Exits the shell. This only makes sense if eLua is compiled with terminal support over TCP/IP , as it closes the telnet session to the
eLua board. Otherwise it just terminates the shell and blocks forever until you reset your board.
[[cmd_wofmt]]
wofmt
~~~~~
"Formats" the link:arch_wofs.html[WOFS file system], erasing its current contents. The user is asked to confirm this operation.
[[cmd_mkdir]]
mkdir
~~~~~
Creates a new directory. The filesystem must have directory support in order fir this to work. Example:
--------------------
elua# mkdir /mmc/dir
--------------------
// $$FOOTER$$

View File

@ -1,358 +0,0 @@
$$HEADER$$
<h3>Using eLua</h3>
<p>So, you already <a href="building.html">built</a> and <a href="installing.html">installed</a>
<b>eLua</b>, now it is time to (finally) have some fun with it :)
You can compile <b>eLua</b> with either console over UART (the default and by far the most popular)
or console over TCP/IP (still experimental, but working quite well). See <a href="building.html">building eLua</a> for details on how to select
the second option above.</p>
<a name="uart"><h3>Using eLua over serial connections</h3></a>
<p>All you need to use <b>eLua</b> over a serial connection is your <b>eLua</b>
board connected to a PC running a terminal emulator program.<br>If
you're using Windows, we recommend <a href="http://www.ayera.com/teraterm/">TeraTerm</a>.
It's a freeware, it's very powerful and also easy to use. The native Hyper Terminal progam can do
too, as well as any most other terminal emulator programs.<br>On
Linux,
you'll probably be stucked with minicom. It is not exactly intuitive
and it runs in text mode, but it's still very powerful. If you
google for "minicom tutorial" you'll get the hang of it in no time. You
can try any other terminal emulator, as long as you set it up
properly and it gives you the option of transferring files
via XMODEM, which is what <b>eLua</b> uses at the moment. These are the main
settings you need to look at:</p>
<ul><li>port setup: 115200 baud (38400 for <a href="installing_str7.html">STR7)</a>, 8N1(8 data bits, no parity, one stop bit). </li><li>hardware flow control: none</li><li>newline handling: "CR" on receive, "CR+LF" on send (some terminal programs won't give you a choice here). </li></ul>
<p>Also, depending on the type of your board, you'll need some way to
connect the board to a serial port on your PC or to USB if you're
using an USB to serial converter. For example (as already explained <a href="installing_lm3s.html">here)</a>,
the USB port on the LM3Sxxxx boards is dual, so you can use it as an USB
to serial converter after downloading your firmware, thus you don't
need any other type of connection. The same is true for the
STR9-Comstick board. On the other hand, for the SAM7-EX256 board you'll
need to connect a serial cable to the "RS232" connector, provided that
the jumpers are already set as explained <a href="installing_at91sam7x.html">here</a> and on the MOD711 you will need to add an RS232 converter chip.
There's no universal rule here, it all depends on your board. Feel free to
ask if you need help in our <a href="https://lists.berlios.de/mailman/listinfo/elua-dev">discussion
list</a>
</p>
<a name="tcpip"><h3>Using eLua over TCP/IP connections</h3></a>
<p>Things are even easier if you decide to enable console over TCP/IP:</p>
<ul>
<li>make sure you know the address of your board. If you enabled static IPs (see <a href="building.html">building</a>) remember what you chose for the static IP; if DHCP
(the default) is used instead, your
DHCP server should've added the address of the <b>eLua</b> board to your DNS. The board name is always "elua"
in our code examples too, so if you execute "ping elua" from a shell you should see that the board is
alive.</li>
<li>telnet to the address of the board (or simply "telnet elua" if DHCP is used), and you'll be greeted with the shell prompt (if the shell is
enabled; see the next paragraph for details).
Note that you can only have one active telnet session to the <b>eLua</b> board at a given time.</li>
</ul>
<p>If you're under Windows, make sure you're using a proper telnet client, which basically means "just about everything <b>but</b> the
built-in telnet client".
<a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/">PuTTY</a> is a very good and popular choice.</p>
<a name="pc"><h3>Using standalone eLua on PC</h3></a>
<p>If you build <b>eLua</b> for the i386 platform, you can boot your PC directly in <b>eLua</b>! No underlying OS, nothing but plain <b>eLua</b>. It won't have any actual peripherals to
access, but it can use the <b>term</b> module to run <i>hangman.lua</i> and <i>life.lua</i>, as well as other
code examples and games, which makes it a nice demo :) Follow <a href="installing_i386.html">
this link</a> for specific informations about the i386 port. </p>
<a name="shell"><h3>The eLua shell</h3></a>
<p>No matter what's your physical connection (serial, TCP/IP or you PC's monitor after booting <b>eLua</b>), after you setup the PC-<b>eLua</b> board connection and press
the "RESET" button on your board or simply press ENTER if you're using the serial connection, you should see the <b>eLua</b> shell prompt (if you enabled the shell in your build, as described <a href="building.html">here</a>). The shell is a simple
interactive command interpreter that allows you to:</p>
<ul>
<li>get help on shell usage with the help command</li>
<li>query the eLua version running on your platform</li>
<li>upload a Lua source file via XMODEM and execute in on board</li>
<li>run the Lua interpreter in interactive mode just like you'd do on a desktop machine</li>
<li>run a Lua program from the eLua File System</li>
<li>list file names and sizes on eLua file systems</li>
<li>print contents from a (text) file in the eLua File System</li>
<li>list file contents</li>
</ul>
<p>A detailed description of the current shell commands is given below.</p>
<h2>help</h2>
<p>Show a list of all shell commands.</p>
<pre><code>$ help</code></pre>
<h2>ver</h2>
<p>Print the version of the <b>eLua</b> image installed on the board. Currently, the version only increments for official releases, so if there's inter-release code in the
development tree, this isn't reflected in the version number.</p>
<pre><code>$ ver</code></pre>
<h2>recv</h2>
<p>Allows you to receive from the PC running the terminal emulator program, a Lua file (either source or compiled bytecode) via
XMODEM and execute it on your board.</p>
<pre><code>$ recv</code></pre>
<p>To use this, your <b>eLua</b> target image must be built with support for XMODEM
(see <a href="building.html">building</a> for details). Also, your terminal emulation program must
support sending files via the XMODEM protocol. Both XMODEM with checksum and XMODEM with CRC are supported, but only XMODEM with 128
byte packets is allowed (XMODEM with 1K packets won't work).
To use this feature, enter "recv" at the shell prompt. <b>eLua</b> will respond with
"Waiting for file ...". At this point you can send the file to the eLua board
via XMODEM. eLua will receive and execute the file. Don't worry when you see 'C'
characters suddenly appearing on your terminal after you enter this command,
this is how the XMODEM transfer is initiated.<br>
Since XMODEM is a protocol that uses serial lines, this command is not available if you're using terminal over TCP/IP.<br>
If you'd like to send compiled bytecode to <b>eLua</b> instead of source code, please check <a href="using.html#cross">this section</a> first.
</p>
<h2>lua</h2>
<p>This command allows you to start the Lua interpreter, optionally passing command line parameters, just
as you would do from a desktop machine.</p>
<pre><code>$ lua</code></pre>
<p> There are some diferences from the the Lua in desktop version:</p>
<ul>
<li>the command line can't be longer than 50 chars</li>
<li>character escaping is not implemented. For example, the next command won't work
because of the ' (simple quotes) escape sequences:
<pre>
<code>eLua# lua -e 'print(\'Hello, World!\')' -i
Press CTRL+Z to exit Lua
lua: (command line):1: unexpected symbol near ''
</code>
</pre>
<p>However, if you use both '' (simple quotes) and "" (double quotes) for string quoting, it will work:</p>
<pre>
<code>eLua# lua -e 'print("Hello, World")' -i
Press CTRL+Z to exit Lua
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
Hello,World
</code>
</pre></li>
<li>
If you want to execute a file from the <a href="arch_romfs.html">ROM file system</a> (or from another file system), remember to prefix it with <i>/rom</i>. For example, to execute <b>hello.lua</b>, do this:
<pre><code>$ lua /rom/hello.lua</code></pre>
</li>
</ul>
<h2>ls or dir</h2>
<p>Shows a list of all the files in the file systems used by <b>eLua</b>, as well as their size and the total size of the given file system.</p>
<pre><code>$ ls
$ dir
</code></pre>
<h2>cat or type</h2>
<p>Prints the content of (usually text) files on the console.</p>
<pre><code>$ cat <i>filename1</i> [<i>filename2 filename3 ...</i>]
$ type <i>filename1</i> [<i>filename2 filename3 ...</i>]</code></pre>
<h2>cp</h2>
<p>Copies a file to another file. This command can be used to copy files between different file systems (for example between the MMC file system and the RFS file system).</p>
<pre><code>$ cp <i>source</i> <i>destination</i></code></pre>
<p>Note that both <b>source</b> and <b>destination</b> must be file names.</p>
<h2>exit</h2>
<p>Exits the shell. This only makes sense if <b>eLua</b> is compiled with terminal support over TCP/IP , as it closes the telnet session to the <b>eLua</b> board. Otherwise it just
terminates the shell and blocks forever until you reset your board.</p>
<pre><code>$ exit</code></pre>
<h2>wofmt</h2>
<p>"Formats" the <a href="arch_wofs.html">WOFS file system</a>, erasing its current contents. The user is asked to confirm this operation.</p>
<pre><code>$ wofmt</code></pre>
<a name="cross"><h3>Cross-compiling your eLua programs</h3></a>
<p><i>Cross-compilation</i> is the process of compiling a program on one hardware platform for a
different hardware platform. For example, the process of compiling the <b>eLua</b> binary image on
a PC for your <b>eLua</b> board is cross-compiling. Lua can be cross-compiled, too. By cross-compiling Lua
to bytecode on a PC and executing the resulting bytecode directly on your <b>eLua</b>
board you have some important advantages:</p>
<ul>
<li><b>speed</b>: the Lua compiler on the <b>eLua</b> board doesn't have to compile your Lua
source code, it just executes the compiled bytecode.</li>
<li><b>memory</b>: f you're executing bytecode directly, no more
memory is "wasted" on the <b>eLua</b> board for compiling the Lua code to bytecode.
Many times this could be a "life saver". If you're trying to run Lua code
directly on your board and you're getting "not enough memory" errors, you
might be able to overcome this by compiling the Lua program on the PC and
running the bytecode instead. Also, compiling large Lua programs on your
<b>eLua</b> board can lead to stack overflows, which in turn leads to very
hard to find errors.</li>
</ul>
<p>In order to use cross-compilation, the two Lua targets (in this case your desktop PC and your <b>eLua</b> board) must be compatible
(they should have the same data types, with the same size and the same memory
representation). This isn't true all the time. For example, some gcc toolchains for ARM targets use a very specific representation for double precision numbers (called FPA
format) by default, which makes bytecode files generated on the PC with the regular Lua compiler useless on
ARM boards. Other toolchains don't have this problem. Other targets (like AVR32) are big endian, as opposed to Intel PCs that are little endian.</p>
<p>To overcome this kind of problems, a "Lua cross-compilation patch" was posted on the
Lua mailing list a while ago, and it was further modified as part of the <b>eLua</b>
project to work with ARM targets. This is how to use it (the following
instructions were tested on Linux, not Windows, but they should work on Windows
too with little or no tweaking):</p>
<ul>
<li>first, make sure that your PC has already a build system installed (gcc,
binutils, libc, headers...). You'll also need scons. The good news is that
you should have it already installed, since otherwise you won't be able to
build even regular <b>eLua</b> (see <a href="building.html">building</a> for more in-depth instructions).</li>
<li>from the <b>eLua</b> base directory, issue this command:
<pre><code>$ scons -f cross-lua.py</code></pre></li>
</ul>
<p>You should get a file called <i>luac</i> in the same directory after this. It's almost the same as the regular Lua compiler, but it has a few arguments that deal with differences between different targets (shown below in bold):</p>
<pre><code>usage: ./luac [options] [filenames].
Available options are:
- process stdin
-l list
-o name output to file 'name' (default is "luac.out")
-p parse only
-s strip debug information
-v show version information
<b>-cci bits cross-compile with given integer size
-ccn type bits cross-compile with given lua_Number type and size
-cce endian cross-compile with given endianness ('big' or 'little')</b>
-- stop handling options</code></pre>
<p>All it's left to do now is to use the table below to figure out what are the right parameters for using the cross-compiler:</p>
<table style="text-align: left;" class="table_center">
<tbody>
<tr>
<th style="text-align: left;">eLua image type</th>
<th style="text-align: center;">Architecture</th>
<th style="text-align: center;">Compiler</th>
<th style="text-align: center;">Command</th>
</tr>
<tr>
<td>Floating point (lua)</td>
<td>ARM7TDMI<br>Cortex-M3<br>ARM966E-S</td>
<td><a href="toolchains.html">arm-gcc</a></td>
<td><code>./luac -ccn float_arm 64 -cce little -o &lt;script.luac&gt; -s &lt;script.lua&gt;</code></td>
</tr>
<tr>
<td>Floating point (lua)</td>
<td>ARM7TDMI<br>Cortex-M3<br>ARM966E-S</td>
<td><a href="toolchains.html">codesourcery</a></td>
<td><code>./luac -ccn float 64 -cce little -o &lt;script.luac&gt; -s &lt;script.lua&gt;</code></td>
</tr>
<tr>
<td>Integer (lualong)</td>
<td>ARM7TDMI<br>Cortex-M3<br>ARM966E-S</td>
<td><a href="toolchains.html">arm-gcc<br>codesourcery</a></td>
<td><code>./luac -ccn int 32 -cce little -o &lt;script.luac&gt; -s &lt;script.lua&gt;</code></td>
</tr>
<tr>
<td>Floating point (lua)</td>
<td>AVR32</td>
<td><a href="toolchains.html">avr32-gcc</a></td>
<td><code>./luac -ccn float 64 -cce big -o &lt;script.luac&gt; -s &lt;script.lua&gt;</code></td>
</tr>
<tr>
<td>Integer (lualong)</td>
<td>AVR32</td>
<td><a href="toolchains.html">avr32-gcc</a></td>
<td><code>./luac -ccn int 32 -cce big -o &lt;script.luac&gt; -s &lt;script.lua&gt;</code></td>
</tr>
</tbody>
</table>
<p>(note that if for some reason you want to cross-compile <b>eLua</b> for the x86 target you can use the regular Lua compiler).<br>
You can omit the <i>-s</i> (strip) parameter from compilation, but this will result in larger bytecode files (as the debug information is not stripped if you don't use <i>-s</i>).</p>
<p>You can use your bytecode file in two ways:</p>
<ul>
<li>write it to <a href="arch_romfs.html">the ROM file system</a> and execute it from there.</li>
<li>use the <i>recv</i> command from <a href="using.html#shell">the shell</a> to upload it to the board using a serial connection.</li>
<li>write it to an sd/mmc card and, if your board supports it, execute it
from there.</li>
</ul>
<a name="rpc"><h3>Controlling eLua with LuaRPC</h3></a>
<p><i>Remote procedure calls</i> (RPC) allow one program to communicate with another and call functions or subroutines within the second program. For example one might want to programmatically control an array of LEDs connected to an eLua embedded device from a desktop Lua state. A simple implementation might be a protocol that would allow one to send numeric or text-based commands that would cause code to be executed in eLua that would change the state of the LEDs. As one needs new commands to change these LEDs, one would need to upload a new Lua program to handle changing functionality. In contrast to this ad-hoc method for remote calls, LuaRPC provides a more general way to manipulate the state and execution of a remote Lua environment.</p>
<p>When a client is connected to a LuaRPC server, it can interact with it in the following ways:</p>
<ul>
<li>assign values to new or existing variables in the server state</li>
<li>get values from variables in the server state</li>
<li>call functions to be executed on the server side using parameters of serializable types, with return values being sent back to the client</li>
<li>create local userdata helpers (aliases) which provide short-hand access to remote state</li>
</ul>
<h2>Building the Desktop Client/Server</h2>
<ul>
<li>first, make sure that your PC has already a build system installed (gcc,
binutils, libc, headers...). You'll also need scons. The good news is that
you should have it already installed, since otherwise you won't be able to
build even regular <b>eLua</b> (see <a href="building.html">building</a> for more in-depth instructions).</li>
<li>from the <b>eLua</b> base directory, issue this command:
<pre><code>$ scons -f rpc-lua.py</code></pre></li>
</ul>
<p>You should get a file called <i>luarpc</i> in the same directory which, when started, should give you a normal Lua interpreter with a built-in rpc module.</p>
<h2>Building eLua with RPC Boot</h2>
<p>See <a href="building.html">building</a> for details and requirements for the building process. In order to boot into RPC mode, the RPC <a href="building.html#components">component</a> will need to be enabled, and appropriate <a href="building.html#static">static configuration data</a> need to be set. To build <b>eLua</b> to boot into RPC mode, include
<b>boot=luarpc</b> in the <a href="building.html#buildoptions">build options</a>.</p>
<h2>LuaRPC Basics</h2>
<p>In terms of the LED example from the beginning of this section, one could directly call pio module functions from the desktop side, experimenting with responses. If the experimentation developed into a program this could be tested both on the desktop side and on the microcontroller by making aliases to eLua modules in local Lua state. Such aliasing can be done as follows:</p>
<pre><code>-- open connection from Linux host serial port to eLua
slave,err = rpc.connect("/dev/ttyUSB0")
-- make a local helper pointing to pio module in eLua
pio = slave.pio
-- define function to set direction and value of port B
function set_port_val(val)
pio.port.setdir( pio.OUTPUT, pio.PB )
pio.port.setval( val, pio.PB )
end
set_port_val(23)</pre></code>
<p>When we run this locally, calling and indexing helpers are translated into appropriate actions on the server. If we were done with modifications to the above function and wanted it to execute in eLua rather than using local aliases, which will result in a great deal of RPC traffic every time the function is called, we can send the function to the remote side:</p>
<pre><code>-- cross-compile local chunk for function and send to server
slave.set_port_val = set_port_val
-- call function on server device
slave.set_port_val(23)</pre></code>
<p>In addition to functions, we can also copy most other Lua types from client to server using simple assignment. Due to Lua's internal workings the opposite operation of copying Lua types from server to client requires an additional metamethod:</p>
<pre><code>-- make table on remote server
slave.remote_table = {}
-- put data in table
slave.remote_table.rval = 42
-- get data back from server, print
local_table = slave.remote_table:get()
print(local_table.rval)</pre></code>
<p>While these examples are trivial, they serve to illustrate a compelling development paradigm that gives one a great deal of flexibility for development and testing with an embedded target.</p>
<h2>Serializable Lua Types</h2>
<p>Most Lua types can be transferred between the client and server states. The following list indicates which ones can be transferred, and where there are known exceptions:</p>
<table style="text-align: left;" class="table_center">
<tbody>
<tr>
<th style="text-align: left;">Serializable Types</th>
<th style="text-align: center;">Exceptions and Notes</th>
</tr>
<tr>
<td>numbers</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>strings</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>booleans</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>tables</td>
<td>no circular references</td>
</tr>
<tr>
<td>functions</td>
<td>no upvalues</td>
</tr>
<tr>
<td>nil</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
$$FOOTER$$

252
doc/en/using.txt Normal file
View File

@ -0,0 +1,252 @@
// $$HEADER$$
Using eLua
----------
So, you already link:building.html[built] and link:installing.html[installed] eLua, now it is time to (finally) have some fun with it :)
You can compile eLua with either console over UART (the default and by far the most popular) or console over TCP/IP (still experimental,
but working quite well). See link:building.html[building eLua] for details on how to choose between serial and TCP/IP console.
[[uart]]
Using eLua over serial connections
----------------------------------
All you need to use eLua over a serial connection is your eLua board connected to a PC running a terminal emulator program.
If you're using Windows, we recommend http://www.ayera.com/teraterm/[TeraTerm]. It's a freeware, it's very powerful and
also easy to use. The native Hyper Terminal progam can do too, as well as any most other terminal emulator programs.
On Linux, you'll probably be stucked with minicom. It is not exactly intuitive and it runs in text mode, but it's still
very powerful. If you google for "minicom tutorial" you'll get the hang of it in no time. You can try any other terminal emulator,
as long as you set it up properly and it gives you the option of transferring files via XMODEM, which is what eLua uses at the
moment. These are the main settings you need to look at:
- port setup: 115200 baud (38400 for link:installing_str7.html[STR7]), 8N1(8 data bits, no parity, one stop bit).
- flow control: none, unless your eLua image is configured to use hardware flow control/
- newline handling: "CR" on receive, "CR+LF" on send (some terminal programs won't give you a choice here).
Also, depending on the type of your board, you'll need some way to connect the board to a serial port on your PC or to USB if
you're using an USB to serial converter. For example (as already explained link:installing_lm3s.html[here]), the USB port on
the LM3Sxxxx boards is dual, so you can use it as an USB to serial converter after downloading your firmware, thus you don't
need any other type of connection. The same is true for the STR9-comStick board. On the other hand, for the SAM7-EX256 board you'll
need to connect a serial cable to the "RS232" connector, provided that the jumpers are already set as explained
link:installing_at91sam7x.html[here] and on the MOD711 you will need to add an RS232 converter chip. There's no universal rule here,
it all depends on your board. Feel free to ask if you need help in our https://lists.berlios.de/mailman/listinfo/elua-dev"[discussion list].
[[tcpip]]
Using eLua over TCP/IP connections
----------------------------------
Things are even easier if you decide to enable console over TCP/IP:
- make sure you know the address of your board. If you enabled static IPs (link:building.html[building]) remember what you chose for the
static IP; if DHCP (the default) is used instead, your DHCP server should've added the address of the eLua board to your DNS. The board
name is always "elua" in our code examples too, so if you execute "ping elua" from a shell you should see that the board is alive.
- telnet to the address of the board (or simply "telnet elua" if your DNS is properly set), and you'll be greeted with the shell prompt
(if the shell is enabled; see the next paragraph for details). Note that you can only have one active telnet session to the eLua board
at any given time.
If you're under Windows, make sure you're using a proper telnet client, which basically means "just about everything *but* the
built-in telnet client". http://www.chiark.greenend.org.uk/~sgtatham/putty/[PuTTY] is a very good and popular choice.
[[pc]]
Using standalone eLua on PC
---------------------------
If you build eLua for the i386 platform, you can boot your PC directly in eLua! No underlying OS, nothing but plain eLua.
It won't have any actual peripherals to access, but it can use the *term* module to run _hangman.lua_ and _life.lua_, as well
as other code examples and games, which makes it a nice demo :) Follow link:installing_i386.html[this link] for specific
informations about the i386 port.
[[shell]]
The eLua shell
--------------
No matter what's your physical connection (serial, TCP/IP or you PC's monitor after booting eLua), after you setup the
PC-eLua board connection and press the "RESET" button on your board or simply press ENTER if you're using the serial connection,
you should see the eLua< shell prompt (if you enabled the shell in your build, as described link:building.html[here]). The shell
is a simple interactive command interpreter that allows you to:
- get help on shell usage with the help command,
- query the eLua version running on your platform,
- upload a Lua source file via XMODEM and execute in on board,
- run the Lua interpreter in interactive mode just like you'd do on a desktop machine.
- run a Lua program from a link:filesystems.html[file system].
- list file names and sizes on eLua file systems.
- list file contents
- execute file operations (copy, rename, move, delete)
eLua has two different versions of the shell (check link:building.html[here] for information about how to enable each of them):
- the basic version is small (to keep the eLua image small), but functional. The documentation for the basic shell can be found link:simple_shell.html[here].
- the advanced shell (new in *0.9*) adds file masks, file operations and other goodies to the basic shell. If you have enough flash on your
MCU, this is almost certainly the version that you want. The documentation for the advanced shell can be found link:advanced_shell.html[here].
[[cross]]
Cross-compiling your eLua programs
----------------------------------
_Cross-compilation_ is the process of compiling a program on one hardware platform for a different hardware platform (for
example, the process of compiling the eLua binary image ona PC for your eLua board). Lua can be cross-compiled, too. By
cross-compiling Lua to bytecode on a PC and executing the resulting bytecode directly on your eLua board you have some
important advantages:
- speed: the Lua compiler on the eLua board doesn't have to compile your Lua source code, it just executes the compiled bytecode.
- memory: if you're executing bytecode directly, no more memory is "wasted" on the eLua board for compiling the Lua code
to bytecode. Many times this could be a "life saver". If you're trying to run Lua code directly on your board and you're
getting "not enough memory" errors, you might be able to overcome this by compiling the Lua program on the PC and running the
bytecode instead. Also, compiling large Lua programs on your eLua board can lead to stack overflows, which in turn leads to very
hard to find errors.
In order to use cross-compilation, the two Lua targets (in this case your desktop PC and your eLua board) must be compatible
(they should have the same data types, with the same size and the same memory representation). This isn't true all the time.
For example, some gcc toolchains for ARM targets use a very specific representation for double precision numbers (called FPA
format) by default, which makes bytecode files generated on the PC with the regular Lua compiler useless on ARM boards. Other
toolchains don't have this problem. Other targets (like AVR32) are big endian, as opposed to Intel PCs that are little endian.
To overcome these kind of problems, a "Lua cross-compilation patch" was posted on the Lua mailing list a while ago, and it was
further modified as part of the eLua project to work with ARM targets. This is how to use it (the following instructions were
tested on Linux, not Windows, but they should work on Windows too with little or no tweaking):
- first, make sure that your PC has already a build system installed (gcc, binutils, libc, headers...). You'll also need scons.
The good news is that you should have it already installed, since otherwise you won't be able to build even regular eLua
(see link:building.html[building] for more in-depth instructions).
- from the eLua base directory, issue this command:
$ scons -f cross-lua.py
You should get a file called _luac_ in the same directory as a result. It's almost the same as the regular Lua compiler, but it
has a few arguments that deal with differences between different targets (shown below in bold):
[subs="quotes"]
------------------------------------
usage: ./luac [options] [filenames].
Available options are:
- process stdin
-l list
-o name output to file 'name' (default is "luac.out")
-p parse only
-s strip debug information
-v show version information
*-cci bits cross-compile with given integer size*
*-ccn type bits cross-compile with given lua_Number type and size*
*-cce endian cross-compile with given endianness ('big' or 'little')*
-- stop handling options
------------------------------------
All it's left to do now is to use the table below to figure out what are the right parameters for using the cross-compiler:
[width="90%", cols="^,^,^,2^", options="header"]
|===============================================================
^|Image type ^|Arch ^|Compiler ^|Command
|Floating point (lua) |ARM7TDMI _br Cortex-M3 _br ARM966E-S |link:toolchains.html[arm-gcc] |./luac *-ccn float_arm 64 -cce little* -o <script.luac> -s <script.lua>
|Floating point (lua) |ARM7TDMI _br Cortex-M3 _br ARM966E-S |link:toolchains.html[codesoucery] |./luac *-ccn float 64 -cce little* -o <script.luac> -s <script.lua>
|Integer (lualong) |ARM7TDMI _br Cortex-M3 _br ARM966E-S |link:toolchains.html[arm-gcc] _br link:toolchains.html[codesourcery] |./luac *-ccn int 32 -cce little* -o <script.luac> -s <script.lua>
|Floating point (lua) |AVR32 |link:toolchains.html[avr32-gcc] |./luac *-ccn float 64 -cce big* -o <script.luac> -s <script.lua>
|Integer (lualong) |AVR32 |link:toolchains.html[avr32-gcc] |./luac *-ccn int 32 -cce big* -o <script.luac> -s <script.lua>
|===============================================================
You can omit the _-s_ (strip) parameter from compilation, but this will result in larger bytecode files (as the debug information is not stripped if you don't use _-s_).
You can use your bytecode file in multiple ways:
- write it to link:arch_romfs.html[the ROM file system] and execute it from there.
- use the _recv_ command from link:using.html#shell[the shell] to upload it to the board using a serial connection.
- write it to an sd/mmc card and, if your board supports it, execute it from there.
[[rpc]]
Controlling eLua with LuaRPC
----------------------------
_Remote procedure calls_ (RPC) allow one program to communicate with another and call functions or subroutines within
the second program. For example one might want to programmatically control an array of LEDs connected to an eLua embedded
device from a desktop Lua state. A simple implementation might be a protocol that would allow one to send numeric or
text-based commands that would cause code to be executed in eLua that would change the state of the LEDs. As one needs
new commands to change these LEDs, one would need to upload a new Lua program to handle changing functionality. In contrast
to this ad-hoc method for remote calls, LuaRPC provides a more general way to manipulate the state and execution of a remote
Lua environment.
When a client is connected to a LuaRPC server, it can interact with it in the following ways:
- assign values to new or existing variables in the server state
- get values from variables in the server state
- call functions to be executed on the server side using parameters of serializable types, with return values being sent back to the client
- create local userdata helpers (aliases) which provide short-hand access to remote state
Building the Desktop Client/Server
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- first, make sure that your PC has already a build system installed (gcc, binutils, libc, headers...). You'll also need scons. The good news is that
you should have it already installed, since otherwise you won't be able to build even regular eLua (see link:building.html[building] for more instructions).
- from the <b>eLua</b> base directory, issue this command:
$ scons -f rpc-lua.py
You should get a file called _luarpc_ in the same directory which, when started, should give you a normal Lua interpreter with a built-in rpc module.
Building eLua with RPC Boot
~~~~~~~~~~~~~~~~~~~~~~~~~~~
See link:building.html[building] for details and requirements for the building process. In order to boot into RPC mode, the RPC
link:building.html#components[component] will need to be enabled, and appropriate link:building.html#static[static configuration data] needs to be set.
To build eLua to boot into RPC mode, include *boot=luarpc* in the link:building.html#buildoptions[build options].
LuaRPC Basics
~~~~~~~~~~~~~
In terms of the LED example from the beginning of this section, one could directly call pio module functions from the desktop
side, experimenting with responses. If the experimentation developed into a program this could be tested both on the desktop side
and on the microcontroller by making aliases to eLua modules in local Lua state. Such aliasing can be done as follows:
-------------------------------------------------------
-- open connection from Linux host serial port to eLua
slave,err = rpc.connect("/dev/ttyUSB0")
-- make a local helper pointing to pio module in eLua
pio = slave.pio
-- define function to set direction and value of port B
function set_port_val(val)
pio.port.setdir( pio.OUTPUT, pio.PB )
pio.port.setval( val, pio.PB )
end
set_port_val(23)
-------------------------------------------------------
When we run this locally, calling and indexing helpers are translated into appropriate actions on the server. If we were done with
modifications to the above function and wanted it to execute in eLua rather than using local aliases, which will result in a great deal
of RPC traffic every time the function is called, we can send the function to the remote side:
------------------------------------------------------------
-- cross-compile local chunk for function and send to server
slave.set_port_val = set_port_val
-- call function on server device
slave.set_port_val(23)
------------------------------------------------------------
In addition to functions, we can also copy most other Lua types from client to server using simple assignment. Due to Lua's internal
workings the opposite operation of copying Lua types from server to client requires an additional metamethod:
--------------------------------------
-- make table on remote server
slave.remote_table = {}
-- put data in table
slave.remote_table.rval = 42
-- get data back from server, print
local_table = slave.remote_table:get()
print(local_table.rval)
--------------------------------------
While these examples are trivial, they serve to illustrate a compelling development paradigm that gives one a great deal of flexibility for development and testing with an embedded target.
Serializable Lua Types
~~~~~~~~~~~~~~~~~~~~~~
Most Lua types can be transferred between the client and server states. The following list indicates which ones can be transferred, and where there are known exceptions:
[width="90%", cols="^,^", options="header"]
|===============================================================
^|Serializable types ^|Exceptions and notes
| Numbers |
| Strings |
| Booleans |
| Tables | No circular references
| Functions | No upvalues
| nil |
|===============================================================
// $$FOOTER$$

View File

@ -6,6 +6,7 @@
#include "elua_int.h"
#include "lua.h"
#include "platform.h"
#include "devman.h"
// Virtual timers data
// VTMR_FIRST_ID must be LARGER than PLATFORM_TIMER_SYS_ID (as declared in platform.h)
@ -13,6 +14,25 @@
#define VTMR_GET_ID( x ) ( ( x ) - VTMR_FIRST_ID )
#define TIMER_IS_VIRTUAL( x ) ( ( VTMR_NUM_TIMERS > 0 ) && ( ( x ) >= VTMR_FIRST_ID ) && ( ( x ) < VTMR_NUM_TIMERS + VTMR_FIRST_ID ) )
// FS interface
#define CMN_FS_INFO_BEFORE_READDIR 0
#define CMN_FS_INFO_INSIDE_READDIR 1
#define CMN_FS_INFO_AFTER_CLOSEDIR 2
#define CMN_FS_INFO_MEMORY_ERROR 3
#define CMN_FS_INFO_OPENDIR_FAILED 4
#define CMN_FS_INFO_READDIR_FAILED 5
#define CMN_FS_INFO_DIRECTORY_DONE 6
#define CMN_FS_TYPE_DIR 0
#define CMN_FS_TYPE_FILE 1
#define CMN_FS_TYPE_PATTERN 2
#define CMN_FS_TYPE_ERROR 3
#define CMN_FS_TYPE_FILE_NOT_FOUND 4
#define CMN_FS_TYPE_DIR_NOT_FOUND 5
#define CMN_FS_TYPE_UNKNOWN_NOT_FOUND 6
typedef int ( *p_cmn_fs_walker_cb )( const char*, const struct dm_dirent*, void*, int );
// Functions exported by the common platform layer
void cmn_platform_init();
void cmn_virtual_timer_cb();
@ -27,10 +47,19 @@ void cmn_systimer_set_interrupt_freq( u32 freq_hz );
void cmn_systimer_set_interrupt_period_us( u32 period );
void cmn_systimer_periodic();
timer_data_type cmn_systimer_get();
// Filesystem-related functions
int cmn_fs_walkdir( const char *path, p_cmn_fs_walker_cb cb, void *pdata, int recursive );
char* cmn_fs_split_path( const char *path, const char **pmask );
int cmn_fs_get_type( const char* path );
char* cmn_fs_path_join( const char *first, ... );
int cmn_fs_is_root_dir( const char *path );
int cmn_fs_check_directory( const char *path );
void cmn_uart_setup_sermux();
unsigned int intlog2( unsigned int v );
char lastchar( const char *s );
char firstchar( const char *s );
const char* cmn_str64( u64 x );
void cmn_get_timeout_data( lua_State *L, int pidx, unsigned *pid, timer_data_type *ptimeout );

View File

@ -45,6 +45,8 @@ typedef struct {
void *userdata;
} DM_DIR;
#define DM_DIRENT_IS_DIR( ent ) ( ( ( ent )->flags & DM_DIRENT_FLAG_DIR ) != 0 )
// A device structure with pointers to all the device functions
typedef int mkdir_mode_t;
@ -60,6 +62,9 @@ typedef struct
int ( *p_closedir_r )( struct _reent *r, void* dir, void *pdata );
const char* ( *p_getaddr_r )( struct _reent *r, int fd, void *pdata );
int ( *p_mkdir_r )( struct _reent *r, const char *pathname, mkdir_mode_t mode, void *pdata );
int ( *p_unlink_r )( struct _reent *r, const char *fname, void *pdata );
int ( *p_rmdir_r )( struct _reent *r, const char *fname, void *pdata );
int ( *p_rename_r )( struct _reent *r, const char *oldname, const char *newname, void *pdata );
} DM_DEVICE;
// Additional registration data for each FS (per FS instance)

View File

@ -3,13 +3,43 @@
#ifndef __SHELL_H__
#define __SHELL_H__
#include "type.h"
#define SHELL_WELCOMEMSG "\neLua %s Copyright (C) 2007-2011 www.eluaproject.net\n"
#define SHELL_PROMPT "eLua# "
#define SHELL_ERRMSG "Invalid command, type 'help' for help\n"
#define SHELL_MAXSIZE 50
#define SHELL_MAX_LUA_ARGS 8
// Shell command handler function
typedef void( *p_shell_handler )( int argc, char **argv );
// Command/handler pair structure
typedef struct
{
const char* cmd;
p_shell_handler handler_func;
} SHELL_COMMAND;
int shell_init();
void shell_start();
const SHELL_COMMAND* shellh_execute_command( char* cmd, int interactive_mode );
int shellh_cp_file( const char *src, const char *dst, int flags );
void shellh_not_implemented_handler( int argc, char **argv );
void shellh_show_help( const char *cmd, const char *helptext );
#define SHELL_SHOW_HELP( cmd ) shellh_show_help( #cmd, shell_help_##cmd )
// Helpers for various functions
int shellh_ask_yes_no();
// Flags for various operations
#define SHELL_F_RECURSIVE 1
#define SHELL_F_FORCE_DESTINATION 2
#define SHELL_F_ASK_CONFIRMATION 4
#define SHELL_F_SIMULATE_ONLY 8
#define SHELL_F_SILENT 16
#define SHELL_F_MOVE 32
#endif // #ifndef __SHELL_H__

View File

@ -88,5 +88,10 @@
#endif
#endif
// BUILD_ADVANCED_SHELL needs BUILD_SHELL
#if defined( BUILD_ADVANCED_SHELL ) && !defined( BUILD_SHELL )
#error "BUILD_ADVANCED_SHELL needs BUILD_SHELL"
#endif
#endif // #ifndef __VALIDATE_H__

View File

@ -573,6 +573,24 @@ unsigned int intlog2( unsigned int v )
return r;
}
char lastchar( const char *s )
{
unsigned len;
if( !s )
return '\0';
len = strlen( s );
if( len == 0 )
return '\0';
else
return s[ len - 1 ];
}
char firstchar( const char *s )
{
return s ? s[ 0 ]: '\0';
}
// 64-bits integer printf support seems to be broken in some versions of Newlib...
const char* cmn_str64( u64 x )
{

301
src/common_fs.c Normal file
View File

@ -0,0 +1,301 @@
// Common file system related operations
#include "common.h"
#include <stdio.h>
#include "devman.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#define SAFE_CLOSEDIR( dir ) \
do { \
dm_closedir( dir ); \
dir = NULL; \
} while( 0 )
// Returns 1 if 'str' matches the given pattern, 0 otherwise
// '?' matches a single char
// "*" matches one or more chars, NON-GREEDY
static int cmn_pattern_matches( const char *str, const char *pattern )
{
int pidx, sidx;
pidx = sidx = 0;
while( pattern[ pidx ] != 0 )
{
if( pattern[ pidx ] == '*' )
{
pidx ++;
// Eat all '?' chars after the '*'
while( pattern[ pidx ] == '?' )
pidx ++;
if( pattern[ pidx ] == 0 ) // '*' in the last position matches everything
return 1;
while( str[ sidx ] != pattern[ pidx ] && str[ sidx ] != 0 )
sidx ++;
if( str[ sidx ++ ] == 0 )
return 0;
}
else if( pattern[ pidx ] == '?' )
{
if( str[ sidx ++ ] == 0 )
return 0;
}
else
{
if( pattern[ pidx ] != str[ sidx ++ ] )
return 0;
}
pidx ++;
}
return str[ sidx ] == 0;
}
// Splits a path into "directory" and "filemask" name
// Returns a pointer to the directory name. The pointer is dynamically
// allocated and it MUST be freed by the caller!
// Also returns a pointer to the file mask in "pmask" as a side effect
// Returns NULL on error
char *cmn_fs_split_path( const char *path, const char **pmask )
{
static const char *all_mask = "*";
FILE *fp;
if( !path || strlen( path ) < 2 || path[ 0 ] != '/' )
return NULL;
// /fs -> always a directory ('/'), mask is *
if( strchr( path + 1, '/' ) == NULL )
{
*pmask = all_mask;
return strdup( path );
}
// /fs/dir1/dir2/dirn/ -> always a directory (note the final '/' ), mask is '*'
if( path[ strlen( path ) - 1 ] == '/' )
{
*pmask = all_mask;
return strndup( path, strlen( path ) - 1 );
}
// At this point, we don't know if 'path' reffers to a file or to a directory
// So try to open it. If it can be opened, it is a file. Otherwise it is a directory.
// But first check for '*' or '?' chars in path (which means it is definitely a file spec)
*pmask = strrchr( path, '/' ) + 1;
if( strchr( path, '*' ) || strchr( path, '?' ) )
return strndup( path, *pmask - path - 1 );
if( ( fp = fopen( path, "r" ) ) != NULL )
{
fclose( fp );
return strndup( path, *pmask - path - 1 );
}
// It is a path, so return it as-is
*pmask = all_mask;
return strdup( path );
}
// Returns the type of the path given as argument
// This can be either CMN_FS_TYPE_DIR, CMN_FS_TYPE_FILE or CMN_FS_TYPE_PATTERN
// Note that CMN_FS_TYPE_DIR is NOT actually checked. A name with a '/' in the
// last position or a name with a single '/' (for example /rom/ and /rom respectively)
// is assumed to be a directory. Otherwise, if the 'path' is not a mask and also
// not a regular file, it is assumed to be a directory
int cmn_fs_get_type( const char *path )
{
FILE *fp;
DM_DIR *d;
if( !path || strlen( path ) < 2 || path[ 0 ] != '/' )
return CMN_FS_TYPE_ERROR;
// /fs -> always a directory ('/'), mask is *
if( strchr( path + 1, '/' ) == NULL )
return CMN_FS_TYPE_DIR;
// /fs/dir1/dir2/dirn/ -> always a directory (note the final '/' ), mask is '*'
if( path[ strlen( path ) - 1 ] == '/' )
{
if( ( d = dm_opendir( path ) ) == NULL )
return CMN_FS_TYPE_DIR_NOT_FOUND;
dm_closedir( d );
return CMN_FS_TYPE_DIR;
}
// At this point, we don't know if 'path' reffers to a file or to a directory
// So try to open it. If it can be opened, it is a file. Otherwise it is a directory.
// But first check for '*' or '?' chars in path (which means it is definitely a file spec)
if( strchr( path, '*' ) || strchr( path, '?' ) )
return CMN_FS_TYPE_PATTERN;
if( ( fp = fopen( path, "r" ) ) != NULL )
{
fclose( fp );
return CMN_FS_TYPE_FILE;
}
if( ( d = dm_opendir( path ) ) == NULL )
return CMN_FS_TYPE_UNKNOWN_NOT_FOUND;
dm_closedir( d );
return CMN_FS_TYPE_DIR;
}
// Join the given elements in a single PATH
// The memory for the final buffer is dynamically allocated and MUST be
// freed by the caller
char *cmn_fs_path_join( const char *first, ... )
{
unsigned total = 0;
va_list ap;
const char *tmp = first;
char *res;
va_start( ap, first );
// Get total length first
while( tmp )
{
if( strlen( tmp ) > 0 )
{
total += strlen( tmp ) + ( lastchar( tmp ) == '/' ? 0 : 1 );
if( firstchar( tmp ) == '/' )
total --;
}
tmp = va_arg( ap, const char* );
}
va_end( ap );
if( total == 0 || ( ( res = ( char* )malloc( total + 2 ) ) == NULL ) )
return NULL;
strcpy( res, "/" );
va_start( ap, first );
tmp = first;
while( tmp )
{
if( strlen( tmp ) > 0 )
{
strcat( res, tmp + ( firstchar( tmp ) == '/' ? 1 : 0 ) );
if( lastchar( res ) != '/' )
strcat( res, "/" );
}
tmp = va_arg( ap, const char* );
}
res[ strlen( res ) - 1 ] = '\0';
va_end( ap );
return res;
}
// This is a generic file/directory walker. It is used by all shell
// operations that have something to do with files (ls, cp, rm...)
// It receives an initial path, which may contain also a pattern specification
// (see cmn_pattern_matches above). If "recursive" is true, it will
// recursively find all files and directories underneath 'path' that match
// the optional pattern in 'path'. When a file is called, the "callback" is
// called. The callback is a function with the following signature:
// void walker_cb( const char *path, const struct dm_entry *ent, void *pdata, int info );
// 'path' is the full path of the file/directory found by the walker
// 'ent' is the directory entry (as defined in devman.h)
// 'pdata' is the callback state, passed to the callback function exactly
// as given to the walker function.
// 'info' gives more information about why/where the callback was called:
// CMN_FS_INFO_BEFORE_READDIR
// CMN_FS_INFO_INSIDE_READDIR
// CMN_FS_INFO_AFTER_CLOSEDIR
// CMN_FS_INFO_DIRECTORY_DONE
// CMN_FS_INFO_MEMORY_ERROR -> called after a memory allocation failed
// CMN_FS_INFO_OPENDIR_FAILED
// CMN_FS_INFO_READDIR_FAILED
// The callback can return 0 (stop walking the directory and calling the callback)
// or 1 (keep on calling the callback). If a 0 was returned, this will also be the
// result returned by the walker, otherwise 1 is returned
static int cmn_fs_actual_walkdir( const char *path, const char *pattern, p_cmn_fs_walker_cb cb, void *pdata, int recursive )
{
DM_DIR *d;
struct dm_dirent *ent;
int hasdirs, isdir;
char *fullname;
if( ( d = dm_opendir( path ) ) != NULL )
{
if( cb( path, NULL, pdata, CMN_FS_INFO_BEFORE_READDIR ) == 0 )
goto abort;
while( ( ent = dm_readdir( d ) ) != NULL )
{
isdir = ( ent->flags & DM_DIRENT_FLAG_DIR ) != 0;
if( !cmn_pattern_matches( ent->fname, pattern ) )
continue;
if( cb( path, ent, pdata, CMN_FS_INFO_INSIDE_READDIR ) == 0 )
goto abort;
if( isdir )
hasdirs = 1;
}
SAFE_CLOSEDIR( d );
if( cb( path, ent, pdata, CMN_FS_INFO_AFTER_CLOSEDIR ) == 0 )
goto abort;
if( recursive && hasdirs )
{
if( ( d = dm_opendir( path ) ) != NULL )
{
while( ( ent = dm_readdir( d ) ) != NULL )
{
if( ent->flags & DM_DIRENT_FLAG_DIR )
{
if( ( fullname = cmn_fs_path_join( path, ent->fname, NULL ) ) != NULL )
{
hasdirs = cmn_fs_actual_walkdir( fullname, pattern, cb, pdata, 1 );
free( fullname );
if( hasdirs == 0 )
goto abort;
}
else
if( cb( path, NULL, pdata, CMN_FS_INFO_MEMORY_ERROR ) == 0 )
goto abort;
}
}
SAFE_CLOSEDIR( d );
}
else
if( cb( path, NULL, pdata, CMN_FS_INFO_OPENDIR_FAILED ) == 0 )
return 0;
}
if( cb( path, ent, pdata, CMN_FS_INFO_DIRECTORY_DONE ) == 0 )
goto abort;
}
else
if( cb( path, NULL, pdata, CMN_FS_INFO_OPENDIR_FAILED ) == 0 )
return 0;
return 1;
abort:
if( d )
dm_closedir( d );
return 0;
}
int cmn_fs_walkdir( const char *path, p_cmn_fs_walker_cb cb, void *pdata, int recursive )
{
char *actpath;
const char *pattern;
if( ( actpath = cmn_fs_split_path( path, &pattern ) ) == NULL )
return 0;
cmn_fs_actual_walkdir( actpath, pattern, cb, pdata, recursive );
free( actpath );
return 1;
}
int cmn_fs_is_root_dir( const char *path )
{
if( !path )
return 0;
if( path[ 0 ] != '/' )
return 0;
if( ( path = strchr( path + 1, '/' ) ) == NULL )
return 1;
if( *( path + 1 ) == 0 )
return 1;
return 0;
}
// Check if the directory in the given argument (if applicable)
// can be opened
int cmn_fs_check_directory( const char *path )
{
DM_DIR *d;
if( ( d = dm_opendir( path ) ) == NULL )
return 0;
dm_closedir( d );
return 1;
}

View File

@ -297,6 +297,16 @@ static int mmcfs_mkdir_r( struct _reent *r, const char *name, mkdir_mode_t mode,
return f_mkdir( name );
}
static int mmcfs_unlink_r( struct _reent *r, const char *fname, void *pdata )
{
return f_unlink( fname );
}
static int mmcfs_rename_r( struct _reent *r, const char *oldname, const char *newname, void *pdata )
{
return f_rename( oldname, newname );
}
// MMC device descriptor structure
static const DM_DEVICE mmcfs_device =
{
@ -309,7 +319,10 @@ static const DM_DEVICE mmcfs_device =
mmcfs_readdir_r, // readdir
mmcfs_closedir_r, // closedir
NULL, // getaddr
mmcfs_mkdir_r // mkdir
mmcfs_mkdir_r, // mkdir
mmcfs_unlink_r, // unlink
mmcfs_unlink_r, // rmdir
mmcfs_rename_r // rename
};
int mmcfs_init()

View File

@ -9,7 +9,9 @@
#include "legc.h"
#include "platform_conf.h"
#include "linenoise.h"
#include "shell.h"
#include <string.h>
#include <stdlib.h>
#if defined( USE_GIT_REVISION )
#include "git_version.h"
@ -59,6 +61,22 @@ static int elua_save_history( lua_State *L )
#endif // #ifdef BUILD_LINENOISE
}
// Lua: elua.shell( <shell_command> )
static int elua_shell( lua_State *L )
{
const char *pcmd = luaL_checkstring( L, 1 );
char *cmdcpy;
// "+2" below comes from the string terminator (+1) and the '\n'
// that will be added by the shell code (+1)
if( ( cmdcpy = ( char* )malloc( strlen( pcmd ) + 2 ) ) == NULL )
return luaL_error( L, "not enough memory for elua_shell" );
strcpy( cmdcpy, pcmd );
shellh_execute_command( cmdcpy, 0 );
free( cmdcpy );
return 0;
}
// Module function map
#define MIN_OPT_LEVEL 2
#include "lrodefs.h"
@ -67,6 +85,7 @@ const LUA_REG_TYPE elua_map[] =
{ LSTRKEY( "egc_setup" ), LFUNCVAL( elua_egc_setup ) },
{ LSTRKEY( "version" ), LFUNCVAL( elua_version ) },
{ LSTRKEY( "save_history" ), LFUNCVAL( elua_save_history ) },
{ LSTRKEY( "shell" ), LFUNCVAL( elua_shell ) },
#if LUA_OPTIMIZE_MEMORY > 0
{ LSTRKEY( "EGC_NOT_ACTIVE" ), LNUMVAL( EGC_NOT_ACTIVE ) },
{ LSTRKEY( "EGC_ON_ALLOC_FAILURE" ), LNUMVAL( EGC_ON_ALLOC_FAILURE ) },

View File

@ -143,7 +143,10 @@ static const DM_DEVICE std_device =
NULL, // readdir
NULL, // closedir
NULL, // getaddr
NULL // mkdir
NULL, // mkdir
NULL, // unlink
NULL, // rmdir
NULL // rename
};
int std_register()

View File

@ -94,7 +94,10 @@ static const DM_DEVICE std_device =
NULL, // readdir
NULL, // closedir
NULL, // getaddr
NULL // mkdir
NULL, // mkdir
NULL, // unlink
NULL, // rmdir
NULL // rename
};

View File

@ -14,6 +14,7 @@
#include "genstd.h"
#include "utils.h"
#include "salloc.h"
#include "shell.h"
#ifdef USE_MULTIPLE_ALLOCATOR
#include "dlmalloc.h"
@ -96,6 +97,11 @@ int _open_r( struct _reent *r, const char *name, int flags, int mode )
return DM_MAKE_DESC( devid, res );
}
int open( const char *name, int flags, mode_t mode )
{
return _open_r( _REENT, name, flags, 0 );
}
// *****************************************************************************
// _close_r
int _close_r( struct _reent *r, int file )
@ -114,6 +120,11 @@ int _close_r( struct _reent *r, int file )
return pinst->pdev->p_close_r( r, DM_GET_FD( file ), pinst->pdata );
}
int close( int file )
{
return _close_r( _REENT, file );
}
// *****************************************************************************
// _fstat_r (not implemented)
int _fstat_r( struct _reent *r, int file, struct stat *st )
@ -163,6 +174,11 @@ _ssize_t _read_r( struct _reent *r, int file, void *ptr, size_t len )
return pinst->pdev->p_read_r( r, DM_GET_FD( file ), ptr, len, pinst->pdata );
}
_ssize_t read( int file, void *ptr, size_t len )
{
return _read_r( _REENT, file, ptr, len );
}
// *****************************************************************************
// _write_r
_ssize_t _write_r( struct _reent *r, int file, const void *ptr, size_t len )
@ -181,12 +197,17 @@ _ssize_t _write_r( struct _reent *r, int file, const void *ptr, size_t len )
return pinst->pdev->p_write_r( r, DM_GET_FD( file ), ptr, len, pinst->pdata );
}
_ssize_t write( int file, const void *ptr, size_t len )
{
return _write_r( _REENT, file, ptr, len );
}
// ****************************************************************************
// _mkdir_r
int _mkdir_r( struct _reent *r, const char *path, mkdir_mode_t mode )
{
char* actname;
int res, devid;
int devid;
const DM_INSTANCE_DATA *pinst;
// Look for device, return error if not found or if function not implemented
@ -211,6 +232,99 @@ int mkdir( const char *path, mode_t mode )
return _mkdir_r( _REENT, path, mode );
}
// ****************************************************************************
// _unlink_r
int _unlink_r( struct _reent *r, const char *fname )
{
char* actname;
int devid;
const DM_INSTANCE_DATA *pinst;
// Look for device, return error if not found or if function not implemented
if( ( devid = find_dm_entry( fname, &actname ) ) == -1 )
{
r->_errno = ENODEV;
return -1;
}
pinst = dm_get_instance_at( devid );
if( pinst->pdev->p_unlink_r == NULL )
{
r->_errno = ENOSYS;
return -1;
}
// Device found, call its function
return pinst->pdev->p_unlink_r( r, actname, pinst->pdata );
}
int unlink( const char *path )
{
return _unlink_r( _REENT, path );
}
// ****************************************************************************
// rmdir
int rmdir( const char *path )
{
char* actname;
int devid;
const DM_INSTANCE_DATA *pinst;
// Look for device, return error if not found or if function not implemented
if( ( devid = find_dm_entry( path, &actname ) ) == -1 )
{
_REENT->_errno = ENODEV;
return -1;
}
pinst = dm_get_instance_at( devid );
if( pinst->pdev->p_rmdir_r == NULL )
{
_REENT->_errno = ENOSYS;
return -1;
}
// Device found, call its function
return pinst->pdev->p_rmdir_r( _REENT, actname, pinst->pdata );
}
// ****************************************************************************
// rename
int _rename_r( struct _reent *r, const char *oldname, const char *newname )
{
char *actname_old, *actname_new;
int devid_old, devid_new;
const DM_INSTANCE_DATA *pinst;
// Look for device, return error if not found or if function not implemented
if( ( devid_old = find_dm_entry( oldname, &actname_old ) ) == -1 )
{
r->_errno = ENODEV;
return -1;
}
if( ( devid_new = find_dm_entry( newname, &actname_new ) ) == -1 )
{
r->_errno = ENODEV;
return -1;
}
if( devid_old == devid_new )
{
pinst = dm_get_instance_at( devid_old );
if( pinst->pdev->p_rename_r == NULL )
{
r->_errno = EPERM;
return -1;
}
// Device found, call its function
return pinst->pdev->p_rename_r( r, actname_old, actname_new, pinst->pdata );
}
// Cannot rename between different devices (EXDEV)
r->_errno = EXDEV;
return -1;
}
// ****************************************************************************
// Miscellaneous functions
@ -245,12 +359,6 @@ clock_t _times_r( struct _reent* r, struct tms *buf )
return 0;
}
int _unlink_r( struct _reent *r, const char *name )
{
r->_errno = ENOSYS;
return -1;
}
int _link_r( struct _reent *r, const char *c1, const char *c2 )
{
r->_errno = ENOSYS;

View File

@ -12,6 +12,7 @@
// Define here what components you want for this platform
#define BUILD_SHELL
#define BUILD_ADVANCED_SHELL
#define BUILD_ROMFS
#define BUILD_CON_GENERIC
#define BUILD_TERM

View File

@ -181,7 +181,10 @@ static const DM_DEVICE rfs_device =
rfs_readdir_r, // readdir
rfs_closedir_r, // closedir
NULL, // getaddr
NULL // mkdir
NULL, // mkdir
NULL, // unlink
NULL, // rmdir
NULL // rename
};
int remotefs_init()

View File

@ -427,7 +427,10 @@ static const DM_DEVICE romfs_device =
romfs_readdir_r, // readdir
romfs_closedir_r, // closedir
romfs_getaddr_r, // getaddr
NULL // mkdir
NULL, // mkdir
NULL, // unlink
NULL, // rmdir
NULL // rename
};
// ****************************************************************************

View File

@ -259,7 +259,10 @@ static const DM_DEVICE semifs_device =
semifs_readdir_r, // readdir
semifs_closedir_r, // closedir
NULL, // getaddr
NULL // mkdir
NULL, // mkdir
NULL, // unlink
NULL, // rmdir
NULL // rename
};
int semifs_init()

View File

@ -1,596 +0,0 @@
// eLua shell
#include "shell.h"
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "xmodem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "platform.h"
#include "elua_net.h"
#include "devman.h"
#include "buf.h"
#include "remotefs.h"
#include "eluarpc.h"
#include "linenoise.h"
#include "term.h"
#include "romfs.h"
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined( USE_GIT_REVISION )
#include "git_version.h"
#else
#include "version.h"
#endif
#include "platform_conf.h"
#ifdef BUILD_SHELL
// Shell alternate ' ' char
#define SHELL_ALT_SPACE '\x07'
#define SHELL_MAX_ARGS 10
// EOF is different in UART mode and TCP/IP mode
#ifdef BUILD_CON_GENERIC
#define SHELL_EOF_STRING "CTRL+Z"
#else
#define SHELL_EOF_STRING "CTRL+D"
#endif
// Shell command handler function
typedef void( *p_shell_handler )( int argc, char **argv );
// Command/handler pair structure
typedef struct
{
const char* cmd;
p_shell_handler handler_func;
} SHELL_COMMAND;
// Shell data
static char* shell_prog;
// ****************************************************************************
// Shell functions
// 'help' handler
static void shell_help( int argc, char **argv )
{
( void )argc;
( void )argv;
printf( "Shell commands:\n" );
printf( " exit - exit from this shell\n" );
printf( " help - print this help\n" );
printf( " ls or dir - lists filesystems files and sizes\n" );
printf( " cat or type - lists file contents\n" );
printf( " lua [args] - run Lua with the given arguments\n" );
printf( " recv [path] - receive a file via XMODEM. If path is given save it there, otherwise run it.\n");
printf( " cp <src> <dst> - copy source file 'src' to 'dst'\n" );
printf( " wofmt - format the internal WOFS\n" );
printf( " ver - print eLua version\n" );
}
// 'lua' handler
static void shell_lua( int argc, char **argv )
{
printf( "Press " SHELL_EOF_STRING " to exit Lua\n" );
lua_main( argc, argv );
clearerr( stdin );
}
// 'recv' handler
static void shell_recv( int argc, char **argv )
{
#ifndef BUILD_XMODEM
printf( "XMODEM support not compiled, unable to recv\n" );
#else // #ifndef BUILD_XMODEM
char *p;
long actsize;
lua_State* L;
if( argc > 2 )
{
printf( "Usage: recv [path]\n" );
return;
}
if( ( shell_prog = malloc( XMODEM_INITIAL_BUFFER_SIZE ) ) == NULL )
{
printf( "Unable to allocate memory\n" );
return;
}
printf( "Waiting for file ... " );
if( ( actsize = xmodem_receive( &shell_prog ) ) < 0 )
{
free( shell_prog );
shell_prog = NULL;
if( actsize == XMODEM_ERROR_OUTOFMEM )
printf( "file too big\n" );
else
printf( "XMODEM error\n" );
return;
}
// Eliminate the XMODEM padding bytes
p = shell_prog + actsize - 1;
while( *p == '\x1A' )
p --;
p ++;
printf( "done, got %u bytes\n", ( unsigned )( p - shell_prog ) );
// we've received an argument, try saving it to a file
if( argc == 2 )
{
FILE *foutput = fopen( argv[ 1 ], "w" );
size_t file_sz = p - shell_prog;
if( foutput == NULL )
{
printf( "unable to open file %s\n", argv[ 1 ] );
free( shell_prog );
shell_prog = NULL;
return;
}
if( fwrite( shell_prog, sizeof( char ), file_sz, foutput ) == file_sz )
printf( "received and saved as %s\n", argv[ 1 ] );
else
printf( "unable to save file %s (no space left on target?)\n", argv[ 1 ] );
fclose( foutput );
}
else // no arg, running the file with lua.
{
if( ( L = lua_open() ) == NULL )
{
printf( "Unable to create Lua state\n" );
free( shell_prog );
shell_prog = NULL;
return;
}
luaL_openlibs( L );
if( luaL_loadbuffer( L, shell_prog, p - shell_prog, "xmodem" ) != 0 )
printf( "Error: %s\n", lua_tostring( L, -1 ) );
else
if( lua_pcall( L, 0, LUA_MULTRET, 0 ) != 0 )
printf( "Error: %s\n", lua_tostring( L, -1 ) );
lua_close( L );
}
free( shell_prog );
shell_prog = NULL;
#endif // #ifndef BUILD_XMODEM
}
// 'ver' handler
static void shell_ver( int argc, char **argv )
{
( void )argc;
( void )argv;
printf( "eLua version %s\n", ELUA_STR_VERSION );
printf( "For more information visit www.eluaproject.net and wiki.eluaproject.net\n" );
}
// ls helper: does the recursive path walk for '-R'
static u32 shell_ls_helper( const char *crtname, int recursive, int *phasdirs )
{
DM_DIR *d;
u32 total = 0;
struct dm_dirent *ent;
unsigned i;
char *fullname;
int ndirs = 0;
if( ( d = dm_opendir( crtname ) ) != NULL )
{
total = 0;
printf( "\n%s", crtname );
while( ( ent = dm_readdir( d ) ) != NULL )
{
printf( "\n%s", ent->fname );
for( i = strlen( ent->fname ); i <= DM_MAX_FNAME_LENGTH; i++ )
printf( " " );
if( ent->flags & DM_DIRENT_FLAG_DIR )
{
printf( "<DIR>" );
ndirs = ndirs + 1;
if( phasdirs )
*phasdirs = 1;
}
else
{
printf( "%u bytes", ( unsigned )ent->fsize );
total = total + ent->fsize;
}
}
dm_closedir( d );
printf( "\nTotal on %s: %u bytes\n", crtname, ( unsigned )total );
if( recursive && ( ndirs > 0 ) )
{
if( ( d = dm_opendir( crtname ) ) != NULL )
{
while( ( ent = dm_readdir( d ) ) != NULL )
{
if( ent->flags & DM_DIRENT_FLAG_DIR )
{
if( asprintf( &fullname, "%s/%s", crtname, ent->fname ) > 0 )
{
total += shell_ls_helper( fullname, 1, phasdirs );
free( fullname );
}
else
printf( "ERROR: unable to open directory '%s/%s' (not enough memory?)\n", crtname, ent->fname );
}
}
dm_closedir( d );
}
}
}
else
printf( "Error: unable to open directory '%s'", crtname );
return total;
}
// 'ls' and 'dir' handler
// Syntax: ls [dir] [-R]
static void shell_ls( int argc, char **argv )
{
const DM_INSTANCE_DATA *pinst;
unsigned dev;
u32 i;
int recursive = 0, hasdirs;
char *pname = NULL;
const char *crtname;
for( i = 1; i < argc; i ++ )
{
if( !strcmp( argv[ i ], "-R" ) )
recursive = 1;
else if( argv[ i ][ 0 ] == '/' )
pname = argv[ i ];
else
printf( "Warning: ignoring argument '%s' of ls", argv[ i ] );
}
// Iterate through all devices, looking for the ones that can do "opendir"
// or the ones that match 'pname' (if that is specified)
for( dev = 0; dev < dm_get_num_devices(); dev ++ )
{
pinst = dm_get_instance_at( dev );
if( pinst->pdev->p_opendir_r == NULL || pinst->pdev->p_readdir_r == NULL || pinst->pdev->p_closedir_r == NULL )
continue;
if( pname && strncmp( pinst->name, pname, strlen( pinst->name ) ) )
continue;
crtname = pname ? pname : pinst->name;
hasdirs = 0;
i = shell_ls_helper( crtname, recursive, &hasdirs );
if( recursive && hasdirs )
printf( "\nTotal on %s with all subdirectories: %u bytes\n", crtname, ( unsigned )i );
}
printf( "\n" );
}
// 'cat' and 'type' handler
static void shell_cat( int argc, char **argv )
{
FILE *fp;
int c;
unsigned i;
if( argc < 2 )
{
printf( "Usage: cat (or type) <filename1> [<filename2> ...]\n" );
return;
}
for( i = 1; i < argc; i ++ )
{
if( ( fp = fopen( argv[ i ] , "rb" ) ) != NULL )
{
c = fgetc( fp );
while( c != EOF )
{
printf("%c", (char) c );
c = fgetc( fp );
}
fclose ( fp );
}
else
printf( "Unable to open '%s'\n", argv[ i ] );
}
}
// 'copy' handler
#ifdef BUILD_RFS
#define SHELL_COPY_BUFSIZE ( ( 1 << RFS_BUFFER_SIZE ) - ELUARPC_WRITE_REQUEST_EXTRA )
#else
#define SHELL_COPY_BUFSIZE 256
#endif
static void shell_cp( int argc, char **argv )
{
FILE *fps = NULL, *fpd = NULL;
void *buf = NULL;
size_t datalen, datawrote, total = 0;
if( argc != 3 )
{
printf( "Usage: cp <source> <destination>\n" );
return;
}
if( ( fps = fopen( argv[ 1 ], "rb" ) ) == NULL )
printf( "Unable to open %s for reading\n", argv[ 1 ] );
else
{
if( ( fpd = fopen( argv[ 2 ], "wb" ) ) == NULL )
printf( "Unable to open %s for writing\n", argv[ 2 ] );
else
{
// Alloc memory
if( ( buf = malloc( SHELL_COPY_BUFSIZE ) ) == NULL )
printf( "Not enough memory\n" );
else
{
// Do the actual copy
while( 1 )
{
datalen = fread( buf, 1, SHELL_COPY_BUFSIZE, fps );
datawrote = fwrite( buf, 1, datalen, fpd );
if( datawrote < datalen )
{
printf( "Copy error (no space left on target?)\n" );
break;
}
total += datalen;
if( datalen < SHELL_COPY_BUFSIZE )
break;
}
fflush( fpd );
printf( "%u bytes copied\n", ( unsigned int )total );
}
}
}
if( fps )
fclose( fps );
if( fpd )
fclose( fpd );
if( buf )
free( buf );
}
// 'wofmt' handler
static void shell_wofmt( int argc, char **argv )
{
#ifndef BUILD_WOFS
printf( "WOFS not enabled.\n" );
#else // #ifndef BUILD_WOFS
int c;
printf( "Formatting the internal WOFS will DESTROY ALL THE FILES FROM WOFS.\n" );
while( 1 )
{
printf( "Are you sure you want to continue? [y/n] " );
c = term_getch( TERM_INPUT_WAIT );
printf( "%c\n", isprint( c ) ? c : ' ' );
c = tolower( c );
if( c == 'n' )
return;
else if( c == 'y' )
break;
}
printf( "Formatting ... " );
if( !wofs_format() )
{
printf( "\ni*** ERROR ***: unable to erase the internal flash. WOFS might be compromised.\n" );
printf( "It is advised to re-flash the eLua image.\n" );
}
else
printf( " done.\n" );
#endif // #ifndef BUILD_WOFS
}
// mkdir handler
static void shell_mkdir( int argc, char **argv )
{
if( argc != 2 )
{
printf( "Usage: mkdir <directory>\n" );
return;
}
if( mkdir( argv[ 1 ], 0 ) != 0 )
printf( "Error creating directory '%s'\n", argv[ 1 ] );
}
// Insert shell commands here
static const SHELL_COMMAND shell_commands[] =
{
{ "help", shell_help },
{ "lua", shell_lua },
{ "recv", shell_recv },
{ "ver", shell_ver },
{ "exit", NULL },
{ "ls", shell_ls },
{ "dir", shell_ls },
{ "cat", shell_cat },
{ "type", shell_cat },
{ "cp", shell_cp },
{ "wofmt", shell_wofmt },
{ "mkdir", shell_mkdir },
{ NULL, NULL }
};
// Execute the eLua "shell" in an infinite loop
void shell_start()
{
char cmd[ SHELL_MAXSIZE + 1 ];
char *p, *temp;
const SHELL_COMMAND* pcmd;
int i, inside_quotes;
char quote_char;
int argc;
char *argv[ SHELL_MAX_ARGS ];
printf( SHELL_WELCOMEMSG, ELUA_STR_VERSION );
while( 1 )
{
while( linenoise_getline( LINENOISE_ID_SHELL, cmd, SHELL_MAXSIZE - 1, SHELL_PROMPT ) == -1 )
{
printf( "\n" );
clearerr( stdin );
}
if( strlen( cmd ) == 0 )
continue;
linenoise_addhistory( LINENOISE_ID_SHELL, cmd );
if( cmd[ strlen( cmd ) - 1 ] != '\n' )
strcat( cmd, "\n" );
// Change '\r', '\n' and '\t' chars to ' ' to ease processing
p = cmd;
while( *p )
{
if( *p == '\r' || *p == '\n' || *p == '\t' )
*p = ' ';
p ++;
}
// Transform ' ' characters inside a '' or "" quoted string in
// a 'special' char. We do this to let the user execute something
// like "lua -e 'quoted string'" without disturbing the quoted
// string in any way.
for( i = 0, inside_quotes = 0, quote_char = '\0'; i < strlen( cmd ); i ++ )
if( ( cmd[ i ] == '\'' ) || ( cmd[ i ] == '"' ) )
{
if( !inside_quotes )
{
inside_quotes = 1;
quote_char = cmd[ i ];
}
else
{
if( cmd[ i ] == quote_char )
{
inside_quotes = 0;
quote_char = '\0';
}
}
}
else if( ( cmd[ i ] == ' ' ) && inside_quotes )
cmd[ i ] = SHELL_ALT_SPACE;
if( inside_quotes )
{
printf( "Invalid quoted string\n" );
continue;
}
// Transform consecutive sequences of spaces into a single space
p = strchr( cmd, ' ' );
while( p )
{
temp = p + 1;
while( *temp && *temp == ' ' )
memmove( temp, temp + 1, strlen( temp ) );
p = strchr( p + 1, ' ' );
}
if( !strcmp( cmd, " " ) )
continue;
// Skip over the initial space char if it exists
p = cmd;
if( *p == ' ' )
p ++;
// Add a final space if it does not exist
if( p[ strlen( p ) - 1 ] != ' ' )
strcat( p, " " );
// Compute argc/argv
for( argc = 0; argc < SHELL_MAX_ARGS; argc ++ )
argv[ argc ] = NULL;
argc = 0;
while( ( temp = strchr( p, ' ' ) ) != NULL )
{
*temp = 0;
if( argc == SHELL_MAX_ARGS )
{
printf( "Error: too many arguments\n" );
argc = -1;
break;
}
argv[ argc ++ ] = p;
p = temp + 1;
}
if( argc == -1 )
continue;
// Additional argument processing happens here
for( i = 0; i < argc; i ++ )
{
p = argv[ i ];
// Put back spaces if needed
for( inside_quotes = 0; inside_quotes < strlen( argv[ i ] ); inside_quotes ++ )
{
if( p[ inside_quotes ] == SHELL_ALT_SPACE )
argv[ i ][ inside_quotes ] = ' ';
}
// Remove quotes
if( ( p[ 0 ] == '\'' || p [ 0 ] == '"' ) && ( p[ 0 ] == p[ strlen( p ) - 1 ] ) )
{
argv[ i ] = p + 1;
p[ strlen( p ) - 1 ] = '\0';
}
}
// Match user command with shell's commands
i = 0;
while( 1 )
{
pcmd = shell_commands + i;
if( pcmd->cmd == NULL )
{
printf( SHELL_ERRMSG );
break;
}
if( !strcasecmp( pcmd->cmd, argv[ 0 ] ) )
{
// Special case: the "exit" command has a NULL handler
if( pcmd->handler_func )
pcmd->handler_func( argc, argv );
break;
}
i ++;
}
// Check for 'exit' command
if( pcmd->cmd && !pcmd->handler_func )
#ifdef BUILD_UIP
{
if( ( i = elua_net_get_telnet_socket() ) != -1 )
elua_net_close( i );
}
#else
break;
#endif
}
// Shell exit point
if( shell_prog )
free( shell_prog );
}
// Initialize the shell, returning 1 for OK and 0 for error
int shell_init()
{
shell_prog = NULL;
return 1;
}
#else // #ifdef BUILD_SHELL
int shell_init()
{
return 0;
}
void shell_start()
{
}
#endif // #ifdef BUILD_SHELL

415
src/shell/shell.c Normal file
View File

@ -0,0 +1,415 @@
// eLua shell
#include "shell.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "platform.h"
#include "elua_net.h"
#include "linenoise.h"
#include "term.h"
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include "common.h"
#include "platform_conf.h"
#ifdef BUILD_SHELL
#if defined( USE_GIT_REVISION )
#include "git_version.h"
#else
#include "version.h"
#endif
// Shell alternate ' ' char
#define SHELL_ALT_SPACE '\x07'
#define SHELL_MAX_ARGS 10
// External shell function declaration
#define SHELL_FUNC( func ) extern void func( int argc, char **argv )
// Shell data
char* shell_prog;
// Extern implementations of shell functions
SHELL_FUNC( shell_ls );
SHELL_FUNC( shell_cp );
SHELL_FUNC( shell_adv_mv );
SHELL_FUNC( shell_adv_rm );
SHELL_FUNC( shell_recv );
SHELL_FUNC( shell_help );
SHELL_FUNC( shell_cat );
SHELL_FUNC( shell_lua );
SHELL_FUNC( shell_ver );
SHELL_FUNC( shell_mkdir );
SHELL_FUNC( shell_wofmt );
// ----------------------------------------------------------------------------
// Helpers
// Helper: ask yes/no
// Returns 1 for yes, 0 for no
int shellh_ask_yes_no( const char *prompt )
{
int c;
if( prompt )
printf( "%s ", prompt );
while( 1 )
{
c = term_getch( TERM_INPUT_WAIT );
if( c == 'y' || c == 'Y' )
{
printf( "y\n" );
return 1;
}
if( c == 'n' || c == 'N' )
{
printf( "n\n" );
return 0;
}
}
// Will never get here
return 0;
}
#ifdef BUILD_RFS
#define SHELL_COPY_BUFSIZE ( ( 1 << RFS_BUFFER_SIZE ) - ELUARPC_WRITE_REQUEST_EXTRA )
#else
#define SHELL_COPY_BUFSIZE 256
#endif
// Dummy log function
static int shellh_dummy_printf( const char *fmt, ... )
{
return 0;
}
typedef int ( *p_logf )( const char *fmt, ... );
// Helper: copy one file to another file
// Return 1 for success, 0 for error
int shellh_cp_file( const char *psrcname, const char *pdestname, int flags )
{
int fds = -1, fdd = -1;
int res = 0;
char *buf = NULL;
ssize_t datalen, datawrote;
u32 total = 0;
p_logf plog = ( flags & SHELL_F_SILENT ) ? shellh_dummy_printf : printf;
if( !strcasecmp( psrcname, pdestname ) )
{
plog( "Cannot copy '%s' into itself.\n", psrcname );
goto done;
}
// If operation confirmation is enabled, ask the user first
if( flags & SHELL_F_ASK_CONFIRMATION )
{
printf( "Copy '%s' to '%s' ? [y/n] ", psrcname, pdestname );
if( shellh_ask_yes_no( NULL ) == 0 )
goto done;
}
// Open source file
if( ( fds = open( psrcname, O_RDONLY, 0 ) ) == -1 )
{
plog( "Error: unable to open source file '%s'\n", psrcname );
goto done;
}
// If the destination exists and we need to ask for confirmation, do it now
if( ( flags & SHELL_F_FORCE_DESTINATION ) == 0 )
{
if( ( fdd = open( pdestname, O_RDONLY, 0 ) ) != -1 )
{
close( fdd );
fdd = -1;
printf( "Destination '%s' already exists, are you sure you want to overwrite it ? [y/n] ", pdestname );
if( shellh_ask_yes_no( NULL ) == 0 )
goto done;
}
}
// Allocate buffer
if( ( buf = ( char* )malloc( SHELL_COPY_BUFSIZE ) ) == NULL )
{
plog( "ERROR: unable to allocate buffer for copy operation.\n" );
goto done;
}
plog( "Copying '%s' to '%s' ... ", psrcname, pdestname );
if( ( flags & SHELL_F_SIMULATE_ONLY ) == 0 )
{
// Open destination file
if( ( fdd = open( pdestname, O_WRONLY | O_CREAT | O_TRUNC, 0 ) ) == -1 )
{
plog( "ERROR: unable to open '%s' for writing.\n", pdestname );
goto done;
}
// Do the actual copy
while( 1 )
{
if( ( datalen = read( fds, buf, SHELL_COPY_BUFSIZE ) ) == -1 )
{
plog( "Error reading source file '%s'.\n", psrcname );
goto done;
}
if( ( datawrote = write( fdd, buf, datalen ) ) == -1 )
{
plog( "Error writing destination file '%s'.\n", pdestname );
goto done;
}
if( datawrote < datalen )
{
plog( "Copy error (no space left on target?)\n" );
goto done;
}
total += datalen;
if( datalen < SHELL_COPY_BUFSIZE )
break;
}
}
plog( "done (%u bytes).\n", ( unsigned )total );
res = 1;
done:
if( fds != -1 )
close( fds );
if( fdd != -1 )
close( fdd );
if( buf )
free( buf );
return res;
}
// 'Not implemented' handler for shell comands
void shellh_not_implemented_handler( int argc, char **argv )
{
printf( SHELL_ERRMSG );
}
// Shows the help for the given command
void shellh_show_help( const char *cmd, const char *helptext )
{
printf( "Usage: %s %s", cmd, helptext );
}
// ****************************************************************************
// Public interface
// Insert shell commands here
static const SHELL_COMMAND shell_commands[] =
{
{ "help", shell_help },
{ "lua", shell_lua },
{ "recv", shell_recv },
{ "ver", shell_ver },
{ "exit", NULL },
{ "ls", shell_ls },
{ "dir", shell_ls },
{ "cat", shell_cat },
{ "type", shell_cat },
{ "cp", shell_cp },
{ "wofmt", shell_wofmt },
{ "mkdir", shell_mkdir },
{ "rm", shell_adv_rm },
{ "mv", shell_adv_mv },
{ NULL, NULL }
};
// Executes the given shell command
// 'interactive_mode' is 1 if invoked directly from the interactive shell,
// 0 otherwise
// Returns a pointer to the shell_command that was executed, NULL for error
const SHELL_COMMAND* shellh_execute_command( char* cmd, int interactive_mode )
{
char *p, *temp;
const SHELL_COMMAND* pcmd;
int i, inside_quotes;
char quote_char;
int argc;
char *argv[ SHELL_MAX_ARGS ];
if( strlen( cmd ) == 0 )
return NULL;
if( cmd[ strlen( cmd ) - 1 ] != '\n' )
strcat( cmd, "\n" );
// Change '\r', '\n' and '\t' chars to ' ' to ease processing
p = cmd;
while( *p )
{
if( *p == '\r' || *p == '\n' || *p == '\t' )
*p = ' ';
p ++;
}
// Transform ' ' characters inside a '' or "" quoted string in
// a 'special' char. We do this to let the user execute something
// like "lua -e 'quoted string'" without disturbing the quoted
// string in any way.
for( i = 0, inside_quotes = 0, quote_char = '\0'; i < strlen( cmd ); i ++ )
if( ( cmd[ i ] == '\'' ) || ( cmd[ i ] == '"' ) )
{
if( !inside_quotes )
{
inside_quotes = 1;
quote_char = cmd[ i ];
}
else
{
if( cmd[ i ] == quote_char )
{
inside_quotes = 0;
quote_char = '\0';
}
}
}
else if( ( cmd[ i ] == ' ' ) && inside_quotes )
cmd[ i ] = SHELL_ALT_SPACE;
if( inside_quotes )
{
printf( "Invalid quoted string\n" );
return NULL;
}
// Transform consecutive sequences of spaces into a single space
p = strchr( cmd, ' ' );
while( p )
{
temp = p + 1;
while( *temp && *temp == ' ' )
memmove( temp, temp + 1, strlen( temp ) );
p = strchr( p + 1, ' ' );
}
if( !strcmp( cmd, " " ) )
return NULL;
// Skip over the initial space char if it exists
p = cmd;
if( *p == ' ' )
p ++;
// Add a final space if it does not exist
if( p[ strlen( p ) - 1 ] != ' ' )
strcat( p, " " );
// Compute argc/argv
for( argc = 0; argc < SHELL_MAX_ARGS; argc ++ )
argv[ argc ] = NULL;
argc = 0;
while( ( temp = strchr( p, ' ' ) ) != NULL )
{
*temp = 0;
if( argc == SHELL_MAX_ARGS )
{
printf( "Error: too many arguments\n" );
argc = -1;
break;
}
argv[ argc ++ ] = p;
p = temp + 1;
}
if( argc == -1 )
return NULL;
// Additional argument processing happens here
for( i = 0; i < argc; i ++ )
{
p = argv[ i ];
// Put back spaces if needed
for( inside_quotes = 0; inside_quotes < strlen( argv[ i ] ); inside_quotes ++ )
{
if( p[ inside_quotes ] == SHELL_ALT_SPACE )
argv[ i ][ inside_quotes ] = ' ';
}
// Remove quotes
if( ( p[ 0 ] == '\'' || p [ 0 ] == '"' ) && ( p[ 0 ] == p[ strlen( p ) - 1 ] ) )
{
argv[ i ] = p + 1;
p[ strlen( p ) - 1 ] = '\0';
}
}
// Match user command with shell's commands
i = 0;
while( 1 )
{
pcmd = shell_commands + i;
if( pcmd->cmd == NULL )
{
printf( SHELL_ERRMSG );
break;
}
if( !strcasecmp( pcmd->cmd, argv[ 0 ] ) )
{
// Special case: the "exit" command has a NULL handler
// Special case: "lua" is not allowed in non-interactive mode
if( pcmd->handler_func && ( interactive_mode || strcasecmp( pcmd->cmd, "lua" ) ) )
pcmd->handler_func( argc, argv );
break;
}
i ++;
}
// Special case: "exit" is not allowed in non-interactive mode
if( !interactive_mode && !strcasecmp( pcmd->cmd, "exit" ) )
return NULL;
return pcmd;
}
// Execute the eLua "shell" in an infinite loop
void shell_start()
{
char cmd[ SHELL_MAXSIZE + 1 ];
const SHELL_COMMAND *pcmd;
int i;
printf( SHELL_WELCOMEMSG, ELUA_STR_VERSION );
while( 1 )
{
while( linenoise_getline( LINENOISE_ID_SHELL, cmd, SHELL_MAXSIZE - 1, SHELL_PROMPT ) == -1 )
{
printf( "\n" );
clearerr( stdin );
}
if( strlen( cmd ) == 0 )
continue;
linenoise_addhistory( LINENOISE_ID_SHELL, cmd );
pcmd = shellh_execute_command( cmd, 1 );
// Check for 'exit' command
if( pcmd && pcmd->cmd && !pcmd->handler_func )
#ifdef BUILD_UIP
{
if( ( i = elua_net_get_telnet_socket() ) != -1 )
elua_net_close( i );
}
#else
break;
#endif
}
// Shell exit point
if( shell_prog )
free( shell_prog );
}
// Initialize the shell, returning 1 for OK and 0 for error
int shell_init()
{
shell_prog = NULL;
return 1;
}
#else // #ifdef BUILD_SHELL
int shell_init()
{
return 0;
}
void shell_start()
{
}
#endif // #ifdef BUILD_SHELL

295
src/shell/shell_adv_cp_mv.c Normal file
View File

@ -0,0 +1,295 @@
// Advanced shell: 'cp' and 'mv' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#ifdef BUILD_ADVANCED_SHELL
typedef struct
{
const char *pdestdir;
const char *psrcdir;
const char *dloc;
u8 flags;
} SHELL_CP_STATE;
const char shell_help_cp[] = "<source> <destination> [-R] [-f] [-c] [-s]\n"
" <source>: source file/directory/file mask.\n"
" <destination>: destination file/directory.\n"
" [-R]: recursive\n"
" [-f]: force destination override (default is to ask confirmation).\n"
" [-c]: confirm each operation.\n"
" [-s]: simulate only (no actual operation).\n";
const char shell_help_summary_cp[] = "copy files";
#define shell_help_mv shell_help_cp
const char shell_help_summary_mv[] = "move/rename files";
int shellh_cp_or_mv_file( const char *psrc, const char *pdest, int flags )
{
if( flags & SHELL_F_MOVE )
{
if( rename( psrc, pdest ) == -1 )
{
if( errno != EXDEV )
{
printf( "Unable to rename '%s'.\n", psrc );
return 0;
}
}
else
{
printf( "Moved '%s' to '%s'.\n", psrc, pdest );
return 1;
}
}
if( !shellh_cp_file( psrc, pdest, flags ) )
return 0;
if( flags & SHELL_F_MOVE )
{
if( unlink( psrc ) == -1 )
{
printf( "Unable to remove original file '%s'.\n", psrc );
return 0;
}
}
return 1;
}
// copy/move callback
static int shellh_cp_walkdir_cb( const char *path, const struct dm_dirent *pent, void *pdata, int info )
{
SHELL_CP_STATE *ps = ( SHELL_CP_STATE* )pdata;
char *tmp = NULL, *tmp2 = NULL;
int res = 1;
DM_DIR *d = NULL;
switch( info )
{
case CMN_FS_INFO_BEFORE_READDIR:
if( strstr( path, ps->psrcdir ) != path )
{
printf( "ERROR: unable to handle directory '%s' (internal error?), aborting.\n", path );
goto done_err;
}
// Need to create this directory if it does not exist
if( ( tmp = ( char* )cmn_fs_path_join( ps->pdestdir, path + strlen( ps->psrcdir ) - strlen( ps->dloc ), NULL ) ) == NULL )
{
printf( "Not enough memory.\n" );
goto done_err;
}
if( ( d = dm_opendir( tmp ) ) != NULL )
goto done;
printf( "Creating directory %s ... ", tmp );
if( ( ps->flags & SHELL_F_SIMULATE_ONLY ) == 0 )
{
if( mkdir( tmp, 0 ) == -1 )
{
printf( "ERROR! (aborting).\n" );
goto done_err;
}
else
printf( "done.\n" );
}
else
printf( "done.\n" );
goto done;
case CMN_FS_INFO_INSIDE_READDIR:
if( !DM_DIRENT_IS_DIR( pent ) )
{
if( strstr( path, ps->psrcdir ) != path )
{
printf( "ERROR: unable to handle directory '%s' (internal error?), aborting.\n", path );
goto done_err;
}
if( ( tmp = cmn_fs_path_join( path, pent->fname, NULL ) ) == NULL )
{
printf( "Not enough memory.\n" );
goto done_err;
}
if( ( tmp2 = cmn_fs_path_join( ps->pdestdir, path + strlen( ps->psrcdir ) - strlen( ps->dloc ), pent->fname, NULL ) ) == NULL )
{
printf( "Not enough memory.\n" );
goto done_err;
}
shellh_cp_or_mv_file( tmp, tmp2, ps->flags );
}
goto done;
case CMN_FS_INFO_OPENDIR_FAILED:
printf( "ERROR: unable to read directory '%s', aborting.\n", path );
goto done_err;
default:
goto done;
}
done_err:
res = 0;
done:
if( tmp )
free( tmp );
if( tmp2 )
free( tmp2 );
if( d )
dm_closedir( d );
return res;
}
static void shellh_adv_cp_mv_common( int argc, char **argv, int is_move )
{
const char *srcpath = NULL, *dstpath = NULL;
unsigned i, flags = is_move ? SHELL_F_MOVE : 0;
int srctype, dsttype;
char *srcdir = NULL, *dstdir = NULL, *tmp = NULL;
const char *srcfile, *dstfile;
SHELL_CP_STATE state;
if( argc < 3 )
{
if( is_move )
SHELL_SHOW_HELP( mv );
else
SHELL_SHOW_HELP( cp );
return;
}
for( i = 1; i < argc; i ++ )
{
if( !strcmp( argv[ i ], "-R" ) )
flags |= SHELL_F_RECURSIVE;
else if( !strcmp( argv[ i ], "-f" ) )
flags |= SHELL_F_FORCE_DESTINATION;
else if( !strcmp( argv[ i ], "-c" ) )
flags |= SHELL_F_ASK_CONFIRMATION;
else if( !strcmp( argv[ i ], "-s" ) )
flags |= SHELL_F_SIMULATE_ONLY;
else if( argv[ i ][ 0 ] == '/' )
{
if( !srcpath )
srcpath = argv[ i ];
else if( !dstpath )
dstpath = argv[ i ];
else
printf( "WARNING: ignoring argument '%s'\n", argv[ i ] );
}
else
printf( "WARNING: ignoring argument '%s'\n", argv[ i ] );
}
if( !srcpath || !dstpath )
{
printf( "Source and/or destination not specified.\n" );
return;
}
srctype = cmn_fs_get_type( srcpath );
if( ( dsttype = cmn_fs_get_type( dstpath ) ) == CMN_FS_TYPE_PATTERN )
{
printf( "Invalid destination '%s'.\n", dstpath );
goto done;
}
if( srctype == CMN_FS_TYPE_ERROR || srctype == CMN_FS_TYPE_FILE_NOT_FOUND ||
srctype == CMN_FS_TYPE_DIR_NOT_FOUND || srctype == CMN_FS_TYPE_UNKNOWN_NOT_FOUND ||
dsttype == CMN_FS_TYPE_ERROR || dsttype == CMN_FS_TYPE_DIR_NOT_FOUND )
{
printf( "%d %d\n", srctype, dsttype );
printf( "Invalid source and/or destination.\n" );
return;
}
srcdir = cmn_fs_split_path( srcpath, &srcfile );
dstdir = cmn_fs_split_path( dstpath, &dstfile );
// Check valid source/destination combinations
if( srctype == CMN_FS_TYPE_FILE )
{
if( dsttype == CMN_FS_TYPE_FILE || dsttype == CMN_FS_TYPE_FILE_NOT_FOUND || dsttype == CMN_FS_TYPE_UNKNOWN_NOT_FOUND ) // direct file-to-file operation
{
shellh_cp_or_mv_file( srcpath, dstpath, flags );
goto done;
}
else if( dsttype == CMN_FS_TYPE_DIR ) // copy/move to destination dir with the same name
{
if( ( tmp = cmn_fs_path_join( dstdir, srcfile, NULL ) ) == NULL )
{
printf( "Not enough memory.\n" );
goto done;
}
shellh_cp_or_mv_file( srcpath, tmp, flags );
goto done;
}
else
{
printf( "Invalid destination.\n" );
goto done;
}
}
else
{
if( dsttype == CMN_FS_TYPE_FILE || dsttype == CMN_FS_TYPE_FILE_NOT_FOUND )
{
printf( "Invalid destination '%s'.\n", dstpath );
goto done;
}
memset( &state, 0, sizeof( state ) );
state.dloc = NULL;
if( ( flags & SHELL_F_RECURSIVE ) != 0 )
state.dloc = strrchr( srcdir, '/' );
if( state.dloc == NULL )
state.dloc = "";
state.flags = flags;
state.pdestdir = dstdir;
state.psrcdir = srcdir;
cmn_fs_walkdir( srcpath, shellh_cp_walkdir_cb, &state, flags & SHELL_F_RECURSIVE );
}
done:
if( srcdir )
free( srcdir );
if( dstdir )
free( dstdir );
if( tmp )
free( tmp );
}
void shell_cp( int argc, char **argv )
{
shellh_adv_cp_mv_common( argc, argv, 0 );
}
void shell_adv_mv( int argc, char **argv )
{
shellh_adv_cp_mv_common( argc, argv, 1 );
}
#else // #ifdef BUILD_ADVANCED_SHELL
const char shell_help_cp[] = "cp <source> <destination>\n"
" <source>: source file/directory/file mask.\n"
" <destination>: destination file/directory.\n";
const char shell_help_summary_cp[] = "copy files";
const char shell_help_mv[] = "";
const char shell_help_summary_mv[] = "";
void shell_cp( int argc, char **argv )
{
if( argc != 3 )
{
SHELL_SHOW_HELP( cp );
return;
}
shellh_cp_file( argv[ 1 ], argv[ 2 ], 0 );
}
void shell_adv_mv( int argc, char **argv )
{
shellh_not_implemented_handler( argc, argv );
}
#endif // #ifdef BUILD_ADVANCED_SHELL

153
src/shell/shell_adv_rm.c Normal file
View File

@ -0,0 +1,153 @@
// Advanced shell: 'rm' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#ifdef BUILD_ADVANCED_SHELL
const char shell_help_rm[] = "<filemask> [-R] [-c] [-s]\n"
" <filemask>: file, directory or file mask to remove.\n"
" -R: remove recursively.\n"
" -c: confirm each remove.\n"
" -s: simulate only (no actual operation).\n";
const char shell_help_summary_rm[] = "remove files";
// helper: remove a single file and/or directory
static void shellh_rm_one( const char* path, int flags )
{
int ftype = cmn_fs_get_type( path );
int res = 0;
if( flags & SHELL_F_ASK_CONFIRMATION )
{
printf( "Are you sure you want to remove %s ? [y/n] ", path );
if( shellh_ask_yes_no( NULL ) == 0 )
return;
}
if( ( flags & SHELL_F_SIMULATE_ONLY ) == 0 )
{
if( ftype == CMN_FS_TYPE_FILE )
res = unlink( path );
else if( ftype == CMN_FS_TYPE_DIR )
res = rmdir( path );
else
{
printf( "WARNING: invalid argument '%s'\n", path );
return;
}
}
if( res )
{
if( ( flags & SHELL_F_SILENT ) == 0 )
printf( "WARNING: unable to remove %s\n", path );
}
else
printf( "Removed %s\n", path );
}
static int shellh_rm_walkdir_cb( const char *path, const struct dm_dirent *pent, void *pdata, int info )
{
u8 *pflags = ( u8* )pdata;
char *tmp = NULL;
int res = 1;
switch( info )
{
case CMN_FS_INFO_BEFORE_READDIR:
goto done;
case CMN_FS_INFO_INSIDE_READDIR:
if( ( tmp = cmn_fs_path_join( path, pent->fname, NULL ) ) == NULL )
{
printf( "Not enough memory.\n" );
goto done_err;
}
if( cmn_fs_get_type( tmp ) == CMN_FS_TYPE_FILE )
shellh_rm_one( tmp, *pflags );
goto done;
case CMN_FS_INFO_OPENDIR_FAILED:
printf( "ERROR: unable to read directory '%s', aborting.\n", path );
goto done_err;
case CMN_FS_INFO_DIRECTORY_DONE:
if( ( *pflags & SHELL_F_RECURSIVE ) && !cmn_fs_is_root_dir( path ) )
shellh_rm_one( path, *pflags | SHELL_F_SILENT );
goto done;
default:
goto done;
}
done_err:
res = 0;
done:
if( tmp )
free( tmp );
return res;
}
void shell_adv_rm( int argc, char **argv )
{
const char *fmask = NULL;
unsigned i, flags = 0;
int masktype;
if( argc < 2 )
{
SHELL_SHOW_HELP( rm );
return;
}
for( i = 1; i < argc; i ++ )
{
if( argv[ i ][ 0 ] == '/' )
{
if( !fmask )
fmask = argv[ i ];
else
printf( "Warning: ignoring argument '%s'\n", argv[ i ] );
}
else if( !strcmp( argv[ i ], "-R" ) )
flags |= SHELL_F_RECURSIVE;
else if( !strcmp( argv[ i ], "-c" ) )
flags |= SHELL_F_ASK_CONFIRMATION;
else if( !strcmp( argv[ i ], "-s" ) )
flags |= SHELL_F_SIMULATE_ONLY;
else
printf( "Warning: ignoring argument '%s'\n", argv[ i ] );
}
if( !fmask )
{
printf( "rm target not specified.\n" );
return;
}
masktype = cmn_fs_get_type( fmask );
if( masktype == CMN_FS_TYPE_FILE )
shellh_rm_one( fmask, flags );
else if( masktype == CMN_FS_TYPE_ERROR || masktype == CMN_FS_TYPE_FILE_NOT_FOUND || masktype == CMN_FS_TYPE_DIR_NOT_FOUND || masktype == CMN_FS_TYPE_UNKNOWN_NOT_FOUND )
printf( "Invalid argument '%s'.\n", fmask );
else if( masktype == CMN_FS_TYPE_DIR && ( ( flags & SHELL_F_RECURSIVE ) == 0 ) )
printf( "'%s': unable to remove directory (use '-R').\n", fmask );
else
cmn_fs_walkdir( fmask, shellh_rm_walkdir_cb, &flags, flags & SHELL_F_RECURSIVE );
}
#else // #ifdef BUILD_ADVANCED_SHELL
const char shell_help_rm[] = "";
const char shell_help_summary_rm[] = "";
void shell_adv_rm( int argc, char **argv )
{
shellh_not_implemented_handler( argc, argv );
}
#endif // #ifdef BUILD_ADVANCED_SHELL

47
src/shell/shell_cat.c Normal file
View File

@ -0,0 +1,47 @@
// Shell: 'cat' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
const char shell_help_cat[] = "<file> [<file2>] ... [<filen>]"
" <file>: the file to list.\n"
" [<file2>] ... [<filen>]: other files to list.\n";
const char shell_help_summary_cat[] = "list the contents of a file";
void shell_cat( int argc, char **argv )
{
FILE *fp;
int c;
unsigned i;
if( argc < 2 )
{
shellh_show_help( argv[ 0 ], shell_help_cat );
return;
}
for( i = 1; i < argc; i ++ )
{
if( ( fp = fopen( argv[ i ] , "rb" ) ) != NULL )
{
c = fgetc( fp );
while( c != EOF )
{
printf("%c", (char) c );
c = fgetc( fp );
}
fclose ( fp );
}
else
printf( "Unable to open '%s'\n", argv[ i ] );
}
}

113
src/shell/shell_help.c Normal file
View File

@ -0,0 +1,113 @@
// Shell: 'help' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
// External help text declaration
#define SHELL_HELP( topic ) extern const char shell_help_##topic[];\
extern const char shell_help_summary_##topic[]
#define SHELL_INFO( cmd ) { #cmd, shell_help_summary_##cmd, shell_help_##cmd }
#define SHELL_INFO_ALIAS( cmd, alias ) { #cmd, shell_help_summary_##alias, shell_help_##alias }
// Help data
typedef struct
{
const char *cmd;
const char *help_summary;
const char *help_full;
} SHELL_HELP_DATA;
SHELL_HELP( cp );
SHELL_HELP( rm );
SHELL_HELP( ls );
SHELL_HELP( recv );
SHELL_HELP( cat );
SHELL_HELP( lua );
SHELL_HELP( ver );
SHELL_HELP( mkdir );
SHELL_HELP( wofmt );
// 'mv' is special, as it uses the main help text from 'cp'
extern const char shell_help_summary_mv[];
// 'Help' help data is local for ovious reasons
static const char shell_help_help[] = "[<command>]\n"
" [<command>] - the command to get help on.\n"
"Without arguments it shows a summary of all the shell commands.\n";
static const char shell_help_summary_help[] = "shell help";
// Also put the help for 'exit' here
static const char shell_help_exit[] = "\n"
"Exits the shell.\n";
static const char shell_help_summary_exit[] = "exit the shell";
static const SHELL_HELP_DATA shell_help_data[] =
{
SHELL_INFO( help ),
SHELL_INFO( lua ),
SHELL_INFO( ls ),
SHELL_INFO_ALIAS( dir, ls ),
SHELL_INFO( cat ),
SHELL_INFO_ALIAS( type, cat ),
SHELL_INFO( recv ),
SHELL_INFO( cp ),
// Yes, 'mv' is still special
{ "mv", shell_help_summary_mv, shell_help_cp },
SHELL_INFO( rm ),
SHELL_INFO( ver ),
SHELL_INFO( mkdir ),
SHELL_INFO( wofmt ),
SHELL_INFO( exit ),
{ NULL, NULL, NULL }
};
void shell_help( int argc, char **argv )
{
const SHELL_HELP_DATA *ph;
if( argc > 2 )
{
SHELL_SHOW_HELP( help );
return;
}
ph = shell_help_data;
if( argc == 1 )
{
// List commands and their summary
// It is assumed that a command with an empty summary does not
// actually exist (helpful for conditional compilation)
printf( "Shell commands:\n" );
while( 1 )
{
if( ph->cmd == NULL )
break;
if( strlen( ph->help_summary ) > 0 )
printf( " %-6s - %s\n", ph->cmd, ph->help_summary );
ph ++;
}
printf( "For more information use 'help <command>'.\n" );
}
else
{
while( 1 )
{
if( ph->cmd == NULL )
break;
if( !strcmp( ph->cmd, argv[ 1 ] ) && strlen( ph->help_summary ) > 0 )
{
printf( "%s - %s\nUsage: %s %s", ph->cmd, ph->help_summary, ph->cmd, ph->help_full );
return;
}
ph ++;
}
printf( "Unknown command '%s'.\n", argv[ 1 ] );
}
}

151
src/shell/shell_ls.c Normal file
View File

@ -0,0 +1,151 @@
// Shell: 'ls' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#ifdef BUILD_ADVANCED_SHELL
// State for walkdir
typedef struct
{
u32 dir_total;
u32 total;
u8 ndirs;
} SHELL_LS_STATE;
const char shell_help_ls[] = "[<path>] [-R]\n"
" [<path>]: path to list.\n"
" [-R]: recursive\n";
const char shell_help_summary_ls[] = "lists files and directories";
// 'ls' and 'dir' handler
// Syntax: ls [dir] [-R]
// directory walker callback
static int shellh_ls_walkdir_cb( const char *path, const struct dm_dirent *pent, void *pdata, int info )
{
SHELL_LS_STATE *ps = ( SHELL_LS_STATE* )pdata;
switch( info )
{
case CMN_FS_INFO_BEFORE_READDIR:
ps->dir_total = 0;
printf( "%s\n", path );
if( ps->ndirs != 0xFF )
ps->ndirs ++;
break;
case CMN_FS_INFO_INSIDE_READDIR:
printf( " %-30s", pent->fname );
if( DM_DIRENT_IS_DIR( pent ) )
printf( "<DIR>\n" );
else
{
printf( "%u bytes\n", ( unsigned )pent->fsize );
ps->dir_total += pent->fsize;
}
break;
case CMN_FS_INFO_AFTER_CLOSEDIR:
printf( "Total on %s: %u bytes\n\n", path, ( unsigned )ps->dir_total );
ps->total += ps->dir_total;
break;
case CMN_FS_INFO_OPENDIR_FAILED:
printf( "WARNING: unable to open %s\n", path );
break;
}
return 1;
}
void shell_ls( int argc, char **argv )
{
const DM_INSTANCE_DATA *pinst;
unsigned i;
int recursive = 0;
char *pname = NULL;
const char *crtname;
SHELL_LS_STATE state;
for( i = 1; i < argc; i ++ )
{
if( !strcmp( argv[ i ], "-R" ) )
recursive = 1;
else if( argv[ i ][ 0 ] == '/' && !pname )
pname = argv[ i ];
else
printf( "Warning: ignoring argument '%s' of ls\n", argv[ i ] );
}
// Iterate through all devices, looking for the ones that can do "opendir"
// or the ones that match 'pname' (if that is specified)
for( i = 0; i < dm_get_num_devices(); i ++ )
{
pinst = dm_get_instance_at( i );
if( pinst->pdev->p_opendir_r == NULL || pinst->pdev->p_readdir_r == NULL || pinst->pdev->p_closedir_r == NULL )
continue;
if( pname && strncmp( pinst->name, pname, strlen( pinst->name ) ) )
continue;
crtname = pname ? pname : pinst->name;
memset( &state, 0, sizeof( state ) );
cmn_fs_walkdir( crtname, shellh_ls_walkdir_cb, &state, recursive );
if( recursive && ( state.ndirs > 1 ) )
printf( "Total on %s with all subdirectories: %u bytes\n\n", crtname, ( unsigned )state.total );
}
}
#else // #ifdef BUILD_ADVANCED_SHELL
const char shell_help_ls[] = "list files and directories";
const char shell_help_summary_ls[] = "lists files and directories";
void shell_ls( int argc, char **argv )
{
const DM_INSTANCE_DATA *pinst;
unsigned dev, i;
DM_DIR *d;
struct dm_dirent *ent;
u32 total;
( void )argc;
( void )argv;
// Iterate through all devices, looking for the ones that can do "opendir"
for( dev = 0; dev < dm_get_num_devices(); dev ++ )
{
pinst = dm_get_instance_at( dev );
if( pinst->pdev->p_opendir_r == NULL || pinst->pdev->p_readdir_r == NULL || pinst->pdev->p_closedir_r == NULL )
continue;
d = dm_opendir( pinst->name );
if( d )
{
total = 0;
printf( "\n%s", pinst->name );
while( ( ent = dm_readdir( d ) ) != NULL )
{
printf( "\n%s", ent->fname );
for( i = strlen( ent->fname ); i <= DM_MAX_FNAME_LENGTH; i++ )
printf( " " );
if( ent->flags & DM_DIRENT_FLAG_DIR )
printf( "<DIR>" );
else
{
printf( "%u bytes", ( unsigned )ent->fsize );
total = total + ent->fsize;
}
}
printf( "\n\nTotal on %s: %u bytes\n", pinst->name, ( unsigned )total );
dm_closedir( d );
}
}
printf( "\n" );
}
#endif // #ifdef BUILD_ADVANCED_SHELL

36
src/shell/shell_lua.c Normal file
View File

@ -0,0 +1,36 @@
// Shell: 'lua' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
// EOF is different in UART mode and TCP/IP mode
#ifdef BUILD_CON_GENERIC
#define SHELL_EOF_STRING "CTRL+Z"
#else
#define SHELL_EOF_STRING "CTRL+D"
#endif
const char shell_help_lua[] = "[-e <stat>] [-l <name>] [-i] [-v] [<script>]\n"
" [<script>]: execute the given script.\n"
" [-e <stat>]: execute string 'stat'.\n"
" [-l <name>]: require library 'name'.\n"
" [-i]: enter interactive mode after executing 'script'.\n"
" [-v]: show version information.\n"
"Without arguments it executes the interactive Lua interpreter.\n";
const char shell_help_summary_lua[] = "start a Lua session";
void shell_lua( int argc, char **argv )
{
printf( "Press " SHELL_EOF_STRING " to exit Lua\n" );
lua_main( argc, argv );
clearerr( stdin );
}

29
src/shell/shell_mkdir.c Normal file
View File

@ -0,0 +1,29 @@
// Shell: 'mkdir' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
const char shell_help_mkdir[] = "<path>\n"
" <path>: the directory to create.\n";
const char shell_help_summary_mkdir[] = "create directories";
void shell_mkdir( int argc, char **argv )
{
if( argc != 2 )
{
SHELL_SHOW_HELP( mkdir );
return;
}
if( mkdir( argv[ 1 ], 0 ) != 0 )
printf( "Error creating directory '%s'\n", argv[ 1 ] );
printf( "Created directory '%s'.\n", argv[ 1 ] );
}

107
src/shell/shell_recv.c Normal file
View File

@ -0,0 +1,107 @@
// Shell: 'recv' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#include "xmodem.h"
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#ifdef BUILD_XMODEM
const char shell_help_recv[] = "[<path>]\n"
" [<path>] - the data received via XMODEM will be saved to this file.\n"
"Without arguments it runs Lua to execute the data it receives.\n";
const char shell_help_summary_recv[] = "receive files via XMODEM";
extern char *shell_prog;
void shell_recv( int argc, char **argv )
{
char *p;
long actsize;
lua_State* L;
if( argc > 2 )
{
SHELL_SHOW_HELP( recv );
return;
}
if( ( shell_prog = malloc( XMODEM_INITIAL_BUFFER_SIZE ) ) == NULL )
{
printf( "Unable to allocate memory\n" );
return;
}
printf( "Waiting for file ... " );
if( ( actsize = xmodem_receive( &shell_prog ) ) < 0 )
{
if( actsize == XMODEM_ERROR_OUTOFMEM )
printf( "file too big\n" );
else
printf( "XMODEM error\n" );
goto exit;
}
// Eliminate the XMODEM padding bytes
p = shell_prog + actsize - 1;
while( *p == '\x1A' )
p --;
p ++;
printf( "done, got %u bytes\n", ( unsigned )( p - shell_prog ) );
// we've received an argument, try saving it to a file
if( argc == 2 )
{
FILE *foutput = fopen( argv[ 1 ], "w" );
size_t file_sz = p - shell_prog;
if( foutput == NULL )
{
printf( "unable to open file %s\n", argv[ 1 ] );
goto exit;
}
if( fwrite( shell_prog, sizeof( char ), file_sz, foutput ) == file_sz )
printf( "received and saved as %s\n", argv[ 1 ] );
else
printf( "unable to save file %s (no space left on target?)\n", argv[ 1 ] );
fclose( foutput );
}
else // no arg, running the file with lua.
{
if( ( L = lua_open() ) == NULL )
{
printf( "Unable to create Lua state\n" );
goto exit;
}
luaL_openlibs( L );
if( luaL_loadbuffer( L, shell_prog, p - shell_prog, "xmodem" ) != 0 )
printf( "Error: %s\n", lua_tostring( L, -1 ) );
else
if( lua_pcall( L, 0, LUA_MULTRET, 0 ) != 0 )
printf( "Error: %s\n", lua_tostring( L, -1 ) );
lua_close( L );
}
exit:
free( shell_prog );
shell_prog = NULL;
}
#else // #ifdef BUILD_XMODEM
const char shell_help_recv[] = "";
const char shell_help_summary_recv[] = "";
void shell_recv( int argc, char **argv )
{
shellh_not_implemented_handler( argc, argv );
}
#endif // #ifdef BUILD_XMODEM

34
src/shell/shell_ver.c Normal file
View File

@ -0,0 +1,34 @@
// Shell: 'ver' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#if defined( USE_GIT_REVISION )
#include "git_version.h"
#else
#include "version.h"
#endif
const char shell_help_ver[] = "\n"
"This displays the git revision of the tree used to build eLua or an official version number if applicable.\n";
const char shell_help_summary_ver[] = "show version information";
void shell_ver( int argc, char **argv )
{
if( argc != 1 )
{
SHELL_SHOW_HELP( ver );
return;
}
printf( "eLua version %s\n", ELUA_STR_VERSION );
printf( "For more information visit www.eluaproject.net and wiki.eluaproject.net\n" );
}

52
src/shell/shell_wofmt.c Normal file
View File

@ -0,0 +1,52 @@
// Shell: 'wofmt' implementation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "shell.h"
#include "common.h"
#include "type.h"
#include "platform_conf.h"
#include "romfs.h"
#ifdef BUILD_WOFS
const char shell_help_wofmt[] = "\n"
"Formats the WOFS, initializing it to a blank state.\n";
const char shell_help_summary_wofmt[] = "WOFS format";
void shell_wofmt( int argc, char **argv )
{
if( argc != 1 )
{
SHELL_SHOW_HELP( wofmt );
return;
}
printf( "Formatting the internal WOFS will DESTROY ALL THE FILES FROM WOFS.\n" );
if( shellh_ask_yes_no( "Are you sure you want to continue? [y/n] " ) == 0 )
return;
printf( "Formatting ..." );
if( !wofs_format() )
{
printf( "\ni*** ERROR ***: unable to erase the internal flash. WOFS might be compromised.\n" );
printf( "It is advised to re-flash the eLua image.\n" );
}
else
printf( " done.\n" );
}
#else // #ifdef BUILD_WOFS
const char shell_help_wofmt[] = "";
const char shell_help_summary_wofmt[] = "";
void shell_wofmt( int argc, char **argv )
{
shellh_not_implemented_handler( argc, argv );
}
#endif // #ifdef BUILD_WOFS