More to come...
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

411 rindas
22KB

  1. #ifndef CHAPTER_0_SOURCE // These two, and "#endif" at the end of the file are header guards, we'll talk about them more when the time comes!
  2. #define CHAPTER_0_SOURCE
  3. #include "chapter_0.h" // We're pasting macros, enumerations and function declarations from header file "chapter_0.h" into this file, at this location.
  4. /*
  5. Function 'in' will perform read system call, literally reading 'size' bytes from standard input, which is terminal in most kernels unless it's redirected to some other file
  6. descriptor, and store it at 'data' memory address, if there's enough space in it. Since this is one of the core functions, if it fails, we want to abort the program and see what
  7. we did wrong... Maybe there wasn't enough space in 'data', maybe 'size' was negative and it overflowed because read system call internally uses 'size_t / unsigned long int', which
  8. is 64 bits wide, maybe we made some other mistake? Just abort, find the error and fix it.
  9. */
  10. void in (void * data, int size) {
  11. fatal_failure (data == NULL, "in: Failed to read from standard input, data is null pointer."); // This function is defined below, but we can call it here.
  12. fatal_failure (size == 0, "in: Failed to read from standard input, size is zero."); // That's because we declared it previously. Look at 'out' function.
  13. (void) read (STDIN_FILENO, data, (unsigned long int) size); // I cast to void type return value of read and write, because I don't really care about it.
  14. }
  15. /*
  16. Similar to 'in' function and read system call, write system call will store 'size' bytes from 'data' memory address into standard output, which is usually what you see in your
  17. terminal. Now, I won't talk much about teletypes, virtual terminals, file descriptor redirections and similar stuff, because I'm not very knowledgable about them. What matters is,
  18. you have a working operating system, terminal and compiler, and you can make things happen. Once you learn C better than me, and start writing your own multi-threaded kernel, core
  19. libraries, compilers and what not, you'll care about those things. I'll briefly talk about function structure for 'reallocate' function soon.
  20. */
  21. void out (void * data, int size) {
  22. fatal_failure (data == NULL, "out: Failed to write to standard output, data is null pointer."); // Notice how we can use function 'fatal_failure' before its' definition.
  23. fatal_failure (size == 0, "out: Failed to write to standard output, size is zero."); // That's because we declared it in 'chapter_0.h' header file.
  24. (void) write (STDOUT_FILENO, data, (unsigned long int) size);
  25. }
  26. /*
  27. Function 'echo' is just a simplification of function 'out', because we'll be using it a lot, notice that it must accept null terminated strings, which are sort of C-style thing. I
  28. really like them, because you don't need to always know size of the string in order to iterate it, but it requires some mental overhead in order to use them without creating hard
  29. to find bugs, which is why newer programming languages consider them unsafe. They're not unsafe, they need to be used like intended.
  30. */
  31. void echo (char * string) {
  32. out (string, string_length (string)); // This function fails when we pass a string that's not null terminated, and we don't care to check for errors...
  33. }
  34. void fatal_failure (int condition, char * message) { // We use this function to abort the program if condition is met and to print the message.
  35. if (condition == TRUE) { // If the variable 'condition' is not equal to 0, we execute the code in curly braces.
  36. echo ("[\033[1;31mExiting\033[0m] "); // Simply printing the message using our 'echo' function, but we also use some colours, more on that later.
  37. echo (message); // Also, notice how "this or that" is implicity 'char *' type... Maybe it's too early to explain it at this point.
  38. echo ("\n"); // This will only print a new line, we'll see how to use it later.
  39. exit (EXIT_FAILURE); // This is the function (and '_exit' system call) that aborts the program with a return code.
  40. } // If condition isn't met, function will just return, and nothing is printed, execution continues.
  41. }
  42. void limit (int * value, int minimum, int maximum) { // This is somewhat similar to limiting a variable to some values, inclusively, we'll use it later.
  43. if ( value == NULL) { return; } // We shouldn't dereference null pointer, but also don't want to abort the program for small mistake.
  44. if (* value <= minimum) { * value = minimum; } // You can also align similar consecutive statements like this, we'll see it more often in switch statement later on...
  45. if (* value >= maximum) { * value = maximum; } // If we pass a null pointer to this function, it won't do anything, just return.
  46. }
  47. /*
  48. Memory management is a whole new topic that's too complex to cover it now in details, and it's the source of most security vunrabilities and hidden bugs. For now, just remember
  49. that every program can read, write or execute only parts of the memory that the kernel allows it. Program can request new memory or release old memory, so some other programs can
  50. use it. We'll learn to use program called Valgrind to find and fix memory related bugs in later chapters. We rely on functions 'calloc', 'realloc' and 'free' from <stdlib.h>
  51. header file, and we'll avoid 'malloc', and use 'realloc' carefully, because they leave new memory uninitialized.
  52. We're internally using function 'calloc' to request new memory, function 'realloc' to enlarge existing memory and function 'free' to release old memory, data that won't be used
  53. later in the program. It's important to "free" all "malloc/calloc/realloc"-ed memory when program finishes successfully, and in some special cases, even when program fails and
  54. aborts. It's important for safety to do so, think of it like open and close braces, if you have some allocations, you should deallocate them later.
  55. Some examples of using them directly (not wrapping them like I like to do) are:
  56. @C
  57. char * data = NULL;
  58. data = malloc (20 * sizeof (* data)); // Allocates 20 bytes of memory for 'data'.
  59. data = calloc (20, sizeof (* data)); // Allocates 20 bytes also, but initializes them to 0 value.
  60. data = realloc (data, 20 * sizeof (* data)); // When 'data' is null pointer, it will be same as 'malloc', else it will reallocate more memory (for correct usage).
  61. // Also, it's best to just use 'calloc', but it complicates some other tasks.
  62. free (data); // Deallocates memory, we'll talk about "double free" later.
  63. @
  64. */
  65. void * allocate (int size) {
  66. char * data = NULL;
  67. data = calloc ((unsigned long int) size, sizeof (* data));
  68. fatal_failure (data == NULL, "standard : allocate : Failed to allocate memory, internal function 'calloc' returned null pointer.");
  69. return ((void *) data);
  70. }
  71. /*
  72. Now, lets see that code formatting in action, with briefly describing function structure in C programming language. Our function is called "reallocate", its' inputs (arguments)
  73. are "data" with type 'void *' (pointer to any type of memory address) and "size" with type 'int' (integer), and its' output is also 'void *' (some memory address). All code
  74. between first '{' and last connected '}' is part of that function. We're using function 'realloc' inside, but we check for error (it return 'NULL' on error), then we print message
  75. and abort the program if there was an error, it there wasn't, we return new enlarged chunk of memory, changing the "data" variable.
  76. */
  77. void * reallocate (void * data, int size) {
  78. data = realloc (data, (unsigned long int) size);
  79. fatal_failure (data == NULL, "standard : reallocate: Failed to reallocate memory, internal function 'realloc' returned null pointer.");
  80. return (data);
  81. }
  82. void * deallocate (void * data) {
  83. if (data != NULL) {
  84. free (data);
  85. }
  86. return (NULL);
  87. }
  88. /*
  89. This program is intended to be a book-like guide for this source code, which is also a book. We'll deal with strings a lot, and they're a good example of code formatting which is
  90. the main topic of chapter zero. In function 'string_length' we have for loop without a body, some people prefer to put '{}' or ';' in same or next line, to express the intention
  91. that the loop shouldn't have a body (code block {}). I just put ';' on the same line. Also, functions 'string_*' could depend on functions 'string_*_limit', but we won't do that
  92. now, and since we've already declared them in header file "chapter_0.h" we can define them and call them in whatever order we want. Nice.
  93. @C
  94. // Simple example of how we could make 'string_*' function dependable on 'string_*_limit' function...
  95. int string_compare (char * string_0, char * string_1) {
  96. return (string_compare_limit (string_0, string_1, string_length (string_0));
  97. }
  98. @
  99. */
  100. int string_length (char * string) {
  101. int length;
  102. fatal_failure (string == NULL, "string_length: String is null pointer."); // If variable 'string' is null pointer, we abort the program.
  103. for (length = 0; string [length] != CHARACTER_NULL; ++length); // In C, strings are null terminated, looping until we see null character is strings' length.
  104. return (length); // If we pass it non-null terminated string, program will fault!
  105. }
  106. /*
  107. Now, I've implemented "unlimited" versions of string comparison, copying and concatenation different from "limited" versions. They correspond with standard library functions
  108. 'strcmp', 'strcpy', 'strcat', 'strncmp', 'strncpy' and 'strncat' found in header file <string.h>. In "unlimited" versions, I rely on the fact that we want to apply the operation
  109. on entire strings, that those strings are null terminated and I used that in my advantage. For example, function 'string_compare' could be something like example below. Also,
  110. notice that 'destination / source' versus 'string_0 / string_1', which do you think is more readable?
  111. @C
  112. int string_compare (char * string_0, char * string_1) {
  113. int offset;
  114. fatal_failure (string_0 == NULL, "string_compare: Destination string is null pointer.");
  115. fatal_failure (string_1 == NULL, "string_compare: Source string is null pointer.");
  116. for (offset = 0; (string_0 [offset] != CHARACTER_NULL) && (string_1 [offset] != CHARACTER_NULL); ++offset) {
  117. if (string_0 [offset] != string_1 [offset]) {
  118. return (FALSE);
  119. }
  120. }
  121. return (TRUE);
  122. }
  123. @
  124. And I used this approach below to show that you can solve the problem using different solutions... You'll notice that "limited" versions have variable 'offset' of type integer. We
  125. use it to interate the strings, while in "unlimited" versions, we iterate on pointers to those strings, which are pushed to the stack. Both versions work, both versions give the
  126. same results, you can use any of them.
  127. */
  128. int string_compare (char * destination, char * source) {
  129. fatal_failure (destination == NULL, "string_compare: Destination string is null pointer."); // This will be seen in next 5 functions too, we don't want NULL here.
  130. fatal_failure (source == NULL, "string_compare: Source string is null pointer.");
  131. for (; (* destination != CHARACTER_NULL) && (* source != CHARACTER_NULL); ++destination, ++source) { // We iterate until either string reaches the null character.
  132. if (* destination != * source) { // In case that characters at the same offset are different:
  133. return (FALSE); // > We return FALSE, 0, since strings aren't the same...
  134. }
  135. }
  136. if (* destination != * source) { // Now, we'll do one last termination check.
  137. return (FALSE);
  138. }
  139. return (TRUE); // Otherwise, strings are same, we return TRUE, 1.
  140. }
  141. char * string_copy (char * destination, char * source) {
  142. char * result = destination; // We need to save pointer to destination string before changing it.
  143. fatal_failure (destination == NULL, "string_copy: Destination string is null pointer.");
  144. fatal_failure (source == NULL, "string_copy: Source string is null pointer.");
  145. for (; * source != CHARACTER_NULL; ++destination, ++source) { // This time and in next function, we iterate only source string.
  146. * destination = * source; // And we assign character at the same offset to destination string (aka copy it).
  147. }
  148. * destination = CHARACTER_NULL; // Copying null termination, since the loop stopped on that condition.
  149. return (result); // Lastly we return the destination string, in order to be able to bind functions.
  150. }
  151. char * string_concatenate (char * destination, char * source) {
  152. char * result = destination;
  153. fatal_failure (destination == NULL, "string_concatenate: Destination string is null pointer.");
  154. fatal_failure (source == NULL, "string_concatenate: Source string is null pointer.");
  155. destination += string_length (destination); // We'll first offset destination string to the end of it.
  156. // Because we want to start copying from the end, aka concatenate it.
  157. for (; * source != CHARACTER_NULL; ++destination, ++source) { // The rest of the function is same as string_copy, so:
  158. * destination = * source; // We could even use it here, but that defies the purpose of learning now.
  159. }
  160. * destination = CHARACTER_NULL; // Again, assign null termination.
  161. return (result);
  162. }
  163. char * string_reverse (char * string) { // Example of implementing "unlimited" version by calling "limited" version.
  164. return (string_reverse_limit (string, string_length (string)));
  165. }
  166. /*
  167. As for "limited" versions of previous 3 functions, they do the same thing, but are capped to some variable 'limit'. These functions have their own use-case, for example, if
  168. strings aren't null terminated, if you're not sure that they are null terminated, if we're dealing with binary (not textual) data (casted to char *), and many more cases. I won't
  169. write comments for 'string_copy_limit', 'string_concatenate_limit' and 'string_reverse_limit', try to read them and understand what kind of operation they'll perform with your
  170. current knowledge of C language.
  171. */
  172. int string_compare_limit (char * destination, char * source, int limit) {
  173. int offset;
  174. fatal_failure (destination == NULL, "string_compare_limit: Destination string is null pointer."); // This is the new trend, check for unimportant things.
  175. fatal_failure (source == NULL, "string_compare_limit: Source string is null pointer."); // At least this isn't too verbose. I hope...
  176. for (offset = 0; offset < limit; ++offset) { // Now, we'll iterate until 'limit' is reached, but it can overrun.
  177. if (destination [offset] != source [offset]) { // All said here applies to next two functions as well...
  178. return (FALSE); // As soon as 2 characters mismatch, they're not same, we return FALSE.
  179. }
  180. }
  181. return (TRUE); // Otherwise, we're reached the end, they're same, we return TRUE.
  182. }
  183. char * string_copy_limit (char * destination, char * source, int limit) {
  184. int offset;
  185. fatal_failure (destination == NULL, "string_copy_limit: Destination string is null pointer.");
  186. if ((limit <= 0) || (source == NULL)) {
  187. return (destination);
  188. }
  189. for (offset = 0; offset < limit; ++offset) {
  190. destination [offset] = source [offset];
  191. }
  192. return (destination);
  193. }
  194. char * string_concatenate_limit (char * destination, char * source, int limit) {
  195. int offset, destination_length, source_length;
  196. fatal_failure (destination == NULL, "string_concatenate_limit: Destination string is null pointer.");
  197. if ((limit <= 0) || (source == NULL)) {
  198. return (destination);
  199. }
  200. destination_length = string_length (destination);
  201. source_length = string_length (source);
  202. for (offset = 0; (offset < source_length) && (offset < limit); ++offset) {
  203. destination [destination_length + offset] = source [offset];
  204. }
  205. return (destination);
  206. }
  207. char * string_reverse_limit (char * string, int limit) {
  208. int i;
  209. fatal_failure (string == NULL, "string_reverse: String is null pointer.");
  210. for (i = 0; i < limit / 2; ++i) {
  211. char temporary = string [i];
  212. string [i] = string [limit - 1 - i];
  213. string [limit - 1 - i] = temporary;
  214. }
  215. return (string);
  216. }
  217. /*
  218. We'll use this function in many other chapters (in other C source files!), but we'll be careful, since compiler can't catch all the mistakes we make. Lets listen a story!
  219. Compiler likes you because you are his master. You tell him what to do (with passing flags as 'argv'), you give him the tool (your text files) and he'll do it. Sometimes he can
  220. complain, like "you gave me a shovel to chop some firewood" or "you gave me an axe to clean the leaves from the road", and he can't do that task. But if you give him a proper tool
  221. for proper task, he'll do it and won't complain at all. However, sometimes, you give him an imperfect tool (your C program full of subtle bugs) and he won't notice it. He'll do
  222. the job (translate bunch of ASCII characters into bunch of bytes), and say he's finished. Then you go out and see the results (run your executable), and it's all mess! You're like
  223. "What the hell, do as I say!", but he doesn't know what he did wrong... And in fact, it was your fault for giving him a imperfect tool all along. That's why we sometimes need more
  224. difficult to use servants. When you, as his master, tell him to do some job for you, he'll complain endlessly. You should use all your servants appropriately, each of them for
  225. different kind of task, and you'll learn to choose them wisely.
  226. Now, funny story aside, some languages are considered safe because they won't compile your code if they find any kind of syntax mistake. Ada is very strict programming language,
  227. we'll talk about it in later chapters, as Ada compilers complain a lot about the source code, but they can't validate incorrect algorythm. Pust is also very strict language, but
  228. it sucks, and it's unreadable pile of characters. Remember, no matter how strict language you use, it'll never validate correctness of the algorythm, only syntax mistakes and
  229. few other checks like life-times, bounds, etc. I'll mention this a lot, think twice, write once.
  230. Obedient servants:
  231. $ gcc -Wall
  232. $ clang -Wall
  233. Complicated servants:
  234. $ gcc -ansi -Werror -Wall -Wextra -Wpedantic
  235. $ clang -ansi -Werror -Weverything
  236. Terrible servants (same as above, but with also using):
  237. $ splint [custom flags]
  238. $ valgrind --show-leak-kinds=all --leak-check=full
  239. */
  240. char * string_realign (char * string, int amount, char character) { // Now, this is our "align string to right" function, lets explain it.
  241. int offset, length; // We're declaring two local (automatic) variables of type 'int'.
  242. length = string_length (string); // We'll use variable 'length' later in the code, so we initialize it to length of the string.
  243. for (offset = 0; offset != length; ++offset) { // We're essentially moving the string to the right, iterating through its' length to amount.
  244. string [amount - offset - 1] = string [length - offset - 1]; // Needless to say, string needs to have enough memory ((pre) allocated) for it to store it.
  245. }
  246. for (offset = 0; offset != amount - length; ++offset) { // Now, we have some "garbage" data left from the actual string, so we iterate through left side and:
  247. string [offset] = character; // Assign to it argument 'character' that we provided in a function call. We can align with anything.
  248. }
  249. string [amount] = CHARACTER_NULL; // I like to null terminate them explicitly, so I don't have to worry about tiny bugs later.
  250. return (string); // Lastly, we return a pointer to our modified string, in order to, again, bind function calls.
  251. }
  252. /*
  253. Ignore what next two functions do, it's about memory stuff that we'll cover in later chapters.
  254. */
  255. int memory_compare (void * destination, void * source, int length) {
  256. int offset;
  257. char * cast_0 = (char *) destination;
  258. char * cast_1 = (char *) source;
  259. fatal_failure (destination == NULL, "memory_compare: Memory is null pointer.");
  260. if (source == NULL) {
  261. return (FALSE);
  262. }
  263. for (offset = 0; offset != length; ++offset) {
  264. if (cast_0 [offset] != cast_1 [offset]) {
  265. return (FALSE);
  266. }
  267. }
  268. return (TRUE);
  269. }
  270. void memory_copy (void * destination, void * source, int length) {
  271. int offset;
  272. char * cast_0 = (char *) destination;
  273. char * cast_1 = (char *) source;
  274. fatal_failure (destination == NULL, "memory_copy: Memory is null pointer.");
  275. if (source == NULL) {
  276. return;
  277. }
  278. for (offset = 0; offset != length; ++offset) {
  279. cast_0 [offset] = cast_1 [offset];
  280. }
  281. }
  282. /*
  283. Again, please consider these 'terminal_*' functions some form of black magic... For now, just take a look at how I format the code in them.
  284. */
  285. void terminal_clear (void) {
  286. echo ("\033[2J\033[H");
  287. }
  288. void terminal_colour (int colour, int effect) {
  289. char format [8] = "\033[ ;3 m";
  290. format [2] = (char) (effect % EFFECT_COUNT) + '0';
  291. format [5] = (char) (colour % COLOUR_COUNT) + '0';
  292. echo (format);
  293. }
  294. void terminal_cancel (void) {
  295. echo ("\033[0m");
  296. }
  297. void terminal_show_cursor (int show) {
  298. if (show != 0) {
  299. echo ("\033[?25h");
  300. } else {
  301. echo ("\033[?25l");
  302. }
  303. }
  304. #endif