Batchography: Parsing INI files from a Batch file

Often times you might want to write Batch file scripts to automate system administration tasks, and in addition to that you might want to pass configuration files to your Batch scripts.

This article, inspired by the Batchography book, shows you how to parse INI files and retrieve values from a given section and key.

Quick background

An INI file (or initialization file) is a text file that has the following format:

; comment

[section_name1]
Key1Name=Value1
.
.
.
[section_name2]
Key1Name=Value1
Key2Name=Value2
.
.
.

In the MS Windows operating system, a C/C++ programmer can read/write values from the INI files using the following APIs:

But can we do the same using Batch files?

Yes and in the next section, we show you how to read values from the INI file. Continue reading “Batchography: Parsing INI files from a Batch file”

Windows Error Reporting – Local crash dump collection – Graphical tool

According to Microsoft, the Windows Error Reporting feature is defined as follows:

The error reporting feature enables users to notify Microsoft of application faults, kernel faults, unresponsive applications, and other application specific problems. Microsoft can use the error reporting feature to provide customers with troubleshooting information, solutions, or updates for their specific problems. Developers can use this infrastructure to receive information that can be used to improve their applications.

When a program crashes in Windows, if it did not have built-in exception handling and crash dump generation, the Windows Error Reporting tool usually creates a crash dump and then queues it for upload to Microsoft.

The Windows Error Reporting tool can be configured in such a way to collect the crashes locally instead of queuing them for upload. The following document explains how.

In short, you have to add the follow registry values:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\<program_name>.exe]
"DumpFolder"=hex(2):43,00,3a,00,5c,00,74,00,65,00,6d,00,70,00,00,00
"DumpCount"=dword:00000100
"DumpType"=dword:00000002

Tweaking the registry manually is often not the best thing to do, therefore I wrote a simple open-source graphical utility that does the registry modification on your behalf.

WerFault GUI Tool

The graphical tool is very simple, but let me explain a few things.

WerFault supports three crash dump types: custom, mini or full memory dumps. Only when the custom dump is selected you can specify additional custom dump flags to WerFault. The custom flags are for advanced users.

In most cases it is advised to select the “Full dump” option because it captures lots of information needed for debugging. And finally, the dump count option lets you specify how many crash dumps to keep around.

There are two blue buttons that allows you to add or update an entry and to delete an entry. That’s it!

In the downloaded package, there’s an executable called crash.exe that you can use for testing. Continue reading “Windows Error Reporting – Local crash dump collection – Graphical tool”

HTMLPen – Free Online HTML authoring tool

HTMLPen is the most advanced online Visual HTML Editor and Text Editor available.

Some HTML features are :

  • Free Visual WYSIWYG Editor
  • Instant Previews and JS Previews
  • Advanced HTMLCSS and JS Color Coding and Code Completion.
  • Embedded HTML, CSS and JavaScript Beautifier.
  • Advanced Color Picker with Alpha Channel
  • Embedded Image to Base64 Converter
  • Respects your Privacy. No data ever leaves your computer
  • Stores your open projects on browser LocalStorage so you can keep working on them later

HTMLPen is also a powerful online Text Editor and Code Editor that can identify 144 different languages.

  • Syntax Highlighting
  • Code Completion
  • Can open Very Large (TB+) Files
  • Regex Search and Count Functions
  • Respects your Privacy. No data ever leaves your computer

HTMLPen can recognize many languages, including:

ABAP, ABC, ActionScript, ADA, Apache Conf, AsciiDoc, Assembly x86, AutoHotKey, BatchFile, Bro, C and C++, C#, C9 Search Results, Cirru, Clojure, Cobol, CoffeeScript, ColdFusion, Csound, Csound Document, Csound Score, CSS, Curly, D, Dart, Diff, Django, Dockerfile, Dot, Drools, Edifact, Eiffel, EJS, Elixir, Elm, Erlang, Forth, Fortran, FreeMarker, Gcode, Gherkin, Gitignore, Glsl, Go, Gobstones, GraphQLSchema, Groovy, HAML, Handlebars, Haskell, Haskell Cabal, haXe, Hjson, HTML, HTML (Elixir), HTML (Ruby), INI, Io, Jack, Jade, JavaJavaScriptJSON, JSONiq, JSP, JSSM, JSX, Julia, Kotlin, LaTeX, LESS, Liquid, Lisp, LiveScript, LogiQL, LSL, Lua, LuaPage, Lucene, Makefile, Markdown, Mask, MATLAB, Maze, MEL, MIXAL, MUSHCode, MySQL, Nix, Nix, NSIS, Objective-C, OCaml, Pascal, Perl, pgSQL, PHP, Pig, Powershell, Praat, Prolog, Properties, Protobuf, Python, R, Razor, RDoc, Red, RHTML, RST, Ruby, Rust, SASS, SCAD, Scala, Scheme, SCSS, SH, SJS, Smarty, snippets, Soy Template, Space, SQL, SQLServer, Stylus, SVG, Swift, Tcl, Tex, Textile, Toml, TSX, Twig, Typescript, Vala, VBScript, Velocity, Verilog, VHDL, Wollok, XML, XQuery, YAML

Made in sunny California.

HTMLPen.com 2018

You might also like:

Batchography: Function calls in Batch file scripts

The Batch files programming language is a powerful language but unfortunately, not many people know it that well. In an effort to pass the knowledge, in this article I am going to illustrate how to do function calls in Batch scripts.

Let’s get started!

The basics

The following example illustrates how to define and call a function:

@echo off
:main
  call :hello
  call :world
  goto :eof

:hello
  echo This is the Hello function
  goto :eof

:world
  echo This is a second function call
  goto :eof

The following outputs:

This is the Hello function
This is a second function call

From the example above, it is obvious how to call a function and return from it:

  1. Define a function as you would define a label
  2. Use the “CALL :function-name” syntax to call the function
  3. Use the “GOTO :EOF” to return from the function back to the caller

Recursive functions are also supported in the Batch language. Just make sure you avoid infinite recursion. Continue reading “Batchography: Function calls in Batch file scripts”

Shuffling function addresses in C/C++ with MSVC

The Microsoft C/C++ compiler allows you to specify link order of functions or variables. Using the #pragma directive with either code_seg or data_seg and specifying the segment name and its sorting key, you can tell the linker how to place the object code in the final executable.

Let’s start with a simple example:

#pragma code_seg(push, ".text$EB009")
__declspec(noinline) void f1()
{
    printf("this is f1()\n");
}
#pragma code_seg(pop)


#pragma code_seg(push, ".text$EB005")
__declspec(noinline) void f2()
{
    printf("this is f2()\n");
}
#pragma code_seg(pop)


#pragma code_seg(push, ".text$EB001")
__declspec(noinline) void f3()
{
    printf("this is f3()\n");
}
#pragma code_seg(pop)

int main()
{
    f1();
    f2();
    f3();
    return 0;
}

When the code_seg pragma is used, we can specify where the subsequent code should lie (in which section in the PE file). When the section name contains the “$” sign, then the subsequent text is not part of the section name (the string prior to the “$”) and instead is used as a sorting key. Continue reading “Shuffling function addresses in C/C++ with MSVC”

Excerpts and notes from the “Soft Skills” book

A couple of years ago, I was reading the book entitled “Soft Skills” by John Sonmez. The book was super useful to me especially that I was exploring ways to improve my soft skills and learn all the tricks I can regarding how to start my own business, organize my time, etc.

In this blog post, I share with you some of the takeaways and excerpts from that book.

Continue reading “Excerpts and notes from the “Soft Skills” book”

Batchography: Polyglot Batch files and C++ – Self compiling C++ script

This article is part of the Batchography articles series and today, I am going to show you how to write a valid Batch file that is also a valid C/C++ file. The Batch file part of the source can do anything, however in this article, its sole purpose will be to compile itself and run the compile C++ program.

Let’s get started with the Polyglot source code:

Continue reading “Batchography: Polyglot Batch files and C++ – Self compiling C++ script”

Programming with Emojis

I ran into the EmojiCode website. Emojicode is an open-source, full-blown programming language consisting of emojis.

I personally did not like that language, but it is worthwhile mentioning:

No idea what that code does…I don’t care 😉

Meanwhile, if you are a C++ programmer, enjoy the following, legitimate, piece of code that redefine keywords into emojis and then the fun starts:

You might  also like:

Zipping all files in a Git repository

Hello,

This is a quick / reference post illustrating how to archive (zip format) all the files in a branch in a Git repository.

From the command prompt, type:

 
git archive --format=zip -o files.zip master

Explanation:

  1. The “–format” argument lets you specify the archive type. I used the zip file format
  2. The “-o” argument lets you specify the output file name
  3. master” is the name of the branch to be archived.

 

flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the right book for you.

Available in print or e-book editions from Amazon.
flower separatorYou might also like:

 

Futurama: Bender – Robot Grace – or the Geek’s prayer

If you are a fan of Futurama, and Bender the bending robot in particular, you might like this audio clip where Bender says grace before eating:

In the name of all that is good and logical, we give thanks for the chemical energy we are about to absorb. To quote the prophet Jerematic, one zero zero zero one zero one zero one zero one zero one… [Time lapse.] Zero zero one… zero one one zero zero one…two.
Amen.

You might also like:

strtok() C++ wrapper

In this article, I share with you a simple C++ class that wraps the string tokenization function strtok(). The QuickTokenizer class makes it easy to tokenize and enumerate the tokens in a thread-safe manner.

The class code

//////////////////////////////////////////////////////////////////////////
class QuickTokenizer
{
private:
  char *buf;
  char *token;
  char *ctx;

  void FreeBuffers()
  {
    if (this->token != NULL)
    {
      free(this->token);
      this->token = NULL;
    }
    if (this->buf != NULL)
    {
      free(this->buf);
      this->buf = NULL;
    }
  }

public:
  QuickTokenizer() : buf(NULL), token(NULL)
  {

  }

  const char *Tokenize(
    const char *str,
    const char *tok)
  {

    this->buf = _strdup(str);
    this->token = _strdup(tok);

    return strtok_s(buf, token, &ctx);
  }

  const char *NextToken()
  {
    return strtok_s(NULL, token, &ctx);
  }

  ~QuickTokenizer()
  {
    FreeBuffers();
  }
};

Continue reading “strtok() C++ wrapper”

Detect executable format using Python

In this article, I am sharing with you a small Python script that lets you detect if a file is an executable file and what platform the executable is targeting.

The following formats for 32 bits and 64bits processors are supported:

  • Mach-O files: both regular and universal formats
  • Windows PE files
  • Linux ELF files

The script

#---------------------------------------------------------------------
EXEFLAG_NONE        = 0x0000
EXEFLAG_LINUX       = 0x0001
EXEFLAG_WINDOWS     = 0x0002
EXEFLAG_MACOS       = 0x0004
EXEFLAG_MACOS_FAT   = 0x0008
EXEFLAG_32BITS      = 0x0010
EXEFLAG_64BITS      = 0x0020

# Keep signatures sorted by size
_EXE_SIGNATURES = (
    ("\x4D\x5A", EXEFLAG_WINDOWS),
    ("\xCE\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_32BITS),
    ("\xCF\xFA\xED\xFE", EXEFLAG_MACOS | EXEFLAG_64BITS),
    ("\xBE\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_32BITS | EXEFLAG_MACOS_FAT),
    ("\xBF\xBA\xFE\xCA", EXEFLAG_MACOS | EXEFLAG_64BITS | EXEFLAG_MACOS_FAT),
    ("\x7F\x45\x4C\x46\x01", EXEFLAG_LINUX | EXEFLAG_32BITS),
    ("\x7F\x45\x4C\x46\x02", EXEFLAG_LINUX | EXEFLAG_64BITS)
)

def get_exeflags(filepath):
    try:
        with open(filepath, "rb") as f:
            buf = ""
            buf_len = 0
            for sig, flags in _EXE_SIGNATURES:
                sig_len = len(sig)
                if buf_len < sig_len:
                    buf += f.read(sig_len - buf_len)
                    buf_len = sig_len

                if buf == sig:
                    return flags
    except:
        pass

    return EXEFLAG_NONE

Continue reading “Detect executable format using Python”

Introducing Ganxo v0.1 – An open source API hooking framework

Hello,

Today I release the first Alpha version of Ganxo (pronounced as “Gun Show” or “Gan Chou”), an open source API hooking framework. In Catalan, Ganxo means “hook”, thus the framework’s name.

Writing an API hooking framework was always on my to do list. I started developing Ganxo back in April 2016 and after two weeks of development during my free time, I got busy with other things and abandoned my efforts.

My initial goals were to accomplish the following before going public with it:

  • Support x86 and x64 hooking
  • Write a more extensive test suite
  • Fully document it

This past weekend, I decided to release Ganxo even though I have not met all my goals. As of today, Ganxo works on MS Windows and supports x86 API hooking. The groundwork is laid down and it should be easy to add x64 bits hooking support on Windows or even just port it to other operating systems.

Feel free to clone the code from here and start using it today.

Stay tuned, I plan more features in the coming future!

flower separator
batchography-good-resDo you want to master Batch Files programming? Look no further, the Batchography is the right book for you.

Available in print or e-book editions from Amazon.
flower separator

You might also like:

Batchography: Batch files and Unicode

Recently, I had to update my popular utility that resets NTFS files permission to support Unicode paths. I had to investigate how to add Unicode support in Batch scripts. It seems that this was a topic I forgot to add into my comprehensive Batch files programming book.

This article is the result of my investigation, in which I am going to show you how to add Unicode support to your Batch file scripts in 3 easy steps.

Continue reading “Batchography: Batch files and Unicode”