Thursday, 17 March 2016

Low-Level Programming_Post20

Low-Level Programming: Post 20 17/03/2016

March 17th 2016 is the date of the twentieth and last lesson on Low-Level Programming (in which I will need to post on this blog needed for the module).

Note: This post is the updated version of the last lesson on Low-Level Programming, as I now have the slides from the lesson to show to you.

Below are the main points taken from the lesson...
  • Bitmasks: What are they and how to use them. 
  • Memory Padding/Alignment: What they are and how they compare to exceptions.
  • Custom Allocations: How to maximize storage of flags or conditions. 
  • Summary: End of!
Bitmasks

Bitmasks
  • Last Week: Last week, we experimented with Bitfields which allow us to store booleans as a single bit inside a data type i.e. an int has 32 bit, so we can have 32 conditions.
  • Another Approach: We can actually approach the same problem from a different perspective. Bitmasking allows the use of logical operators to determine the bit’s status.
  • Padding: If we’re not concerned with controlling the padding or alignment of our data, it’s possible to store the data in a standard variable, either locally or globally.

Example Usage

  • Space Conscious: As with bitfields, reducing the number of booleans used to store conditionals in our code saves memory (due to minimum addressable types) over several booleans.
  • Arbitrary Args: Imagine a situation where we need to pass many args through to a function and we don’t want to wrap it in a struct, we could chose a field of bits instead. Each bit or bits representing a value or state.
  • Component Flags: Game objects are often formed of different component types. Using a mask, an object can store all of it’s component types effectively i.e. an object could be a renderable and movable component.

Vector of Bool

  • STL: The STL actually has a special container type for storing arrays of bits. It's the STL::Vector<bool> container class.
  • Non-Standard: It works differently to standard containers in the STL and actually breaks some of the generic ways of interacting with containers.
  • Disliked: For this reason, it's a useful but disliked container class.
Custom Allocators

New/Delete
  • Replacements: New & Delete are the functions that are responsible for allocating dynamic memory when you instantiated an object on the heap. We can replace these functions, but why?
  • Usage Errors: Using more than one delete on new memory yields undefined behaviour. If the new operator keeps a list of allocated addresses & the delete operator removes them for the list, it's easy to detect this use case & prevent undefined behaviour.
  • Underruns/Overruns: Programming mistakes can lead to data overruns (writing beyond the allocated memory) or underruns (writing prior to the allocation). The allocate can place markers at the beginning and end of the memory block and log these.

New/Delete Continued

  • Efficiency: The versions of new & delete that ship with compiles are general-purpose allocators & deallocators. The allocators therefore apply a middle of the road approach not favouring any one particular usage pattern of memory.
  • Usage Patterns: If you have an impressively good understanding of your program’s memory usage patterns, a custom new and delete operator may outperform the default shipped versions.
  • Performance Increase: You can, if correctly implemented gain some significant performance benefits by adapting the allocation memory model to match your programs memory signature.
  • Usage Statistics: How do we determine our programs memory usage patterns? We can accomplish this through logs.
  • Allocators: We can customise the allocators & deallocators can be used to collect information regarding memory usage.
  • Max Memory: Using this technique it’s possible to establish the baseline for memory usage but also the maximum dynamic memory usage requirement for your game.
Custom Allocators Continued
  • Alignment: The previous example demonstrates how easy it is to create a custom allocator. However, there's a couple issues with it and one in particular worth mentioning. Alignment.
  • Memory Placement: Many computer architectures require that data of particular types are placed in memory at particular kinds of addresses i.e. pointers should occur at addresses that are multiples of 4 (four-byte aligned) or that doubles multiples of 8.
  • Issues: This could lead to exceptions at runtime. Some architectures are more forgiving, but will offer better performance if alignment is maintained. Malloc is byte aligned, but adding the signature could throw off alignment.
C++ Custom Memory
  • Summary:
  1. To detect usage errors.
  2. Collect statistics about dynamically allocated memory.
  3. Increase speed of allocation & deallocations.
  4. To reduce the space overhead of default memory management.
  5. Compensate for sub-optimal alignment in default allocator.
Memory Alignment
  • Access: A computer accesses memory by a single memory word at a time. As long as the memory word size is at least as large as the smallest primitive data type, aligned accesses will always be accessed within a single word.
  • Split: If the highest and lowest bytes in a block of data are not within the same word, the computer must split the data access into multiple memory accesses.
  • TLB/Page Faults: To handle data split across multiple words, the processor must verify both pages before execution or be able to handle a TLB (translation lookaside buffer) miss or page fault during memory access as the instructions are executed.
Atomics
  • Remember those: When a single word is accessed, the operation is atomic. Other devices need to wait until the read or write has been fully completed.
  • Across the words: This is not necessarily the case when accessing multiple words e.g. the first word can be read by one device, both words written by another device and then the second word read by the first device. This is bad, as the data has now been altered mid-way through a read. Think of concurrency issues in threading.
  • X86: X86 is a platform that can handle both aligned and misaligned memory access. However, alignment is preferred for performance reasons.
  • Atomic Instructors: Modern CPUs provide atomic instructions (covered in previous lessons). This prevents issues with concurrent access to the same address.
  • Turn a Bit On: For atomic operations to operate correctly, the address you pass them must be at least four-byte aligned. This is due to atomic instructions and virtual memory.
  • Misaligned: If the address is misaligned, the operation requires at least two memory access operations. If data spanned two pages of virtual memory, this could lead to one part loaded and a page fault being generated when loading the second. The fault would destroy the atomicity of the operation. Because of this addresses must be at least four-byte aligned.
Padding
  • Alignment Concerns: You can see from the previous slides how ensuring data is correctly aligned in memory is essential to performance & stability.
  • Compilers: Compilers will ensure this behaviour for you. Forcing data types to be padded out to ensure they can be read in alignment. This can potentially lead to memory wastage.
  • Padding: It’s possible to create custom data structures and re-assign the basic types memory bits (last week). We can then pad out our structure to ensure optimum performance and memory usage.
Memory Padding

Padding Continued
  • Backwards Compatibility: As some architectures and older CPUs would crash when accessing data on odd memory addresses, the compiler will ensure all fields start on an even memory address.
  • Performance: As demonstrated earlier, accessing data in larger granularities and correctly aligned fields mean a huge boost to the CPU’s performance when accessing memory.
  • Placement: Padding can be added in between members to ensure the individual data items are on aligned boundaries. Data structures will often have members with different alignment requirements.
  • End-Of: The other area in which padding can be added is at the end of the structure. The compiler will add a final unnamed member. This allows each member of an array of structures to aligned.
  • Reordering: Consider reordering to make maximum use of the space. For example: two chars next to each other, followed by a short.
  • No Except: Packed structures (forcing the alignment) is normally used to conserve memory, they can also be used to force the size of data before transmitting it over a network. There’s no need to waste extra space with padding.
  • Performance Trade-off: Of course, whenever we use packed structures in this manner, there’s a space/time compromise being made. Slower performance for less memory.
  • Typical Alignments [32 Bits]:
  1. A char (one byte) will be 1-byte aligned.
  2. A short (two bytes) will be 2-byte aligned.
  3. An int (four bytes) will be 4-byte aligned.
  4. A long (four bytes) will be 4-byte aligned.
  5. A float (four bytes) will be 4-byte aligned. 
  6. A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux 
  7. Any pointer (four bytes) will be 4-byte aligned. (e.g.: char*, int*)  
For the practical in the lesson, we were given two simple options, work on the Chat Program, or leave the lesson early. I decided to try and work on the Chat Program and generally look at how SFML works. Sadly, I couldn't really work on the Chat Program since it had some errors. I will be attempting to work on them over the holiday. Despite this, however, I managed to complete the battleship game and made a good start on the Supporting Document needed for the assignment, with the objective being trying to fit the game into the Chat Program.

Thursday, 10 March 2016

Low-Level Programming_Post19

Low-Level Programming: Post 19 10/03/2016

March 10th 2016 is the date of the nineteenth lesson on Low-Level Programming.

This week's lesson started of in the same fashion as many of the other previous lesson, in that, we were shown what we were going to be covering in the lesson via bullet points. The main points taken from the lesson are listed below...

  • Exceptions: What are they and how to use them.
  • Assertions: What they are and how they compare to exceptions.
  • Bitfields: How to maximise storage of flags or conditions.
However, before we began looking into the parts from the points, we were shown a schedule of the time remaining that we had in the module. In it, it said that this week's lesson and next week's lesson were the last that had lecture slide in them, so in short, next week's post will be the last in this module. The other weeks listed were to focus on the assignments given to us and the Easter break.

Exceptions

Exceptions
  • What are they?: Exceptions provide a way to react to exceptional circumstances (runtime errors) in programs by passing control to a special handler.
  • Catch: When an exception occurs and if we want to handle this exception we need to ‘catch’ it.
  • Try-Block: The code that could generate an exception can be captured in a try block. When an exception occurs in that block, control is transferred to the exception handler.
Handling
  • Thrown: An exception is thrown using the throw keyword within a try block and exception handlers are declared with the keyword ‘catch’.
The Three Keywords
  • Throw: A program throws an exception when a problem shows up. To do this we need to use the ‘throw’ keyword.
  • Catch: A program catches an exception with a handler, at the place in the program where you want to handle the problem. For this we use the ‘catch’ keyword.
  • Try: The try block identifies the block of code for which particular exceptions will be activated. You follow this with one or more catch blocks.
  • Catch Blocks: Multiple catch statements can be used to catch different type of exceptions in case your try block raises more than one possible exception.
Catch Them All
  • Ellipsis: If you want a catch block that handles all exception types thrown or acts as a default, use the ellipsis operator.
  • Nested: It is even possible to nest try blocks. You can then forward a catch block to an external (higher up) catch block. To do this use the throw keyword.
C++ Standard Exceptions
  • C++: Provides a list of standard exceptions (classes) defined in . They are arranged in the following hierarchy.

Throwing
  • When: The general consensus and main use for exceptions is to report when external pre-conditions or invariants, such as disk space or memory are not available. In these cases the program is normally terminated and the exception is the mechanism for transmitting that information.
  • Guidance: Throw exceptions sparingly, when there’s an actual error and no way to deal with it.
  • Catch: Always endeavour to catch exceptions as close to the thrown statement as possible.
  • In Essence: If your code can detect an error and handle it, then do so. If the error is uncorrectable and outside of your scope, thrown an exception.
  • Performance: Exceptions can have a dramatic performance overhead. But this varies depending on the implementation by the compiler. The standard states how an exception must work, but the compilers are free to choose how to implement that functionality.
  • Performance Critical: Generally, if a code path is mission critical and performance is of the upmost concern you wouldn't want to use a throw during any of it.
  • Zero-Cost Model Exceptions:  A newer exception model is now commonly in use. It’s based around the idea that instead of setting up guards and checking for exceptions, the compiler generates a side table that maps any point that may throw to a list of handlers.
Zero Cost Exceptions Cont
  • Exception: Once the exception table is mapped and an exception is thrown, the list is checked to see which handler should be used and the call stack unwound.
  • Overhead:
  1. The zero model is free when no exception occurs.
  2. It can be ~20x slower to call an exception than to use an if check instead.  
  • Measuring Costs:  Measuring the difference is not easy i.e. cache misses:
  1. The side table is generally not loaded in memory.
  2. Determining the right exception handler involves RTTI and complex operations to run a test for the handler’s suitability i.e. a dynamic cast operation.
Exception-Safe Code
  • Strive: Always strive for exception-safe code. When an exception is thrown, exception safe functions should:
  1. Leak no resources.
  2. Prevent data structures to become corrupted. 
  • Safe Functions: Exception safe functions offer one of the following three guarantees:
  1. Basic guarantee.
  2. Strong guarantee.
  3. The no throw guarantee.
  • Resource Leak: The code breaks the resource leak rule, because if the memory allocation throws an exception, the mutex will never get unlocked.
  • Data Corruption: If memory allocation throws, bgImage is left pointing to a deleted object. In addition the background change count has been increased even though no new image has been setup.
  • Resolutions: How do we resolve these issues;
  1. Acquire a scope terminating mutex.
  2. Use a scoped smart pointer for creating the new image.
  • Basic Guarantees: The example we fixed now offers basic guarantee i.e. if an exception is thrown, everything in the program remains in a valid state. No data is corrupted and all objects remain in a consistent state.
  • Strong Guarantee: Functions that offer the strong guarantee, promise that if an exception is thrown the state of the program is unchanged. Calls to such functions are atomic i.e. they either completely succeed or completely fail.
  • No Throw: Functions that will never thrown an exception can be also be thought of as exception safe.
Exception Summary
  • Safe: Exception safe functions do not leak resources when an exception is thrown and no data structures should become corrupt as a part of this process.
  • Strong: The strong guarantee, means resources do not leak and no data should be changed. This can be achieved by copy-and-swap approaches, but has overheads.
  • Max Guarantee: The max level guaranteed by a function is no stronger that then weakest guarantee of the functions it goes on to call.
Asserts

Assertions
  • What are they?: Assertions are use to abort your program if the a specific assertion is not met. In essence it’s a way of explicitly stating something should hold true in your code base, otherwise something is wrong or more succinctly ‘make sure’.
  • Expression: If an asserted expression does not evaluate true, an error message displaying the expression being checked, along with source information can be printed to the console out or window.
  • Termination: The program will then terminate with no clean-up. A crash dump may also be generated.
  • Debugging (1): Assertions are commonly used to help track down program bugs. They can be used to track down conditions which aren't sensible during run time.
  • Additional Info: Using asserts, it’s possible to construct a string that contains information about the program’s running state and display it as part of the assert.
  • Debugging (2): If a debugger is attached to the running process and an assert is triggered, there’s the possibility to break into the program just as if a break point had been reached.
  • Debug Builds: Default release build settings will strip out asserts from the codebase. This in turn reduces the size of the final executable. When the compile option is disabled, you can be guaranteed that assert checks won’t be performed in release mode.
  • Asserts: Asserts are used to aid in debugging code that we have written and can react accordingly. They are primarily only used for debug builds but can be used in release builds if desired.
  • Exceptions: Exceptions are used when a set of circumstances outside of our program’s control is encountered and is detrimental to the programs function i.e. disk space issues.
  • Summary: Both asserts and exceptions are runtime. Asserts are useful for debugging the code we've written and managed. Exceptions are most useful when an issue has occurred outside of our control and allows us to communicate the exception to the user.
Static Asserts
  • C++11: Traditional asserts are performed at runtime. C++11 allows us to perform static asserts i.e. checks performed at compile time. If they fail the program will not compile.
Bitfields

Bitfields
  • Flags: Imagine that somewhere in your codebase that you wanted to store a series of conditions or flags on an object.
  • Bool (1): The simplest approach would be to utilise Boolean’s. One Boolean for each condition or flag.
  • Bool (2): For the space conscious amongst us, there’s an alternative approach to using Booleans (3xbytes).
  • Bitfields: Instead of Booleans as shown on the previous slide, let’s consider what a flag or condition is trying to represent; simply a state, either on or off just like binary.
  • Bits: It makes sense then that if only a single bit is required to show state, that we should be able to divide up a larger data type into bits and access each bit individually i.e. an integer which is 32bit large, can have 32 fields. One per bit.
  • Define: Defining a custom size for a field (struct/class only) is possible and supported and has the following syntax: declarator : constant-expression.
Following the end of the lecture slides, we then moved onto the practical side of the lesson. For this lesson, it was effectively carrying on from the past week(s) in trying to create a Chat Server & Chat Client. However, once I re-added the LibCaca files necessary for the project, I made a start in listing the various features in the Battleships game for the assignment. I realise that I went a little off-track on the practical, but it was important work nether-the-less.

Thursday, 3 March 2016

Low-Level Programming_Post18

Low-Level Programming: Post 18 03/03/2016

March 3rd 2016 is the date of the eighteenth lesson on Low-Level Programming.

This week's lesson was a particularly important one, as we were set the details for our second assignment, which I will talk about later in this post. The following main points that were taken from the lesson are listed below...

  • Dump Files: How to use them.
  • PDB Files: How to load symbols for debugging.
  • Assignment: In detail.
Dump Files

Dump Files
  • MSDN: States, a dump file is a snapshot of an app at the point in time the dump is taken. It shows what processes were executing and what modules are loaded. A copy of the heap can also be stored, allowing examination of the memory.
  • Crashes: When applications crash a crash dump is often generated. These can be essential in debugging the root cause of the crash. A copy of the heap is generally required.
  • Visual Studio: Opening a file in VS is like stopping at a breakpoint in a debug session. You can not continue execution but you can examine threads, stacks and variables.
Debugging Symbols
  • Symbols: Depending on the type of dump, symbol files may be required to enable proper debugging. You can easily load symbol files using modules inside visual studio.
  • Heaps: Visual Studio can load the symbols even if the application binary is not found. Includes a copy of the heap and stack.
  • No Heaps: The debugger has to load the app binaries to find the symbol information. The binaries must be an exact match.
Symbols/PDB Files

Symbols
  • Placeholders: Symbols are placeholders or mappings of variable and function names to respective memory addresses. This mapping is used to determine the location in memory when specific data or functions are used.
  • Linkage: Symbols are used during the linkage phase of your programs build process. This is why you will often get errors involving unknown external symbols i.e. the symbol’s mapping could not be determined.
  • Symbol Tables: When the symbols are being generated they placed in a table, there are symbol tables created as part of the compilation process and tables as part of the linkage phase as well.
Symbol Tables
  • Data Structure: The symbol table is an important data structure created and maintained by compilers in order to store information about the occurrence of entities such as variable names, function names, objects, classes interfaces etc.
  • Purposes: May serve the following purposes depending upon language:
  1. To store the name of all entities in a structured form at one place.
  2. To verify if a variable has been declared.
  3. Type checking, verifying assignments and expressions are correct.
  • Table: A symbol table should provide both an insert and a lookup function.
  • Insert: Used more frequently at the analysis stage of compilation. The operation is used to add information in to the table about unique names occurring in the source code (i.e. symbols).
  • Lookup: The lookup operation is used to search a name in the symbol table to determine:
  1. If the symbol exists and has been declared before it’s used.
  2. If the symbol is initialized.
  3. If it’s been declared multiple times and whether or not it’s in scope.
Compilation
  • Object Files: During the compilation process, source files are compiled and stored in resultant object files often with .obj or .o extensions. A symbol table is also included.
  • Output: The object file’s symbol table is a data structure and it maps the different items (variables, functions etc.) in the object file to names that the linker can understand.
  • Calls: If you call a function from your code, the compiler uses a placeholder value that tells the linker to look up the reference in the all available symbol files, looking for a match. This will have the address details required.
Libraries
  • Shared Libs: Shared libs or DLL also have a symbol table. This is a linker stage generated process. It names and exposes all the functions and data that are visible to users of the library. The static library in dungeon death is doing exactly this.
  • Runt-Time: Using the exposed symbol table, runtime linkage can be performed i.e. map the placeholder to it’s address. In essence this allows references to the memory location of the library which isn’t known until runtime.
DLLS
  • Shared Code: DLL’s (dynamic link libraries) are used to share code between developers. They also allow upgrade of library functionality without re-linking or re-compiling.
  • EXES: When programs rely on DLLs the executable informs the OS of the DLLs name. The loader than searches for the DLL file and loads it. Inside the DLL there is an export list.
  • Export List: The export list functions like the symbol list. When your executable calls a libraries function, the symbol is searched for and the memory address of the function is returned.
Address Space
  • Address Space: When windows loads the program, it creates a whole new “address space” for the program. This is the same process for DLL files. The DLLs addresses for exported functionality is dependent on where the OS has loaded the DLL in memory.
  • Relocatable: Unless you use special data inside DLL or the 3rd party company does, only a single instance of that DLL can be loaded at any given time. It’s not possible to load multiple versions of the same DLL in different address spaces.
PDB Files
  • Program Database: When debugging crash dumps, if we don’t have access to the symbol table, we’ll see a list of memory addresses in the call stack. To aid debugging we can utilise program database files.
  • PDB: PDB files are collections of all the symbol based information used in the program and libraries. They are directly linked to the version they were built against.
  • Debug: Debug build targets inside VS normally automatically created the PDB files for you.
  • Release: Release builds can create PDB files but often need to be manually enabled depending on build defaults.
After showing us about PDB files, we had to complete a mini tutorial. In this tutorial, we had to load and examine two 'dump' files, one where we needed to debug without a heap and debug with a heap. After a little bit of guidance, I managed to load up both files in two separate VS projects. The only difference I could see between the one with a heap and the one without a heap. One of them had some unknown values, whereas the other had it's value's set to 0. I couldn't remember which was which, unfortunately, nor do I know if I did it 100% correctly.

Assignment

Exercise 2 Overview
  • Multi-Player Game: Your assignment will be to create a multi-player game that is playable over a network. You will be responsible for creating both the client and server with respective logic.
  • In this exercise you will be recreating a version of Battleships. The exercise assignment details how the game is expected to play.
  • As the UWE network is firewalled, running the client and the server on the same PC during development is advisable i.e. use localhost for network address. 
Brief
  • Pirate Themed: You are asked to complete a faithful recreation of Battleships, however, rather than the traditional ships, the theme of your game should be pirates.
  • Game Grid: Fundamentally you will need to utilize a game grid that allows the player to position their ships and keep track of cannonballs fired.
Points of Interest
  • Pairs: The coursework will be in pairs. Where a pairing is not feasible a single person may complete the exercise at expense of the additional features. Each member of the pair will tackle their own extra feature.
  • Git: You will need to use git as your version control software. The git repository will need your submission.
  • SFML: It is expected that the networking functionality of your game is to be provided using the SFML library.
  • Games Mechanics: The games mechanics will be tested the game should run as expected. The rules have been provided within the assignment specification.
  • Essentials: Ship placement rules must also be implemented alongside the games turn based logic. Placement, firing, hit/miss stages and winning or losing the game are essentials.
  • Focus: Marks will be focused on the quality and suitability of the code in tandem with whether or not the game runs as expected.
  • Game/Server/Client: The solution should be broken down into three projects. One project for common code, one for the client and one for the project. Client and Server should be exes i.e. (DD)
  • Client: Should show two grids, one for player’s own ships and one for attacking. Consider how best to display this. Only a console UI is required for this.
  • Server: The server should show both player’s grids and any shots that have been fired. It will also need to include a list of all players connected. Clients should be able to send messages to each other. Again a console application is fine.
  • Ping: Implement a working ping/pong system. The client should display the latency to the server. The server should show the latency of all connected clients.
  • Disconnections: Make sure to handle disconnections gracefully, either when a client exits expectedly as well as when a client’s connection drops unexpectedly.
  • Remaining Clients: The remaining client should be shown a game won message as well as the reason for their victory i.e. dropped connection or rage quit.
  • Multiple Choice: You have a choice of one of the following three features:
  1. GUI: Using SFML create a graphical based version of your game. SFML provides basic OpenGL and window management support. Sprites may be a good choice.
  2. A.I: Implement a computer based opponent. Consider how they would place their ships and also how they explore the grid.
  3. Save/Loads: Create a profile system which allows games to be saved and resumed when both users reconnect. Should have choice to resume or create a new game.
  • UML: Provide class diagrams and explain relationships between classes. Why inheritance or composition?
  • Design: Evidence of planning and design stages either through discussion or diagrams. Researching a game’s requirements before writing the codebase will make it easier to implement.