First commit to this server

This commit is contained in:
Tim O\'Neil 2025-08-19 07:49:22 -07:00
parent ec05d3601a
commit cce6f6b9c6
44 changed files with 5529 additions and 296 deletions

11
.gitignore vendored
View File

@ -1,4 +1,3 @@
# ---> C
# Prerequisites
*.d
@ -43,6 +42,15 @@
*.idb
*.pdb
# Misc meta fles
*.user
*.debug
*.dirstamp
.vs/
.deps/
x64/
build-interp-*/
# Kernel Module Compile Results
*.mod*
*.cmd
@ -51,4 +59,3 @@ modules.order
Module.symvers
Mkfile.old
dkms.conf

128
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
interval1066@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

557
LICENSE
View File

@ -1,232 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
interp
Copyright (C) 2025 interval
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
interp Copyright (C) 2025 interval
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

31
Makefile.am Normal file
View File

@ -0,0 +1,31 @@
AUTOMAKE_OPTIONS = foreign
CFLAGS = -Wall -std=c11 -Wno-unused-result -Wno-unused-function -Wno-incompatible-pointer-types \
-Wno-discarded-qualifiers -Wno-int-conversion -Wno-parentheses
LDFLAGS +=-s
# this lists the binaries to produce, the (non-PHONY, binary) targets in
# the previous manual Makefile
sbin_PROGRAMS = interp help
interp_SOURCES = src/main.c \
src/intrinsic.c \
src/foo1.c \
src/utils/filesys.c \
src/utils/huff.c \
src/utils/config.c
AM_CPPFLAGS = -Wall -std=c11 -O2 -g0 -I$(top_srcdir)/include
man_MANS =
EXTRA_DIST = include/foo1.h \
include/intrinsic.h \
include/simple_strlib.h \
include/support.h \
include/utils/filesys.h \
include/utils/getopt.h \
include/utils/huff.h \
include/utils/config.h
help$(EXEEXT):
@echo "Installing interp help file"
cp ./extra/interp.hlp ~/.interp.hlp

View File

@ -1,12 +1,8 @@
# interp
Super simple arbitrary length, "first match", command interpeter for embedded projects in C11. I'm talking SIMPLE configuration, just try it. I'd be surprised if there's a easier to use parser than this one, unless it can be configured without re-compiling.<br><br>"Q", "qu", "qUi" (case insensitive and normalized to lower case), and "quit" will all exit the interpreter, for example. Generates its own menu, super light, and highly portable. Only depends on libconfig, and even that can be removed with little effort. See the "newcmds" markdown file for info on customizing and adding new commands.
interp
Have been getting a lot of positive reviews; as I said its VERY flexible and parses a treat with very little code. Needs more testing, but so far
I'm seeing that the first match action on this is great; say you have a command "get door". If both get and door are registered as a command and a parameter "g d" works fine, as long as they appear first in the command/parameter list. If not then again, next match. If "gummy door" is next in the list it will pick that up. Try it!
Super simple arbitrary length, "first match", command interpeter for embedded projects in C11. I'm talking SIMPLE configuration, just try it. I'd be surprised if there's a easier to use parser than this one, unless it can be configured without re-compiling.
"Q", "qu", "qUi" (case insensitive and normalized to lower case), and "quit" will all exit the interpreter, for example. Generates its own menu, super light, and highly portable. Only depends on libconfig, and even that can be removed with little effort. See the "newcmds" markdown file for info on customizing and adding new commands.
Have been getting a lot of positive reviews; as I said its VERY flexible and parses a treat with very little code. Needs more testing, but so far I'm seeing that the first match action on this is great; say you have a command "get door". If both get and door are registered as a command and a parameter "g d" works fine, as long as they appear first in the command/parameter list. If not then again, next match. If "gummy door" is next in the list it will pick that up. Try it!
(10/17/2024) Finally removed the dependancy on libconfig.
(10/17/2024) Finally removed the dependancy on libconfig.<br>
(10/20/2024) Code now handles back spaces on Windows.

22
TODO.md Normal file
View File

@ -0,0 +1,22 @@
- [X] Fix help file reader
- [X] Implement make install for help, ini files.
- [ ] Debug interpreter, seems to be some issues
- [X] Setting the prompt to the time or date output doesn't work, will need to surround command with escape characters I'm sure.
- [X] Need to check for the existence of motd, hlp, and so on or the app falls over when it assume they are availalbe and they aren't.
- [ ] At the point where I need to add that error reporting module.
- [X] Port to ARM64.
- [X] Probably getting close to time to think about changing the recursive makefile to a canonical makefile chain, or use cmake.
- [X] Same repo builds on Windows and Linux x64.
- [X] Fix stack corruption when windows version exits.
- [X] Report to the user that dependancies (like libconfig) aren't on the build host.
- [ ] Manpage? Maybe?
- [ ] Add some code that actually uses the threadpool.
- [ ] Check to see if the code is truly thread-safe, I'm sure its not (hello printf...)
- [X] Fix help system.
- [ ] Implement and USE uinfo struct in support.h.
- [ ] Add posix style command line options.
- [ ] Add case senitivity as an option (?).
- [X] Make use of encryption module.
- [X] Add a string member to the user context struct that holds the user's prompt so when user changes it it can be reflected immedaitely.
- [ ] Rename any "motd" references to "intrpmotd" or anything else, too easy to confuse with the actual linux motd file.
- [X] Process backspace characters.

10
autoclean.sh Executable file
View File

@ -0,0 +1,10 @@
#!/bin/sh
#
# Clean autotools config, run in top directory
#
make clean
rm -rf autom4te.cache
rm aclocal.m4 compile config.h config.h.in config.log \
config.status configure depcomp install-sh Makefile.in \
missing stamp-h1 Makefile

1579
autogen.sh Executable file

File diff suppressed because it is too large Load Diff

22
configure.ac Normal file
View File

@ -0,0 +1,22 @@
AC_PREREQ([2.71])
AC_INIT([interp],[1.0],[interval1066@gmail.com])
AM_INIT_AUTOMAKE([subdir-objects])
AC_CONFIG_FILES([Makefile])
AC_OUTPUT
AC_CONFIG_SRCDIR([src/main.c])
AC_CONFIG_HEADERS([config.h])
# Checks for programs.
AC_PROG_CXX
AC_PROG_CC
AC_LANG(C)
AC_LANG_PUSH([C])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],[],[AC_MSG_ERROR([No C compiler found])])
AC_LANG_POP([C])
# Checks for typedefs, structures, and compiler characteristics.
AC_CHECK_HEADER_STDBOOL
AC_C_INLINE
# Checks for library functions.
AC_OUTPUT

42
detail.md Normal file
View File

@ -0,0 +1,42 @@
# interp
Simple command interpeter for embedded projects in C. I needed to re-write a very badly written command shell for an internet appliance once. Too bad that company elected not to use it; "would cost to much to replace." Bad idea and I hope you're not using that product, it was a security nightmare. Also, for various technical reasons, this had to be written in linear C, not C++. Which is not really a bad way to go with some embedded platforms.
Although by no means useful as is, the design is really quite modular and loosely coupled; adding new commands to this is a simple matter of adding them to "commands" and "table" static members of the main module<sup>1</sup>, then adding their definitions to either the "foo1" translation unit or a completely new one, just add the new files with your functionality defined in them.
The "huff" module is a simple huffman encryption C implementation you can use to encrypt plain text, like the message of the day included example command. Use it to do just that or maybe a list of passwords or whatever, or completly remove it and make the app even smaller. Warning: its just that; a simple huffman encoding implementaion. Please use AES or something like that for really sensitive data. Its meant soley as a way to make non-critical data readable only through the app.
Action is a first match, arbitrary length thing; q, qu, and qui will all "quit" the interpreter, but quib will not. The logic that implements this is tiny (pretty terse pointer magic) and all contained in the main module<sup>1</sup> (but not in the main function, there's like two or three static functions in the main module that handle all this. It shouldn't be a huge climb to follow. That same magic extends to commands as parameters to the help module; simply typing "h a" will return info on the arp command, simply being entered into the "commands" and "table" tables is snough to have the application treat them like any other command.
As is the code compiles down to under 35K bytes<sup>3</sup>, filled out with some actually useful commands, stripped release, and an embedded clib, I figure you can have a board that can do things via this interpreter for well under 100KB or possibly less if you really watch your memory usage.
Builds its own command menu automgically, no need to update that. Detailed descriptions will need updating in extra/interp.hlp however. Rename to your actual application name and place in the $USER home directory.
Autoconf automatically provides an "install" command but there's no point in installing this. I'm going to remove the autoconf directive. You are welcome to use the autoconf install command if you want but its really kind of pointless. I would add that in your own finished package that uses this code.
As well as typical scripts for autotools there's a qtcreator project file and a visual studio 2022 project configuration just for fun.
Builds an ARMhf 32 bit target using the generic makefile in the linux subdirectory as long as you have the GCC ARMhf compiler installed on your system,
can probably target other platforms using GCC or LLVM.
To initiate an autotools build just run autogen.sh and follow the instructions, make sure that the execute bit is set on the automake and clean scripts. To build using the qtcreator project file load the project and select your build kit of choice. To build on Windows you'll need to reconfigure the project for your Win SDK, obviously. I'm on visual studio 2022, so you may need to create a project for your version and add the source modules manually. For visual studio code I have no idea, I rarely use that ide. For eclipse? Lift the voodoo curse off yourself and stop using it, you know that thing was originally written by IBM??
autoclean.sh should reset the entire source directory to the "ground state." See "newcmds.md" for instruction on adding commands to the interpreter. Take special note
of the user context struct, its key for makeing changes to the shell's environment without needing to re-start it.
Again, and probably can't be stressed enough; this project is a "starter" project for your own command line processor engine or shell utiity; the included commands in the foo1 source are just examples; all of them need to be replaced with your required functionality and the extra/interp.help updated with actual descriptions of your new commands. MAKE INSTALL will do NOTHING USEFUL, but you can use it if for some reason you must. Never the less this is fully functioning code (the foo commands don't do anything though, not really) I simply consider it bad form to provide broken example code. That said, there maybe be some "slightly" broken code here and there. Pleaase write me about it or submit your own patch if you like.
Depends on libconfig, barely. Can be easily removed if needed.
7/12/2024 Fixed flaw with the help code.
---
1. The code now counts the number of members in the table static global member automatically, no need for this constant anymore. Also, the "commands" & "table" structs have been moved to include/parser.h.<br>
2. This has been eliminated in subsequent versions.
3. Under 25K on windows.
9/11/2024 Uncovered some serious issues
---
Turns out libconfig sucks. You can't put arbitrary characters in the ini files, it either needs to have legitmate alphanumeric characters or no file. If it encounters, say stars or hashbangs it spews core. Unacceptable. So I'm going back to my original idea of writing my own ini parser. When I can. Really busy right now.
10/26/2024 Removed the libconfig dependancy
---
Got the above done.

19
extra/interp.hlp Normal file
View File

@ -0,0 +1,19 @@
aaa|===||aaa <param>||Development test command.
access-lists|============||access-lists||List all access lists.
elist|====||elist <list> <no>||Edit the specified list or list all the available lists.
amp|===||amp <no>|Edit the properties of the specified amplifier.
arp|===||arp|List the arp table.
app|===||app <property>||Edit interpreter properites.
badl|====||badl <list entry>||Mark a list as being bad. Will be deleted AFTER the next processing cycle.
batch|=====||batch <list>||Execute a batch list.
bert|====||bert <no> (on/off)||Check the status or activate/deactivate the specified BERT device.
help|====||help <topic>||Get command list or detail on the specified topic.
motd|====||motd <message>||Set the message of the day for the interpreter. The message must be quote surrounded.
prompt|=====||prompt <new prompt>||Set a new prompt for the interpreter. The prompt will be avilable when the interpreter is re-started. The new prompt must be quote surrounded.
quit|====||quit||Exit the application.
date|====||date||Output the current date.
list|====||list <new list/(all)>||Create a new batch list, or list all existing lists.
time2|====||time2||Output the current time.
loglevel|====||loglevel||Log verbosity; from 0 (Off) to 4 (Maximum).
filet|====||filet||A fine cut of meat.

21
include/error_info.h Normal file
View File

@ -0,0 +1,21 @@
#pragma once
typedef enum
{
CMD_MISPARAM = -11, // inimissing paramt file
CMD_MEMERR = -10,
CMD_INITNF = -9, // initialization file not found
CMD_HELPERR = -8, // problem with help subsystem
CMD_QUOTES = -7, // argument not enclosed in quotes
CMD_IOERR = -6, // io error
CMD_BANNERPTH = -5, //
CMD_FILEEXST = -4, // file exists
CMD_FILENF = -3, // file not found
CMD_ARGS = -2, // error with command arguments
CMD_ERR = -1, // non-specific error
CMD_OK = 0, // command completed successfully
CMD_QUIT = 1, // exit application
CMD_NOOP = 2 // no operation
} RET_CODE;
// Hashmap of pointers to error text and codes whatever else.

41
include/foo1.h Normal file
View File

@ -0,0 +1,41 @@
#pragma once
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
#ifndef _WIN32
#include "utils/filesys.h"
#endif
#include "simple_strlib.h"
#include "error_info.h"
#ifdef __cplusplus
extern "C"{
#endif
int dummy(const char*);
int aaa(const char*);
int alist(const char*);
int amp(const char*);
int app(const char*);
int arp(const char*);
int badl(const char*);
int batch(const char*);
int bert(const char*);
int date(const char*);
int list(const char*);
int time2(const char*);
int loglevel(const char*);
int filet(const char*);
#ifdef __cplusplus
}
#endif

42
include/intrinsic.h Normal file
View File

@ -0,0 +1,42 @@
#pragma once
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
#include "utils/filesys.h"
#include "utils/huff.h"
#include "error_info.h"
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4090 )
#pragma warning( disable : 594 )
#pragma warning( disable : 542 )
#endif
extern const char dateout[16];
extern const char timeout[20];
extern const char* commands[];
extern const int noCmds;
#ifdef __cplusplus
extern "C" {
#endif
int help(const char*);
int find_help_section(const char*);
int motd(const char*);
int prompt(const char*);
int quit(const char*);
#ifdef _MSC_VER
#pragma warning ( pop )
#endif
#ifdef __cplusplus
}
#endif

12
include/logger.h Normal file
View File

@ -0,0 +1,12 @@
#pragma once
/**
* Logging thread, complately alpha code- may completely change form in the near future.
*/
inline int
StartLogger(int nLevel)
{
return CMD_OK;
}

141
include/parser.h Normal file
View File

@ -0,0 +1,141 @@
#pragma once
#include "foo1.h"
#ifdef _MSC_VER
#include <io.h>
#include "winunistd.h"
#define STRLWR _strlwr
extern size_t getline(char**, size_t*, FILE*);
#else
#include <unistd.h>
#include <libconfig.h>
extern char* strlwr(char*);
#define STRLWR strlwr
#endif
#ifdef __cplusplus
extern "C" {
#endif
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4090 )
#pragma warning( disable : 542 )
#endif
extern const char* strstrip(char*);
// Just a simple jump table
const char* commands[] = {
"dummy",
"help",
"aaa",
"access-lists",
"amplifiers",
"app",
"arp",
"badl",
"batch",
"bert",
"motd",
"prompt",
"quit",
"date",
"lists",
"time2",
"loglevel",
"filet",
"?" };
int (*table[])() = {
dummy, help, aaa, alist, amp, app, arp, badl, batch, bert,
motd, prompt, quit, date, list, time2, loglevel, filet,
};
#ifdef _MSC_VER
int const noCmds = _countof(table);
#else
const int noCmds = *(&table + 1) - table;
#endif
bool
run_cmd(int nCmd, char* full_cmd)
{
int n = 0;
if(nCmd == CMD_ERR) {
printf("\nUnknown command.\n");
return true;
}
// If help is invoked with '?'
if (nCmd == noCmds) nCmd = 1;
if((nCmd == 1) && (strlen(full_cmd) < 5)) {
printf("\n");
while (strchr(*(commands + ++n), '?') == NULL)
printf("- %s\n", *(commands + n));
printf("\n");
}
int nStatus = CMD_ERR;
int (**p)(char*);
p = table;
// command found, execute it.
nStatus = (*p[nCmd])(strstrip(full_cmd));
// if its the 'special' quit command; bail.
if (nStatus == CMD_QUIT)
return false;
return true;
}
/**
* @brief Process the commands rejecting those that aren't on the list
* This needs to be moved to another translation unit (completed 11/2023)
*
* @param char** inp The string to process
* @param int size The number of command elements
* @return boolean returns the status of the run_cmd
* function, which is only false if we
* process a quit command.
*/
bool
proc_cmds(char** inp, int size)
{
int n = 0, nCmd = 0;
bool bFound = false;
char full_cmd[200], cmd[40];
memset(full_cmd, '\n', sizeof(full_cmd));
memset(cmd, '\n', sizeof(cmd));
for(n = 0; n <= noCmds; n++) {
if(strncmp(inp[0],
*(commands + n),
strlen(strstrip(STRLWR(inp[0])))) == 0) {
bFound = true;
}
if(bFound) {
nCmd = n;
strcpy(full_cmd, *(commands + n));
for(int m = 1; m < size; m++) {
strcat(full_cmd, " ");
strcat(full_cmd, inp[m]);
}
printf("\n");
return run_cmd(nCmd, full_cmd);
}
}
return run_cmd(CMD_ERR, NULL);
}
#ifdef _MSC_VER
#pragma warning ( pop )
#endif
#ifdef __cplusplus
}
#endif

266
include/simple_strlib.h Normal file
View File

@ -0,0 +1,266 @@
#pragma once
#ifdef _MSVC_VER
#include <winunistd.h>
#endif
#include "support.h"
/**
* @file simple_strlib.h
* @brief Some additions that seem to be missing or
* are missing from the clib port.
*
* @details We've rolled our own string functions, they
* were either missing or I didn't like the way
* they worked. (I tend to favor in-place string
* manips for embedded work.) Needs to be tested
* for thread safety.
*
* @author t.o.
* @bug
*/
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include <stdlib.h>
#ifndef _WIN32
#include <sys/param.h>
#endif
#ifdef __cplusplus
extern "C"{
#endif
/**
* @brief strlwr
*
* @details My own version of strlwr, becuase clib
* doesn't appear to have one.
*
* @param s The string to convert
* @return pointer to the modified string
*/
inline char*
strlwr(char* s)
{
char* p = s;
while(*p) {
*p = tolower((uint32_t)*p);
p++;
}
return s;
}
/**
* @brief countc
*
* @details Count the number of occurrences of c in s
*
* @param s The target string
* @param c The character to count
* @return the count
*/
static inline int
countc(const char* s, char c)
{
int n = 0;
while(*s++ != '\0') {
if(*s == c)
n++;
}
return n;
}
/**
* @brief Strip trailing whitespace from s inplace
*
* @param s The string to trim
* @return the modified string
*/
inline const char*
strstrip(char* s)
{
size_t size = strlen(s);
if (!size)
return s;
char* end;
end = s + size - 1;
while(end >= s && isspace(*end))
end--;
*(end + 1) = '\0';
while(*s && isspace(*s))
s++;
return s;
}
/**
* @brief Split the string at delimiters using a zero-copy in-place algorithm
*
* @param s The string to split (every delimiter will be replaced by NULL)
* @param delimiter The delimiter character to split at
* @param size The size of the return array w
* @return A list of char* (size stored in *size), pointing to all split results in order
* Don't forget to free the returned array in the caller
*/
static inline char**
split(char* s, char delimiter, int* size)
{
int numdelimiters = countc(s, delimiter);
char** splitresult = malloc((numdelimiters + 2) * sizeof(char*)); // +2 for the last substring and NULL terminator
if (splitresult == NULL) {
*size = 0;
return NULL; // Memory allocation failed
}
splitresult[0] = s;
int i = 1;
char* hit = s;
while ((hit = strchr(hit, delimiter)) != NULL) {
*hit++ = '\0';
splitresult[i++] = hit;
}
splitresult[i] = NULL; // Mark the end of the splitresult array with NULL
*size = numdelimiters + 1;
return splitresult;
}
/**
* @breif Remove the substring matched. Operates
* in-place.
*
* @param the string to operate on
* @param the character sequence to remove
*/
static inline void
remove_first(char* str, const char* str_remove)
{
size_t j;
size_t len;
size_t remove_len;
int found = 0;
len = strlen(str);
remove_len = strlen(str_remove);
for(size_t i = 0; i < len; i++) {
found = 1;
for(j = 0; j < remove_len; j++) {
if(*(str + i + j) != *(str_remove + j)) {
found = 0;
break;
}
}
// If word has been found then remove it by shifting characters
if(found == 1) {
for(j = i; j <= len - remove_len; j++)
*(str + j) = *(str + j + remove_len);
// Terminate from loop so only first occurrence is removed
break;
}
}
}
/**
* @brief find first index of character in string
*
* @param string string to operate on
* @param char char to find index of
* @return integer index of the first occurance of char
*/
static inline int
find_ch_index(const char* string, char ch)
{
int i = 0;
while(*(string + i) && *(string + i) != ch) i++;
return *(string + i) == ch ? -1 : i;
}
/**
* @brief pass a substring of the source string through an i/o parameter
*
* @param char pointer source string
* @param start index of starting character for subsctring in source
* @param length of source string
* @param char pointer to destination string buffer
* @param length of destination string buffer
*/
static inline void
mid(const char* src, size_t start, size_t length, char* dst, size_t dstlen)
{
size_t len = MIN(dstlen, length);
strncpy(dst, src + start, len);
// zero terminate because strncpy() didn't ?
if(len < length)
dst[dstlen - 1] = 0;
}
static char*
right(char* string, int size)
{
while(*string++);
return(string - size - 2);
}
static char*
replace_char(char* str, char find, char replace){
char *current_pos = strchr(str,find);
while (current_pos) {
*current_pos = replace;
current_pos = strchr(current_pos,find);
}
return str;
}
static void
substr(const char* inputString, char delimiter, char** resultBuffer) {
// Find the first occurrence of the delimiter
const char* firstOccurrence = strchr(inputString, delimiter);
if (firstOccurrence == NULL) {
// Delimiter not found
*resultBuffer = NULL;
return;
}
// Find the second occurrence of the delimiter
const char* secondOccurrence = strchr(firstOccurrence + 1, delimiter);
if (secondOccurrence == NULL) {
// Second occurrence not found
*resultBuffer = NULL;
return;
}
// Calculate the length of the substring
size_t substringLength = secondOccurrence - (firstOccurrence + 1);
// Allocate memory for the result buffer
*resultBuffer = (char*)malloc(substringLength + 1);
if (*resultBuffer == NULL) {
// Memory allocation failed
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
// Copy the substring into the result buffer
strncpy(*resultBuffer, firstOccurrence + 1, substringLength);
(*resultBuffer)[substringLength] = '\0'; // Null-terminate the string
}
#ifdef __cplusplus
}
#endif

57
include/support.h Normal file
View File

@ -0,0 +1,57 @@
#pragma once
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 5945 )
#include <conio.h>
#else
#include <termios.h>
#endif
#include <string.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C"{
#endif
/**
* Internal objects ONLY
*/
#define MAXMOTD 512
#define MAXBUF 256
#ifndef SIZEARRAY
#define SIZEARRAY(a) (sizeof(a) / sizeof((a)[0]))
#endif
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif
typedef int (*command_object)(char*);
//typedef enum {false, true} bool;
struct uinfo {
struct passwd* info;
};
struct user_ctx
{
int loglevel;
bool admin;
char prompt[16];
};
#ifdef __cplusplus
}
#endif
#ifdef _MSC_VER
#pragma warning( pop )
#endif

48
include/threadpool.h Executable file
View File

@ -0,0 +1,48 @@
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <threads.h>
#define DEFAULT_THREAD_POOL_SIZE 5
typedef struct ThreadPool ThreadPool;
typedef struct Task Task;
struct Task {
void (*function)(void* arg);
void* arg;
Task* next;
};
struct ThreadPool {
mtx_t lock;
cnd_t condition;
Task* task_queue;
thrd_t* threads;
size_t num_threads;
bool shutdown;
};
#ifdef __cplusplus
extern "C"{
#endif
// Function to initialize a thread pool
ThreadPool* thread_pool_init(size_t num_threads);
// Function to destroy a thread pool
void thread_pool_destroy(ThreadPool* pool);
// Function to add a task to the thread pool
bool thread_pool_enqueue(ThreadPool* pool, void (*function)(void*), void* arg);
// Function executed by each thread in the pool
int thread_function(void* arg);
#ifdef __cplusplus
}
#endif

111
include/utils/config.h Normal file
View File

@ -0,0 +1,111 @@
#ifndef _TCONFIG_H_
#define _TCONFIG_H_
#include <stdbool.h>
typedef struct ini_entry_s {
char* key;
char* value;
} ini_entry_s;
typedef struct ini_section_s {
char* name;
ini_entry_s* entry;
int size;
} ini_section_s;
typedef struct ini_table_s {
ini_section_s* section;
int size;
} ini_table_s;
/**
* @brief Creates an empty ini_table_s struct for writing new entries to.
* @return ini_table_s*
*/
ini_table_s* ini_table_create();
/**
* @brief Free up all the allocated resources in the ini_table_s struct.
* @param table
*/
void ini_table_destroy(ini_table_s* table);
/**
* @brief Creates an ini_table_s struct filled with data from the specified
* `file'. Returns NULL if the file can not be read.
* @param table
* @param file
* @return ini_table_s*
*/
bool ini_table_read_from_file(ini_table_s* table, const char* file);
/**
* @brief Writes the specified ini_table_s struct to the specified `file'.
* Returns false if the file could not be opened for writing, otherwise
* true.
* @param table
* @param file
* @return bool
*/
bool ini_table_write_to_file(ini_table_s* table, const char* file);
/**
* @brief Creates a new entry in the `table' containing the `key' and `value'
* provided if it does not exist. Otherwise, modifies an exsiting `key'
* with the new `value'
* @param table
* @param section_name
* @param key
* @param value
*/
void ini_table_create_entry(ini_table_s* table, const char* section_name,
const char* key, const char* value);
/**
* @brief Checks for the existance of an entry in the specified `table'. Returns
* false if the entry does not exist, otherwise true.
* @param table
* @param section_name
* @param key
* @return bool
*/
bool ini_table_check_entry(ini_table_s* table, const char* section_name,
const char* key);
/**
* @brief Retrieves the unmodified value of the specified `key' in `section_name'.
* Returns NULL if the entry does not exist, otherwise a pointer to the
* entry value data.
* @param table
* @param section_name
* @param key
* @return const char*
*/
const char* ini_table_get_entry(ini_table_s* table, const char* section_name,
const char* key);
/**
* @brief Retrieves the value of the specified `key' in `section_name', converted
* to int. Returns false on failure, otherwise true.
* @param table
* @param section_name
* @param key
* @param [out]value
* @return int
*/
bool ini_table_get_entry_as_int(ini_table_s* table, const char* section_name,
const char* key, int* value);
/**
* @brief Retrieves the value of the specified `key' in `section_name', converted
* to bool. Returns false on failure, true otherwise.
* @param table
* @param section_name
* @param key
* @param [out]value
* @return bool
*/
bool ini_table_get_entry_as_bool(ini_table_s* table, const char* section_name,
const char* key, bool* value);
#endif//_TCONFIG_H_

51
include/utils/filesys.h Normal file
View File

@ -0,0 +1,51 @@
#pragma once
#include <sys/types.h>
#include <stdlib.h>
#include <utils/filesys.h>
#include <sys/stat.h>
#include <stdbool.h>
#include <stdio.h>
#ifndef _MSC_VER
#include <pwd.h>
#include <unistd.h>
#else
#include <io.h>
#include <Shlobj.h>
#endif
#include "support.h"
#include "simple_strlib.h"
#include "error_info.h"
#define MAXSIZE 256
#ifdef __cplusplus
extern "C" {
#endif
/**
* @file filesys.h
* @author Tim O'Neil
* @date 3/9/2018
*
* @brief System-specific & near system-specific utilities
*
* @section DESCRIPTION
*
* Collection of functions that will be more system specific
* and non-portable (mostly file systems utils and such).
*/
int find_cfgfile(const char*, char*, bool);
int create_cfgfile(const char*);
void get_userdir(char*);
int write_motd(char*, const char*);
int read_motd(const char*);
const char* get_keyvalue(const char*, const char*);
int set_keyvalue(const char*, const char*);
bool file_exists(const char*);
#ifdef __cplusplus
}
#endif

84
include/utils/getopt.h Normal file
View File

@ -0,0 +1,84 @@
/* A minimal POSIX getopt() implementation in ANSI C
*
* This is free and unencumbered software released into the public domain.
*
* This implementation supports the convention of resetting the option
* parser by assigning optind to 0. This resets the internal state
* appropriately.
*
* Ref: http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html
*/
#ifndef GETOPT_H
#define GETOPT_H
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int optind;
int opterr = 1;
int optopt;
char *optarg;
int
getopt(int argc, char * const argv[], const char *optstring)
{
static int optpos = 1;
const char *arg;
/* Reset? */
if (optind == 0) {
optind = !!argc;
optpos = 1;
}
arg = argv[optind];
if (arg && strcmp(arg, "--") == 0) {
optind++;
return -1;
} else if (!arg || arg[0] != '-' || !isalnum(arg[1])) {
return -1;
} else {
const char *opt = strchr(optstring, arg[optpos]);
optopt = arg[optpos];
if (!opt) {
if (opterr && *optstring != ':')
fprintf(stderr, "%s: illegal option: %c\n", argv[0], optopt);
if (!arg[++optpos]) {
optind++;
optpos = 1;
}
return '?';
} else if (opt[1] == ':') {
if (arg[optpos + 1]) {
optarg = (char *)arg + optpos + 1;
optind++;
optpos = 1;
return optopt;
} else if (argv[optind + 1]) {
optarg = (char *)argv[optind + 1];
optind += 2;
optpos = 1;
return optopt;
} else {
if (opterr && *optstring != ':')
fprintf(stderr,
"%s: option requires an argument: %c\n",
argv[0], optopt);
if (!arg[++optpos]) {
optind++;
optpos = 1;
}
return *optstring == ':' ? ':' : '?';
}
} else {
if (!arg[++optpos]) {
optind++;
optpos = 1;
}
return optopt;
}
}
}
#endif

66
include/utils/huff.h Executable file
View File

@ -0,0 +1,66 @@
#pragma once
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/**
* @file huff.h
* @author Tim O'Neil
* @date 3/9/2018
*
* @brief Probably pretty portable Huffman coder
*
* @section DESCRIPTION
*
* Huffman ecoder to compress large blobs of text and anything
* meant to be read only through an application UI. This file
* defines some necessary structs and such. See the implementation
* file for more details.
*/
typedef struct node
{
char c;
int freq;
struct node *link;
struct node *rlink;
struct node *llink;
} node_t;
typedef struct List
{
node_t *head;
} List_t;
typedef struct
{
unsigned char c : 8;
} code_generated;
typedef struct
{
int freq;
unsigned char ch;
} info;
void decode(const char*);
void encode(const char*, char*);
void insert_in_list(List_t*, node_t*);
void init_list(List_t *ptr);
void disp_list(const List_t*);
void make_node(List_t*, int, char);
void make_list(List_t*, int*);
void find_freq(char*, int*);
void make_tree(List_t*, int*);
void find_code(node_t*, char*, char codes[256][40]);
void compress(char*, FILE*, char codes[256][40], int, info*, int*, int num);
unsigned char convert_string_char(char string[8]);
int find_no_of_chars(int*);
void strre(char*, int);
node_t* decode_char(FILE*, node_t*, int, int, node_t*, int*, int);
int create_header(int*, int, info*);

61
linux/ARM_etc/Makefile Normal file
View File

@ -0,0 +1,61 @@
# This is a recursive makefile- do not use in production
# convert to canonical make chain when time permits
#
# recursive file search
rfilelist=$(wildcard $1$2) $(foreach d,$(wildcard $1*),$(call rfilelist,$d/,$2))
# the name of program
TARGET = interp
CC = gcc
# C++ compiler flags
LIBS += -pthread -lconfig
EXT = c
# source files
SRC = ./src
SRCS := $(call rfilelist,$(SRC),*.$(EXT))
INCLUDES = ./include ./include/utils
CFLAGS := -Wall -std=c11 -c
CFLAGS += $(addprefix -I,$(INCLUDES))
OBJS = $(SRCS:%.$(EXT)=%.o)
DEBUG_HELPERS = $(SRCS:%.$(EXT)=%.debug)
OPTIMIZE_HELPERS = $(SRCS:%.$(EXT)=%.optim)
OBJDEBOUT = $(@:%.debug=%.o)
OBJOPTOUT = $(@:%.optim=%.o)
DEBOUT = $(@:%.debug=%.$(EXT))
OPTOUT = $(@:%.optim=%.$(EXT))
# rules for debug build and optimized build
%.debug: %.$(EXT)
$(CC) $(CFLAGS) -ggdb -D_DEBUG -DDEBUG -o $(OBJDEBOUT) $(DEBOUT)
rm -f $(@.debug=%.debug)
touch -f $@
%.optim: %.$(EXT)
$(CC) $(CFLAGS) -O2 -DNDEBUG -o $(OBJOPTOUT) $(OPTOUT)
rm -f $(@.optim=%.optim)
touch -f $@
# rules for object files
%.o: %.$(EXT)
$(CC) $(CFLAGS) $?
# default build
all: debug
# debug build
debug: $(DEBUG_HELPERS)
test -s $@ || mkdir $@
$(CC) $(OBJS) -o debug/$(TARGET) $(LIBS)
rm -f $(DEBUG_HELPERS)
# optimized build
optim: $(OPTIMIZE_HELPERS)
test -s $@ || mkdir $@
$(CC) $(OBJS) -o optim/$(TARGET) $(LIBS)
rm -f $(OPTIMIZE_HELPERS)
strip optim/$(TARGET)
# clean rule
clean:
rm -f $(OBJS) $(DEBUG_HELPERS) $(OPTIMIZE_HELPERS)

1
linux/ARM_etc/README.md Normal file
View File

@ -0,0 +1 @@
Generic makefile, use this for hacking or building on other architectures. This will build on the Raspberry Pi as is.

39
linux/interp.pro Normal file
View File

@ -0,0 +1,39 @@
TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt
TARGET = interp
QMAKE_CFLAGS += -Wall -std=c17 -Wno-unused-parameter
QMAKE_CFLAGS += -Wno-unused-function -Wno-unused-result
QMAKE_CFLAGS += -Wno-discarded-qualifiers -Wno-int-conversion
QMAKE_CFLAGS += -Wno-incompatible-pointer-types
INCLUDEPATH += $$PWD/../include
LIBS += -lpthread
SOURCES += \
../src/foo1.c \
../src/intrinsic.c \
../src/support.c \
../src/main.c \
../src/support.c \
../src/utils/filesys.c \
../src/utils/huff.c \
../src/utils/config.c
HEADERS += \
../include/commands.h \
../include/foo1.h \
../include/intrinsic.h \
../include/parser.h \
../include/simple_strlib.h \
../include/support.h \
../include/utils/filesys.h \
../include/utils/huff.h \
../include/utils/config.h
CONFIG(release, debug|release) {
QMAKE_POST_LINK=$(STRIP) $(TARGET)
}

46
newcmds.md Normal file
View File

@ -0,0 +1,46 @@
### Adding New Commands to the Interpreter
<p>The code consists of intrinsic commands and add-on commands. Intrinsic commands shouldn't be modified
or expanded.</p>
<p>Add-on commands are all the other commands you can see in the "foo1" source file. Add-ons can be added to
those existing sources, added to an entirely new translation unit, to a static library or a shared lib, whatever
makes the most sense for your application. You're also welcome to remove all of those commands and add your own, of course.</p>
#### Adding a Log Level Command
<p>In this example, we'll add a new command called `loglevel` that will set the logging level of the of the
interpreter. There are lots of descisions to make in developing a loggng facility to an application; mostly
its scope, where it'll be written and its persistence, but since we won't actually implement a working logging
facility we'll just worry about adding the command to the interpreter.</p>
<p>Let's add the command "loglevel" with an integer parameter 0-4. 0 will mean logging off, and 4 is the highest
level of verbosity:</p>
1. Add our new command "loglevel" to the "commands" double array in the "parser.h" file. The question mark must be the last command in the array, and help must always be first:
``` c
const char* commands[] = { "dummy",
"help",
"aaa",
"access-lists",
"amplifiers",
"app",
<...>
"loglevel",
"?" };
```
2. Add a "loglevel" token to the "table" double array. Note, this is just an index token, not a string.
Importance is its place in the table, not its value:
``` c
int (*table[])() = {
dummy, help, aaa, alist, amp, app, arp, badl, batch, bert,
help, motd, prompt, quit, date, list, time2, loglevel
};
```
3. For statically linked commands define the function(s) for your new command in either foo1.c or add a new source file to the project. Add the new function prototypes to the appropriate header files. Use a pointer to the command invocation for access to parameters and delimeter processing; for example; if you want to use posix-style parameter marking ('-' & '--', and etc) define that in your new translation unit and pass all paramters through it before routing to the actual command definition. Look to the command examples in foo1.c for examples.
4. Add a useful description of the new command the ./extra/help file.
No modification of the parser code should be required for the UTF-8 charcter set-based projects. A list of all the commands is printed out when the user enters "help" or "?" and generated automtically from the available data. Command descriptions must be entered into the text file in the extra directory.
The "dummy" command is nessessary for now, obviously an index is off, I'll be getting rid of that when I find the error.
If you do see a problem a report would be appreciated. interval1066@gmail.com.

216
src/foo1.c Normal file
View File

@ -0,0 +1,216 @@
#include <string.h>
#include "foo1.h"
#include "utils/filesys.h"
const char dateout[16];
const char timeout[20];
extern const char* commands;
extern const int noCmds;
extern struct user_ctx user;
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 836 )
#pragma warning( disable : 594 )
#pragma warning( disable : 4090 )
#pragma warning( disable : 859 )
#endif
/**
* Command objects. Normally these would go into separate translation units.
* Quit is a special command that has its own return status, needed to signal
* to main that we are exiting.
* Callee functions are responsible for parsing and converting the opts string
* for any necessary arguments.
*/
int
dummy(const char* opts)
{
return CMD_OK;
}
int
aaa(const char* opts)
{
int size;
char** splitresult = split(opts, ' ', &size);
if(size < 2)
printf("%s called with no options.\n", splitresult[0]);
for(int n = 1; n < size; n++)
printf("%s called with option %s.\n", splitresult[0], splitresult[n]);
free(splitresult);
return CMD_OK;
}
int
alist(const char* opts)
{
int size;
char** splitresult = split(opts, ' ', &size);
for(int n = 1; n < size; n++)
printf("access_lists called with option %s.\n", splitresult[n]);
free(splitresult);
return CMD_OK;
}
int
amp(const char* opts)
{
printf("amp called with %s\n", opts);
return CMD_OK;
}
int
app(const char* opts)
{
printf("app called with %s\n", opts);
return CMD_OK;
}
int
arp(const char* opts)
{
printf("arp called with %s\n", opts);
return CMD_OK;
}
int
badl(const char* opts)
{
int n = 0;
char line[100];
FILE* fp = fopen("./list.dev", "r");
if(!fp) {
printf("No lists have been created yet\n");
return CMD_FILEEXST;
}
while(fgets(line, sizeof(line), fp))
if(strlen(line) > 1) printf("%d - %s", ++n, line);
fclose(fp);
return CMD_OK;
}
int
batch(const char* opts)
{
printf("batch called with %s\n", opts);
return CMD_OK;
}
int
bert(const char* opts)
{
printf("bert called with %s\n", opts);
return CMD_OK;
}
int
get_date(const char* opts)
{
sprintf(opts, "%s\n", __DATE__);
return CMD_OK;
}
int
date(const char* opts)
{
memset((const char*)dateout, '\0', sizeof(dateout));
get_date(dateout);
printf("%s\n", dateout);
return CMD_OK;
}
int
get_time(const char* opts)
{
sprintf(opts, "%s\n", __TIME__);
return CMD_OK;
}
int
time2(const char* opts)
{
memset((const uint64_t*)timeout, '\0', sizeof(timeout));
get_time(timeout);
printf("%s\n", timeout);
return CMD_OK;
}
int
list(const char* opts)
{
FILE* f = NULL;
char buf[16] = { 0 };
char dev[16] = { 0 };
strncpy(buf, right(opts, (int)strlen(opts) - 6), strlen(opts) - 2);
if(strlen(buf) == 2)
return CMD_ARGS;
printf("%s\n", buf);
if(strcmp(buf, "all") == 0) {
badl(NULL);
return CMD_OK;
}
printf("Adding new device %s to list.\n", buf);
f = fopen("./list.dev", "w");
if(f == NULL)
return CMD_IOERR;
do {
scanf("%15s", dev);
if(strcmp(dev, ".") != 0)
fwrite(&dev, strlen(dev), 1, f);
fprintf(f, "\n");
} while(strlen(dev) > 1);
if(f) fclose(f);
return CMD_OK;
}
int
loglevel(const char* opts)
{
int size;
char** splitresult = split((const char*)opts, ' ', &size);
if(size == 1) {
printf("Current log level: %i\n", user.loglevel);
free(splitresult);
return CMD_OK;
}
int m = atoi(splitresult[1]);
if((m < 0) && m > 4)
return CMD_ARGS;
user.loglevel = m;
free(splitresult);
return CMD_OK;
}
int
filet(const char* opts)
{
return CMD_OK;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif

125
src/intrinsic.c Normal file
View File

@ -0,0 +1,125 @@
#include "intrinsic.h"
extern struct user_ctx user;
extern int writeconfig();
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4090 )
#pragma warning( disable : 594 )
#endif
int
help(const char* opts)
{
int size;
int retcode;
char** splitresult = split(opts, ' ', &size);
if(size == 1)
retcode = find_help_section(opts);
else
retcode = find_help_section(splitresult[1]);
free(&splitresult[0]);
return retcode;
}
int
find_help_section(const char* section)
{
bool found = false;
FILE* fp = NULL;
char cfg_path[MAXBUF];
char chunk[MAXBUF];
memset(cfg_path, 0, sizeof(cfg_path));
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.hlp");
#else
strcat(cfg_path, "\\.interp.hlp");
#endif
fp = fopen(cfg_path, "r");
if(!fp) return CMD_FILEEXST;
while(fgets(chunk, sizeof(chunk), fp) != NULL) {
int n = strncmp(section, chunk, strlen(section));
if(n == 0) {
replace_char(chunk, '|', '\n');
fputs(chunk, stdout);
found = true;
}
}
if((!found) && strncmp(section, "?", (size_t)1) != 0)
printf("Keyword not found\n");
if(fp) fclose(fp);
return CMD_OK;
}
int
motd(const char* string)
{
char cfg_path[MAXBUF];
char mot_path[MAXBUF];
if(strlen(string) < 3)
return CMD_ARGS;
if(strchr(string, '"') == NULL)
return CMD_QUOTES;
memset(cfg_path, 0, sizeof(cfg_path));
get_userdir(cfg_path);
strcpy(mot_path, cfg_path);
remove_first(mot_path, ".interp.ini");
#ifndef _MSC_VER
strcat(mot_path, "/.motd");
#else
strcat(mot_path, "\\.motd");
#endif
char newm[MAXMOTD];
memset(newm, '\0', MAXMOTD);
mid(string, 6, find_ch_index(string, '"'), newm, strlen(string));
remove_first(newm, "\"");
encode(mot_path, newm);
return CMD_OK;
}
int
prompt(const char* opts)
{
char *buf;
int n = countc(opts, '\"');
if (n < 2)
return CMD_ARGS;
substr(opts, '\"', &buf);
memset(user.prompt, 0, strlen(user.prompt));
strcpy(user.prompt, buf);
free(buf);
return CMD_OK;
}
int
quit(const char* opts)
{
return CMD_QUIT;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif

272
src/main.c Normal file
View File

@ -0,0 +1,272 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <ctype.h>
#include <errno.h>
#include <signal.h>
#include "utils/config.h"
#include "intrinsic.h"
#include "support.h"
#include "parser.h"
#include "error_info.h"
#include "logger.h"
extern const int noCmds;
extern int help(const char*);
extern int StartLogger(int);
extern bool proc_cmds(char**, int);
struct user_ctx user;
char str[1024];
#define MAX_LINE 1024
/**
* @file main.c
* @author Tim O'Neil
* @date 3/9/2018
*
* @brief Probably pretty portable CLI interpreter
*
* @section DESCRIPTION test
*
* Alternate command line interpreter prototype.
*/
/**
* Anticipate ctrl + c
*
* no signals we need to handle as far as we
* know right now. May change in the future.
*/
void
sig_handler(int sign)
{
signal(SIGINT, sig_handler);
}
/**
* buffer sanitizer, on hold for now
*/
static int
sanitize_buf()
{
static char ok_chars[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"1234567890_-.@";
char user_data[] = "Bad char 1:} Bad char 2:{";
char *cp = user_data; // Cursor into string
const char *end = user_data + strlen(user_data);
for (cp += strspn(cp, ok_chars); cp != end; cp += strspn(cp, ok_chars))
*cp = '_';
return CMD_OK;
}
static void
reverse(char s[])
{
size_t i, j;
char c;
for (i = 0, j = (int)strlen(s) - 1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
static void
myitoa(int n, char s[])
{
size_t i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/**
* initial state
*
* set defaults including prompt which is a "> " (greater than + space), can be changed
* via the 'prompt' intrinsic command.
*/
static int
init(void)
{
char tmp[16] = { 0 };
memset(user.prompt, 0, sizeof(user.prompt));
strcpy(tmp, get_keyvalue("prompt", ""));
if(strlen(tmp) == 0)
strcpy(tmp, get_keyvalue("prompt", ">"));
#ifndef _MSC_VER
int len2 = (int)strlen(tmp);
tmp[len2 - 1] = '\0';
#endif
char banner_path[MAXBUF];
char cfg_path[MAXBUF];
signal(SIGINT, sig_handler);
memset(cfg_path, 0, sizeof(cfg_path));
memset(banner_path, 0, sizeof(banner_path));
get_userdir(cfg_path);
strcpy(banner_path, cfg_path);
#ifndef _MSC_VER
strcat(banner_path, "/.motd");
strcat(cfg_path, "/.interp.ini");
#else
strcat(banner_path, "\\.motd");
strcat(cfg_path, "\\.interp.ini");
#endif
if (access(banner_path, 0) == 0) {
decode(banner_path);
printf("\n");
}
return CMD_OK;
}
static int
readconfig(void)
{
user.admin = 0;
char adminperm[10] = { 0 };
char cfg_path[MAXBUF] = { 0 };
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.ini");
#else
strcat(cfg_path, "\\.interp.ini");
#endif
ini_table_s* config = ini_table_create();
if(ini_table_read_from_file(config, cfg_path)) {
strcpy(user.prompt, ini_table_get_entry(config, "Main", "prompt"));
user.loglevel = atoi(ini_table_get_entry(config, "Main", "loglevel"));
strcpy(adminperm, ini_table_get_entry(config, "Main", "admin"));
if(strcmp(adminperm, "true") == 0)
user.admin = 1;
}
ini_table_destroy(config);
return CMD_OK;
}
static int
writeconfig(void)
{
char cfg_path[MAXBUF] = { 0 };
char astr[10] = { 0 };
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.ini");
#else
strcat(cfg_path, "\\.interp.ini");
#endif
ini_table_s* config = ini_table_create();
if(ini_table_read_from_file(config, cfg_path)) {
ini_table_create_entry(config, "Main", "prompt", user.prompt);
myitoa(user.loglevel, astr);
ini_table_create_entry(config, "Main", "loglevel", astr);
if(user.admin == 1)
ini_table_create_entry(config, "Main", "admin", "true");
else
ini_table_create_entry(config, "Main", "admin", "false");
ini_table_write_to_file(config, cfg_path);
}
ini_table_destroy(config);
return CMD_OK;
}
#ifdef _MSV_VER
char*
get_cmdln(void)
{
char ch;
int i = 0, flag = 0;
for (i = 0; i < MAX_LINE && flag == 0; ++i) {
ch = _getch();
switch (ch) {
case 13:
str[i] = '\0';
flag = 1;
break;
case '\b':
if (i > 0) i--;
str[i--] = '\0';
printf("\b \b");
break;
default:
str[i] = ch;
printf("%c", ch);
}
}
str[strlen(str)] = '\0';
return &str[0];
}
#endif
/**
* main.c, pretty self explanitory I hope.
* Will be changed to take command line options eventually.
*/
int
main(int argc, char** argv)
{
size_t size, len;
bool bDo = true;
//char* cmd_string = NULL;
init();
readconfig();
do {
len = 0;
char* cmd_string = NULL;
printf("%s ", user.prompt);
#ifdef _MSV_VER
cmd_string = get_cmdln();
#else
getline(&cmd_string, &len, stdin);
#endif
size = (size_t)strlen(cmd_string);
char** splitresult = split(cmd_string, ' ', &size);
bDo = proc_cmds(splitresult, size);
free(&splitresult[0]);
} while (bDo);
writeconfig();
return EXIT_SUCCESS;
}

141
src/threadpool.c Executable file
View File

@ -0,0 +1,141 @@
#include "threadpool.h"
ThreadPool*
thread_pool_init(size_t num_threads)
{
ThreadPool* pool = malloc(sizeof(ThreadPool));
if(!pool) {
perror("Memory allocation failed for thread pool");
return NULL;
}
if (mtx_init(&pool->lock, mtx_plain) != thrd_success) {
perror("Mutex initialization failed");
free(pool);
return NULL;
}
if (cnd_init(&pool->condition) != thrd_success) {
perror("Condition variable initialization failed");
mtx_destroy(&pool->lock);
free(pool);
return NULL;
}
pool->task_queue = NULL;
pool->num_threads = num_threads > 0 ? num_threads : DEFAULT_THREAD_POOL_SIZE;
pool->shutdown = false;
pool->threads = malloc(pool->num_threads * sizeof(thrd_t));
if (!pool->threads) {
perror("Memory allocation failed for thread pool threads");
mtx_destroy(&pool->lock);
cnd_destroy(&pool->condition);
free(pool);
return NULL;
}
for (size_t i = 0; i < pool->num_threads; ++i) {
if (thrd_create(&pool->threads[i], thread_function, pool) != thrd_success) {
perror("Thread creation failed");
thread_pool_destroy(pool);
return NULL;
}
}
return pool;
}
void
thread_pool_destroy(ThreadPool* pool)
{
if (!pool)
return;
mtx_lock(&pool->lock);
pool->shutdown = true;
mtx_unlock(&pool->lock);
cnd_broadcast(&pool->condition);
for (size_t i = 0; i < pool->num_threads; ++i) {
thrd_join(pool->threads[i], NULL);
printf("Thread destroyed\n");
}
free(pool->threads);
mtx_destroy(&pool->lock);
cnd_destroy(&pool->condition);
free(pool);
}
bool
thread_pool_enqueue(ThreadPool* pool, void (*function)(void*), void* arg)
{
if (!pool || !function)
return false;
Task* new_task = malloc(sizeof(Task));
if (!new_task) {
perror("Memory allocation failed for new task");
return false;
}
new_task->function = function;
new_task->arg = arg;
new_task->next = NULL;
mtx_lock(&pool->lock);
if (pool->task_queue == NULL)
pool->task_queue = new_task;
else {
Task* last_task = pool->task_queue;
while (last_task->next != NULL)
last_task = last_task->next;
last_task->next = new_task;
}
cnd_signal(&pool->condition);
mtx_unlock(&pool->lock);
return true;
}
int
thread_function(void* arg)
{
ThreadPool* pool = (ThreadPool*)arg;
while (true) {
mtx_lock(&pool->lock);
while (!pool->task_queue && !pool->shutdown)
cnd_wait(&pool->condition, &pool->lock);
if (pool->shutdown) {
mtx_unlock(&pool->lock);
return thrd_success;
}
Task* task = pool->task_queue;
if (task) {
pool->task_queue = task->next;
}
mtx_unlock(&pool->lock);
if (task) {
task->function(task->arg);
free(task);
}
}
}

300
src/utils/config.c Normal file
View File

@ -0,0 +1,300 @@
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_WIN32) || defined(_WIN64)
#define strcasecmp _stricmp
#define strncasecmp _strnicmp
#else
#include <strings.h>
#endif
#include "utils/config.h"
static void print_log(int line, const char* msg, const char* extra)
{
printf("TConfig [Line: %i]: ", line);
printf(msg, extra);
printf("\n");
}
static ini_entry_s* _ini_entry_create(ini_section_s* section,
const char* key, const char* value)
{
if ((section->size % 10) == 0) {
section->entry =
realloc(section->entry, (10+section->size) * sizeof(ini_entry_s));
}
ini_entry_s* entry = &section->entry[section->size++];
entry->key = malloc((strlen(key)+1)*sizeof(char));
entry->value = malloc((strlen(value)+1)*sizeof(char));
strcpy(entry->key, key);
strcpy(entry->value, value);
return entry;
}
static ini_section_s* _ini_section_create(ini_table_s* table,
const char* section_name)
{
if ((table->size % 10) == 0) {
table->section =
realloc(table->section, (10+table->size) * sizeof(ini_section_s));
}
ini_section_s* section = &table->section[table->size++];
section->size = 0;
section->name = malloc((strlen(section_name)+1) * sizeof(char));
strcpy(section->name, section_name);
section->entry = malloc(10 * sizeof(ini_entry_s));
return section;
}
static ini_section_s* _ini_section_find(ini_table_s* table, const char* name)
{
for (int i = 0; i < table->size; i++) {
if (strcmp(table->section[i].name, name) == 0) {
return &table->section[i];
}
}
return NULL;
}
static ini_entry_s* _ini_entry_find(ini_section_s* section, const char* key)
{
for (int i = 0; i < section->size; i++) {
if (strcmp(section->entry[i].key, key) == 0) {
return &section->entry[i];
}
}
return NULL;
}
static ini_entry_s* _ini_entry_get(ini_table_s* table, const char* section_name,
const char* key)
{
ini_section_s* section = _ini_section_find(table, section_name);
if (section == NULL) {
return NULL;
}
ini_entry_s* entry = _ini_entry_find(section, key);
if (entry == NULL) {
return NULL;
}
return entry;
}
ini_table_s* ini_table_create()
{
ini_table_s* table = malloc(sizeof(ini_table_s));
table->size = 0;
table->section = malloc(10 * sizeof(ini_section_s));
return table;
}
void ini_table_destroy(ini_table_s* table)
{
for (int i = 0; i < table->size; i++) {
ini_section_s* section = &table->section[i];
for (int q = 0; q < section->size; q++) {
ini_entry_s* entry = &section->entry[q];
free(entry->key);
free(entry->value);
}
free(section->entry);
free(section->name);
}
free(table->section);
free(table);
}
bool ini_table_read_from_file(ini_table_s* table, const char* file)
{
FILE* f = fopen(file, "r");
if (f == NULL) return false;
enum {Section, Key, Value, Comment} state = Section;
int c;
int position = 0;
int spaces = 0;
int line = 0;
int buffer_size = 128 * sizeof(char);
char* buf = malloc(buffer_size);
char* value = NULL;
ini_section_s* current_section = NULL;
memset(buf, '\0', buffer_size);
while((c = getc(f)) != EOF) {
if (position > buffer_size-2) {
buffer_size += 128 * sizeof(char);
size_t value_offset = value == NULL ? 0 : value - buf;
buf = realloc(buf, buffer_size);
memset(buf+position, '\0', buffer_size-position);
if (value != NULL)
value = buf + value_offset;
}
switch(c) {
case ' ':
switch(state) {
case Value: if (value[0] != '\0') spaces++; break;
default: if (buf[0] != '\0') spaces++; break;
}
break;
case ';':
if (state == Value) {
buf[position++] = c;
break;
}
else {
state = Comment;
buf[position++] = c;
while (c != EOF && c != '\n') {
c = getc(f);
if (c != EOF && c != '\n') buf[position++] = c;
}
}
// fallthrough
case '\n':
// fallthrough
case EOF:
line++;
if (state == Value) {
if (current_section == NULL) {
current_section = _ini_section_create(table, "");
}
_ini_entry_create(current_section, buf, value);
value = NULL;
} else if (state == Comment) {
if (current_section == NULL) {
current_section = _ini_section_create(table, "");
}
_ini_entry_create(current_section, buf, "");
} else if (state == Section) {
print_log(line, "Section `%s' missing `]' operator.", buf);
} else if(state == Key && position) {
print_log(line, "Key `%s' missing `=' operator.", buf);
}
memset(buf, '\0', buffer_size);
state = Key;
position = 0;
spaces = 0;
break;
case '[':
state = Section;
break;
case ']':
current_section = _ini_section_create(table, buf);
memset(buf, '\0', buffer_size);
position = 0;
spaces = 0;
state = Key;
break;
case '=':
if (state == Key) {
state = Value;
buf[position++] = '\0';
value = buf + position;
spaces = 0;
continue;
}
default:
for(;spaces > 0; spaces--) buf[position++] = ' ';
buf[position++] = c;
break;
}
}
free(buf);
fclose(f);
return true;
}
bool ini_table_write_to_file(ini_table_s* table, const char* file)
{
FILE* f = fopen(file, "w+");
if (f == NULL) return false;
for (int i = 0; i < table->size; i++) {
ini_section_s* section = &table->section[i];
fprintf(f, i > 0 ? "\n[%s]\n" : "[%s]\n", section->name);
for (int q = 0; q < section->size; q++) {
ini_entry_s* entry = &section->entry[q];
if (entry->key[0] == ';') {
fprintf(f, "%s\n", entry->key);
} else {
fprintf(f, "%s = %s\n", entry->key, entry->value);
}
}
}
fclose(f);
return true;
}
void ini_table_create_entry(ini_table_s* table, const char* section_name,
const char* key, const char* value)
{
ini_section_s* section = _ini_section_find(table, section_name);
if (section == NULL) {
section = _ini_section_create(table, section_name);
}
ini_entry_s* entry = _ini_entry_find(section, key);
if (entry == NULL) {
entry = _ini_entry_create(section, key, value);
}else {
free(entry->value);
entry->value = malloc((strlen(value)+1) * sizeof(char));
strcpy(entry->value, value);
}
}
bool ini_table_check_entry(ini_table_s* table, const char* section_name,
const char* key)
{
return (_ini_entry_get(table, section_name, key) != NULL);
}
const char* ini_table_get_entry(ini_table_s* table, const char* section_name,
const char* key)
{
ini_entry_s* entry = _ini_entry_get(table, section_name, key);
if (entry == NULL) {
return NULL;
}
return entry->value;
}
bool ini_table_get_entry_as_int(ini_table_s* table, const char* section_name,
const char* key, int* value)
{
const char* val = ini_table_get_entry(table, section_name, key);
if (val == NULL) {
return false;
}
*value = atoi(val);
return true;
}
bool ini_table_get_entry_as_bool(ini_table_s* table, const char* section_name,
const char* key, bool* value)
{
const char* val = ini_table_get_entry(table, section_name, key);
if (val == NULL) {
return false;
}
if (strcasecmp(val, "on") == 0 || strcasecmp(val, "true") == 0) {
*value = true;
}else {
*value = false;
}
return true;
}

232
src/utils/filesys.c Normal file
View File

@ -0,0 +1,232 @@
#include "utils/filesys.h"
#include "utils/config.h"
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 594 )
#pragma warning( disable : 4047 )
#pragma warning( disable : 4024 )
#endif
/**
* @brief find_cfgfile search for ini in a few predefined locations
*
* @details make three attempts to locate the cfg file requested
* using three different strategies (/etc, $HOME, and
* the home for the current user using the passwd
* database), errors out with an integer code if
* finally unsuccessful. If the bUseDot is set the
* search will make the file name a dot file during
* search in the user directories
*
* @param const string file_name: name of cfg file to search for
* @param string path_found: result of successful search
* @param boolean make it a dot file flag
* @return integer status code, path_found is NULLed if unsuccessful
*/
#ifndef _MSC_VER
int
find_cfgfile(const char* file_name, char* path_found, bool bUseDot)
{
if(file_name == NULL && path_found == NULL)
return CMD_ARGS;
char search_this_path[MAXSIZE];
char* sp = &search_this_path[0];
strcpy(sp, "/etc");
// Search /etc first for a plain,
// un-decorated (no dot prefix)
// file_name
memset(sp, 0, strlen(search_this_path));
sp = strcpy(search_this_path, "/etc");
sp = strcat(search_this_path, "/");
sp = strcat(sp, file_name);
if(access(sp, F_OK) != -1 ) {
strcpy(path_found, sp);
return CMD_OK;
}
// then try for whatever is in $HOME,
// if bUseDot == true prefix the file
// name with a dot.
char* homedir = getenv("HOME");
if(homedir != NULL) {
memset(sp, 0, strlen(search_this_path));
strcpy(sp, homedir);
strcat(sp, "/");
if(bUseDot) strcat(sp, ".");
strcat(sp, file_name);
if(access(sp, F_OK) != -1 ) {
strcpy(path_found, sp);
return CMD_OK;
}
}
// Finally try the user's directory as
// specified in the passwd data base
uid_t uid = getuid();
struct passwd* pw = getpwuid(uid);
if(pw != NULL) {
memset(sp, 0, strlen(search_this_path));
strcpy(sp, pw->pw_dir);
strcat(sp, "/");
if(bUseDot) strcat(sp, ".");
strcat(sp, file_name);
if(access(search_this_path, F_OK) != -1 ) {
strcpy(path_found, sp);
return CMD_OK;
}
}
// nothing worked, set the result string
// param to null and return an error code
strcpy(path_found, "\0");
return CMD_FILENF;
}
#endif
/**
* @brief create_cfgfile create a new ini file
*
* @details copies the passed parameter to a buffer to
* protect against file names larger than 256
* chars.
*
* @param const char* the full path of the new file
* @return integer status code
*/
int
create_cfgfile(const char* file_path)
{
char cfg_path[MAXBUF];
memset(cfg_path, 0, sizeof(cfg_path));
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.ini");
#else
strcat(cfg_path, "\\.interp.ini");
#endif
ini_table_s* config = ini_table_create();
if(!ini_table_read_from_file(config, cfg_path)) {
// create new table
ini_table_create_entry(config, "Main", "prompt", "> ");
ini_table_create_entry(config, "Main", "loglevel", "0");
ini_table_create_entry(config, "Main", "admin", "false");
ini_table_write_to_file(config, cfg_path);
}
ini_table_destroy(config);
return CMD_OK;
}
#ifndef _MSC_VER
void
get_userdir(char* path)
{
uid_t uid = getuid();
struct passwd* pw = getpwuid(uid);
strcpy(path, pw->pw_dir);
}
#else
void
get_userdir(char* path)
{
wchar_t wpath[MAXBUF * 2] = { 0 };
if (FAILED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, wpath)))
path = NULL;
else
wcstombs(path, wpath, MAXBUF);
}
#endif
int
write_motd(char* path, const char* motd)
{
char newm[MAXMOTD];
memset(newm, '\0', MAXMOTD);
mid(motd, 6, find_ch_index(motd, '"'), newm, strlen(motd));
remove_first(newm, "\"");
FILE* fp = fopen(path, "w");
if (fp == NULL) return CMD_ERR;
fprintf(fp, "%s", newm);
fclose(fp);
return CMD_OK;
}
int
read_motd(const char* path)
{
FILE* stream;
char line[MAXMOTD];
int errno;
errno = CMD_OK;
if((stream = fopen(path, "r")) != NULL) {
if (NULL != fgets(&line, MAXMOTD, stream))
errno = CMD_FILEEXST;
fclose(stream);
}
return errno;
}
const char*
get_keyvalue(const char* key, const char* def)
{
//struct config_setting_t const *setting;
char cfg_path[MAXBUF];
memset(cfg_path, 0, sizeof(cfg_path));
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.ini");
#else
strcat(cfg_path, "\\.interp.ini");
#endif
if(!file_exists(cfg_path))
create_cfgfile(cfg_path);
return "";
}
int
set_keyvalue(const char* key, const char* value)
{
char cfg_path[MAXBUF];
memset(cfg_path, 0, sizeof(cfg_path));
get_userdir(cfg_path);
#ifndef _MSC_VER
strcat(cfg_path, "/.interp.ini");
#else
strcat(cfg_path, "\\.interp.ini");
#endif
return CMD_OK;
}
bool
file_exists(const char* filename)
{
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif

378
src/utils/huff.c Executable file
View File

@ -0,0 +1,378 @@
#define __STDC_WANT_LIB_EXT1__ 1
#include "utils/huff.h"
#include <string.h>
/**
* @file huff.c
* @author Tim O'Neil
* @date 3/9/2018
*
* @brief Probably pretty portable huffman coder
*
* @section DESCRIPTION
*
* Huffman coder for making text blobs psuedo-encrypted
* and psuedo-compressed and editable only through this
* the application (more or less). This code is not
* tested with other implementations, so its totally
* possible to be a wonky, one-off, not comatible, non-
* standard implementation (if there is such a thing.)
*/
/**
* @brief encode coder entrypoint, this one of our public facing
* interfaces, the other being decode, below.
*
* @details Given a buffer of text encode it and write the output
* to a file.
* @param const char* file_name2: path of output file
* @param char* buf: string containing text to encode
*/
void
encode(const char* file_name2, char* buf)
{
FILE* en;
int freq[256] = {0};
info header[256];
char codes[256][40];
char code[40];
strcpy(code, "");
List_t mylist_en;
size_t num, no_of_chars;
en = fopen(file_name2, "w");
if(en) {
find_freq(buf, freq);
no_of_chars = strlen(buf);
if(no_of_chars > 0) {
make_tree(&mylist_en, freq);
num = create_header(freq, (int)no_of_chars, header);
find_code(mylist_en.head, code, codes);
compress(buf, en, codes, (int)no_of_chars, header, freq, (int)num);
}
}
fclose(en);
}
/**
* @brief decode: decode a buffer of huffman encoded text
*
* @details Decode a file and send the output to stdout
*
* @param const char*: file_name1: path of input file
*/
void
decode(const char* file_name1)
{
info y, * ptrrr;
FILE* en;
ptrrr = &y;
code_generated x, * ptrr;
ptrr = &x;
List_t mylist_de;
int i, num, no_of_chars, count = 0;
int freq[256] = {0};
en = fopen(file_name1, "r");
if(en) {
fread(ptrr, sizeof(code_generated), 1, en);
num = ptrr->c;
for(i = 0; i < num; ++i) {
fread(ptrrr, sizeof(info), 1, en);
freq[(int)ptrrr->ch] = ptrrr->freq;
}
make_tree(&mylist_de, freq);
no_of_chars = find_no_of_chars(freq);
node_t* root = mylist_de.head;
node_t* ptr = root;
while(fread(ptrr, sizeof(code_generated), 1, en) == 1)
ptr = decode_char(stdout, ptr, ptrr->c, 1, root, &count, no_of_chars);
}
fclose(en);
}
node_t*
decode_char(FILE* de, node_t* ptr, int x, int y,
node_t* root, int* count, int no_of_chars)
{
if(y != 9 &&(*count) != no_of_chars) {
if(ptr->llink == 0 && ptr->rlink == 0) {
fputc(ptr->c, de);
ptr = root;
++(*count);
ptr = decode_char(de, ptr, x, y, root, count, no_of_chars);
}
else if(x % 2 == 0 && ptr->llink)
ptr = decode_char(de, ptr->llink, x / 2, ++y, root, count, no_of_chars);
else if(x%2!=0 && ptr->rlink)
ptr = decode_char(de, ptr->rlink, x / 2, ++y, root, count, no_of_chars);
}
return ptr;
}
void
insert_in_list(List_t*, node_t*);
void
init_list(List_t* ptr)
{
ptr->head = 0;
}
void
disp_list(const List_t* ptr)
{
node_t* temp = ptr->head;
while(temp) {
printf("%d( %c )\t",temp->freq,temp->c);
temp = temp->link;
}
printf("\n");
}
void
make_node(List_t* ptr, int n, char c)
{
node_t* temp;
temp = (node_t*)malloc(sizeof(node_t));
temp->freq = n;
temp->c = c;
temp->link = 0;
temp->rlink = 0;
temp->llink = 0;
insert_in_list(ptr, temp);
//free(temp);
}
void
insert_in_list(List_t* ptr, node_t* t)
{
if(ptr->head == 0)
ptr->head = t;
else {
node_t* prev = 0;
node_t* pres = ptr->head;
while(pres && pres->freq <= t->freq) {
prev = pres;
pres = pres->link;
}
if(pres == ptr->head) {
ptr->head = t;
t->link = pres;
}
else if(pres == 0)
prev->link = t;
else {
t->link = pres;
prev->link = t;
}
}
}
void
make_list(List_t* ptr, int* freq)
{
int i;
for(i = 0; i < 256; ++i) {
if(freq[i] != 0)
make_node(ptr, freq[i], i);
}
}
void
find_freq(char* fp, int* freq)
{
char c;
unsigned n = 0;
while(n < strlen(fp)) {
c = fp[n++];
++freq[(int)c];
}
}
void
make_tree(List_t* ptr, int* freq)
{
node_t * t1, * t2;
init_list(ptr);
make_list(ptr,freq);
while(ptr->head->link != 0) {
t1=ptr->head;
t2=ptr->head->link;
ptr->head=t2->link;
t1->link = 0;
t2->link = 0;
node_t* temp;
temp=(node_t*)malloc(sizeof(node_t));
temp->freq = t1->freq + t2->freq;
temp->c = 0;
temp->link = 0;
temp->rlink = t2;
temp->llink = t1;
insert_in_list(ptr, temp);
}
}
void
find_code(node_t* ptr, char* code, char codes[256][40])
{
char temp[40];
if(ptr->rlink == 0 && ptr->llink == 0)
strcpy(codes[(int)(ptr->c)], code);
if(ptr->rlink != 0) {
strcpy(temp, code);
strcat(temp, "1");
find_code(ptr->rlink, temp, codes);
}
if(ptr->llink != 0) {
strcpy(temp, code);
strcat(temp, "0");
find_code(ptr->llink, temp, codes);
}
}
int
find_no_of_chars(int* freq)
{
int i, sum = 0;
for(i = 0; i < 256; ++i)
sum = sum + freq[i];
return sum;
}
void
compress(char* fp, FILE* en, char codes[256][40],
int no_of_chars, info* header, int* freq, int num)
{
char ch;
int n = 0, i = 0, j = 0, count = 0, k, l;
unsigned char c;
code_generated x;
char string_rev[9];
x.c = num;
fwrite(&x, sizeof(code_generated), 1 ,en);
for(k = 0, l = 0; k < 256; ++k) {
if(freq[k]) {
fwrite(&header[l], sizeof(info), 1, en);
++l;
}
}
while((ch = fp[n++]) != EOF) {
j = 0;
++count;
while(codes[(int)ch][j] != '\0') {
string_rev[i] = codes[(int)ch][j];
++i; ++j;
if(i == 8) {
string_rev[i] = '\0';
strre(string_rev, (int)strlen(string_rev));
c = convert_string_char(string_rev);
strcpy(string_rev, "");
i = 0; x.c = c;
fwrite(&x,sizeof(x),1,en);
}
if(count == no_of_chars ) {
while(codes[(int)ch][j]) {
string_rev[i] = codes[(int)ch][j];
++i; ++j;
if(i == 8) {
string_rev[i] = '\0';
strre(string_rev, (int)strlen(string_rev));
c = convert_string_char(string_rev);
strcpy(string_rev, "");
i = 0; x.c=c;
fwrite(&x,sizeof(x),1,en);
}
}
string_rev[i] = '\0';
strre(string_rev, (int)strlen(string_rev));
c = convert_string_char(string_rev);
strcpy(string_rev, "");
x.c = c;
fwrite(&x, sizeof(x), 1, en);
}
}
}
}
void
strre(char* str, int n)
{
int i = 0, j = n - 1;
char temp;
while(i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
++i; --j;
}
str[n]='\0';
}
int
create_header(int* freq, int no_of_chars, info* header)
{
int i, j;
for(i = 0, j = 0; i < 256; ++i) {
if(freq[i] != 0) {
header[j].freq = freq[i];
header[j].ch = i;
++j;
}
}
return j;
}
unsigned char
convert_string_char(char string[8])
{
int i=0;
unsigned char c = 0;
while(string[i]) {
if(string[i] == '1') {
c = c * 2;
c = c + 1;
}
else
c = c * 2;
++i;
}
return c;
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<InterpExtra>$(ProjectDir)..\extra</InterpExtra>
</PropertyGroup>
<PropertyGroup />
<ItemDefinitionGroup>
<ClCompile>
<AdditionalIncludeDirectories>
</AdditionalIncludeDirectories>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<BuildMacro Include="InterpExtra">
<Value>$(InterpExtra)</Value>
<EnvironmentVariable>true</EnvironmentVariable>
</BuildMacro>
</ItemGroup>
</Project>

18
windows/README.md Normal file
View File

@ -0,0 +1,18 @@
# Building interp on Windows
I configured this project with Visual Studio 2022, I hope you have few problems, I've been noticing
over the last few years Microsoft has been pretty good about making visual studio projects back rev
compatible, if you have problems would love to hear about them, send reports to
interval1066@gmail.com.
If you haven't done it yet configure vcpkg to work with vs2022 or your preferred version of VS, I
understand versions after 2017 can do this with varying degrees of success.
Follow the instructions here for installation and configuration of vcpckg:
https://devblogs.microsoft.com/cppblog/vcpkg-is-now-included-with-visual-studio/
That should be all you need to do. In visual studio look at the include list in filesys.h; line
7 should be the include for libconfig.h. If its not underlined then the project is probably
ready to build.
(10/17/2024) All dependancies on libconfig have been removed.

View File

@ -0,0 +1,19 @@
#pragma once
#include <windows.h>
#define MAX_THREADS 10
typedef struct {
// Add any data members you need for your specific task
// ...
// Add synchronization objects if needed
CRITICAL_SECTION lock;
} TaskData;
typedef struct {
HANDLE hThread;
TaskData* pData;
} ThreadPoolThread;

View File

@ -0,0 +1,62 @@
#ifndef _UNISTD_H
#define _UNISTD_H 1
/* This file intended to serve as a drop-in replacement for
* unistd.h on Windows.
* Please add functionality as neeeded.
* Original file from: http://stackoverflow.com/a/826027
*/
#include <stdlib.h>
#include <io.h>
#ifndef _MSC_VER
#include <getopt.h> /* getopt at: https://gist.github.com/bikerm16/1b75e2dd20d839dcea58 */
#endif
#include <process.h> /* for getpid() and the exec..() family */
#include <direct.h> /* for _getcwd() and _chdir() */
#define srandom srand
#define random rand
/* Values for the second argument to access.
These may be OR'd together. */
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK R_OK /* execute permission - unsupported in Windows,
use R_OK instead. */
#define F_OK 0 /* Test for existence. */
#define access _access
#define dup2 _dup2
#define execve _execve
#define ftruncate _chsize
#define unlink _unlink
#define fileno _fileno
#define getcwd _getcwd
#define chdir _chdir
#define isatty _isatty
#define lseek _lseek
/* read, write, and close are NOT being #defined here,
* because while there are file handle specific versions for Windows,
* they probably don't work for sockets.
* You need to look at your app and consider whether
* to call e.g. closesocket().
*/
#define ssize_t int
#define size_t ssize_t
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
/* should be in some equivalent to <sys/types.h> */
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* unistd.h */

10
windows/interp.csproj Normal file
View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

31
windows/interp.sln Normal file
View File

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34112.27
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "interp", "interp.vcxproj", "{8BF84208-506F-49D2-B39B-4726A266C6E4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Debug|x64.ActiveCfg = Debug|x64
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Debug|x64.Build.0 = Debug|x64
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Debug|x86.ActiveCfg = Debug|Win32
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Debug|x86.Build.0 = Debug|Win32
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Release|x64.ActiveCfg = Release|x64
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Release|x64.Build.0 = Release|x64
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Release|x86.ActiveCfg = Release|Win32
{8BF84208-506F-49D2-B39B-4726A266C6E4}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {552FA45B-1EC0-4A26-B26B-CDB0DE0F816B}
EndGlobalSection
EndGlobal

173
windows/interp.vcxproj Normal file
View File

@ -0,0 +1,173 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\foo1.c" />
<ClCompile Include="..\src\intrinsic.c" />
<ClCompile Include="..\src\main.c" />
<ClCompile Include="..\src\utils\config.c" />
<ClCompile Include="..\src\utils\filesys.c" />
<ClCompile Include="..\src\utils\huff.c" />
<ClCompile Include="src\winstring_ext.c" />
<ClCompile Include="src\winthread.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\error_info.h" />
<ClInclude Include="..\include\foo1.h" />
<ClInclude Include="..\include\intrinsic.h" />
<ClInclude Include="..\include\logger.h" />
<ClInclude Include="..\include\parser.h" />
<ClInclude Include="..\include\simple_strlib.h" />
<ClInclude Include="..\include\support.h" />
<ClInclude Include="..\include\utils\config.h" />
<ClInclude Include="..\include\utils\filesys.h" />
<ClInclude Include="..\include\utils\huff.h" />
<ClInclude Include="include\winthread.h" />
<ClInclude Include="include\winunistd.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{8bf84208-506f-49d2-b39b-4726a266c6e4}</ProjectGuid>
<RootNamespace>interp</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="PropertySheet.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="PropertySheet.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="PropertySheet.props" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="PropertySheet.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ExecutablePath>$(VC_ExecutablePath_x64);$(CommonExecutablePath)</ExecutablePath>
<IncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath)</IncludePath>
<ExternalIncludePath>$(VC_IncludePath);$(WindowsSDK_IncludePath)</ExternalIncludePath>
</PropertyGroup>
<PropertyGroup Label="Vcpkg">
<VcpkgEnableManifest>false</VcpkgEnableManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir)..\include;$(ProjectDir)..\include\utils;$(ProjectDir)..\windows\include</AdditionalIncludeDirectories>
<DisableSpecificWarnings>4996;4113;28251</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>$(CoreLibraryDependencies);%(AdditionalDependencies);</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalIncludeDirectories>$(ProjectDir)..\include;$(ProjectDir)..\include\utils;$(ProjectDir)..\windows\include</AdditionalIncludeDirectories>
<LanguageStandard_C>stdc11</LanguageStandard_C>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\src\main.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\winstring_ext.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\utils\filesys.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\foo1.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\intrinsic.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\utils\huff.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="src\winthread.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\src\utils\config.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\include\simple_strlib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\support.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\utils\huff.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\winunistd.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\utils\filesys.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\parser.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\intrinsic.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\foo1.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\error_info.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\logger.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="include\winthread.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\include\utils\config.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -0,0 +1,59 @@
#include <stdlib.h>
#include <stdio.h>
size_t
getline(char** lineptr, size_t* n, FILE* stream)
{
char* bufptr = NULL, * p = bufptr;
size_t size;
int c;
if (lineptr == NULL)
return -1;
if (stream == NULL)
return -1;
if (n == NULL)
return -1;
bufptr = *lineptr;
size = *n;
c = fgetc(stream);
if (c == EOF)
return -1;
if (bufptr == NULL) {
bufptr = malloc(128);
if (bufptr == NULL)
return -1;
size = 128;
}
p = bufptr;
while (c != EOF) {
if ((size_t)(p - bufptr) > (size - 1)) {
size = size + 128;
bufptr = realloc(bufptr, size);
if (bufptr == NULL)
return -1;
p = bufptr + (size - 128);
}
*p++ = c;
if (c == '\n')
break;
c = fgetc(stream);
}
*p++ = '\0';
*lineptr = bufptr;
*n = size;
return p - bufptr - 1;
}

46
windows/src/winthread.c Normal file
View File

@ -0,0 +1,46 @@
#include "winthread.h"
TaskData yourTaskData;
ThreadPoolThread g_ThreadPool[MAX_THREADS];
DWORD WINAPI WorkerThread(LPVOID lpParam) {
TaskData* pData = (TaskData*)lpParam;
// Your thread's work goes here
// ...
// Release any resources or perform cleanup if needed
// ...
return 0;
}
void InitializeThreadPool() {
// Initialize the critical section
InitializeCriticalSection(&g_ThreadPool[0].pData->lock);
for (int i = 0; i < MAX_THREADS; ++i) {
// Initialize your task data structure and other necessary members
// ...
// Create threads
g_ThreadPool[i].pData = &yourTaskData; // Set your task data
g_ThreadPool[i].hThread = CreateThread(NULL, 0, WorkerThread, g_ThreadPool[i].pData, 0, NULL);
}
}
void CleanupThreadPool() {
for (int i = 0; i < MAX_THREADS; ++i) {
// Perform any cleanup or signal threads to exit gracefully
// ...
// Wait for thread termination
WaitForSingleObject(g_ThreadPool[i].hThread, INFINITE);
// Close thread handle
CloseHandle(g_ThreadPool[i].hThread);
}
// Delete the critical section
DeleteCriticalSection(&g_ThreadPool[0].pData->lock);
}