foreign episode 4 topic today printing stuff but anyway more importantly do you guys ever use this utility called cat basically it lets you print stuff to the screen um yeah it works just fine the problem is if you use it you're officially a boomer because there's a better version that we just made a couple days ago I made called Nyan Cat which is the same thing in every way only it's like 30 less legible because everything is rainbow colors so if you want to see how that works we'll talk about that in this video as well as everything that goes into it and the cool thing is is that I think the Linux version of cat it's like 140 000 bytes this one is like 800 or less and we didn't even code golf that's just what it comes out to be so if that interests you check it out uh at the end of the video so let's go through the very short the slides I have and so first thing and pretty much the only thing that we're going to cover is this uh right syscall and if you can't see this on the bottom right that's the 105. but basically the way this works is on Linux and Bs diggers or write syscall where you pass it in a file descriptor that could be either screen like the console or you're gonna pass in standard out or it could be an actual file that you've already opened so you can write bytes to that file this character array buffer in RSI that is kind of the address for your memory is that you want to be printing and and then uh number of bytes in that array so it also prints out it returns I should say the number of bytes that it wrote if you care about that I don't really care about that about you uh so let's you want to print out a nine byte string address 1942 what you do is you'd pass in the file scripter for the output in RDI you'd pass in the the address in RSI you'd pass in the number of bytes in RDX you pass in the syscall ID in RX execute the sysical that's how the process works very simple and that's what we're going to do in this video but we're going to make a function to do it for us thanks plank um but I want to speak about this call a little bit more closely because I have to make an apology video I'd make this kind of video so soon but we gotta apologize I apologize that the FreeBSD devs are almost as dumb as I am that's my apology uh yeah so basically I never came across this because I always use system 5 API in which case this is not a problem but when you assume that all registers are being preserved across every function call like we are in the series with our own Abi this matters and so what the problem is is that in Linux when you call a syscall it collabors rcx and R11 why that is I mean it makes sense it has to preserve certain things it has to use those registers for certain things Bond FreeBSD they also clobber R8 R9 and r10 at least as far as I can tell that's what they clobber in addition it could be more I have no idea I have to check that but either way I put a listing in the syscall ASM for both FreeBSD and Linux that has an OS dependent macro basically called sys push Sysco Club collaborate registers and says pop registers and so basically on previously when you execute this macro it will push rcx R8 R9 or 10 and 11 to the stack and then pop them off in reverse order and on Linux it will only it will only push the you know outer two not this and not this so yeah I changed the code to reflect that if I figure out that there's actually more registers that are going to be clobbered in Linux for BSD I will adjust these macros accordingly and here's how that process works for one of the uh programs that we're going to actually be using today and we use in the previous video file open basically you remember I I had sets of pushes and Pops above and below the main code body where I was just saving all the registers that were going to be clobbered in this case I'm just executing that macro CIS push and sys pop so very simple at this point we're pretty much done with the slideshow I'm just going to get right into the code so I want to first show you kind of the motivation for this so I have four examples here let's start with example uh B that's what I was just talking about so let me open up this stuff and so yeah all we're including here is exit and the syscall listing that will give us the the variables like standard out and it's just right that we need to execute this this code so what I've got here ignore the commented out parts that's for a little a later bit basically we're doing what I just said we're moving that file descriptor into RDI we're moving the text address here's the the text that we're going to be printing out that address is going to be in RSI now here you'd put an RDX the number of bytes if you're too lazy like I am to count this 22 bytes what you can do is you can just um compute that with nasm so what you can do is you can actually subtract text that address from address after text and that would give you the number of bytes between the two so you can use this to kind of count strings for you if you're too lazy to count them yourself um and then removing the CIS right column to Rex calling syscall and if you execute this it prints out the string to the screen so we're done with our video thanks for watching just kidding if we go back and I want to uncomment out those lines I want to show you something as you would expect this is a loop so we start with R15 as a million every time we go around the loop we decrement and we jump back to the top of the loop until we get to zero in which case we exit so let's just run that and you can see it's printing out a bunch of random nonsense of the screen it was pretty quick um but that's not the issue on Linux you have a command called s trace on BSD it's called truss you can actually um count the number of ciscolls being executed by a program with Dash C oh now it's even slower you know the time it takes is always different you know I don't know why I think it's because the console is a bunch of voodoo magic sometimes this is actually faster okay anyway you can see here that there's a million calls to the right syscall I'm not sure why it's not telling us about the exit but oh well a million calls to write which is what we expect we did that Loop a million times but here's the thing if I go back into this other example example a and look at what's in here this was the C version of the same thing this is just printf a million times so you would expect this to also be doing a million syscalls right We're looping a Million Times Printing the same exact string so if we if we run this I should have trust it might not do that oh I know why you can see here obviously the Boomers got involved a bunch of this crap as well like I O control and f-stat and memory map or whatever who cares but look at the right row only 5372. calls to the rights this call we had a million how did they get away with only five thousand well my friends let's see so we did hold on let me put this out let me get the more sig figs here so we did a million sys calls and each of those strings was 22 bytes and somehow it managed to only do that in five thousand 372.
write calls hmm very curious does that number make any Impressions on you does that mean anything to you 50 or sorry 409 5. 3 yeah is that is that not basically 2 to the 12th I think what's going on is they're buffering it I have no idea I didn't look this up but I'm guessing that they're buffering the output in other words they're filling up a buffer with their strings until it gets to 4K and the one hits 4K it flushes the buffer and let me show you how I think that's working in the last slide here I could be wrong about this but what we just did in our assembly code was we were writing one not one letter at a time but one string at a time right we're writing that 22 by string out three times or in a one e six times and that was a lot of CIS calls and that was slow what I think they're doing in C is that they're basically putting those strings in a buffer and then their auto flush that buffer whenever it's full but then at the end of the program they're also pushing the buffer and maybe on new lines they're also you know flushing their buffer as well sorry this says faster so yeah it's fuses calls it executes more quickly so why don't we do that and we will and we will so let me go to the third example buffered rights let's take a look at the code and also let's take a look at the um to let's look at this one hold on pretty cars hold on so second one as well live I uh print I have two functions here one is print characters and one is print string look at all three Also let's look at the um print buffer flush I should have prepared this beforehand okay and so in this code it is very much the same thing except we're not going to do the assist call in a loop we're going to be using this print characters function instead which we're including here by the way the Align this align thing basically means whenever it basically will align that code to a number of bytes so this will align into 16 byte boundary which is a little bit faster when you're calling functions many many many times that's why I have aligned this print character's function so whenever we jump to that it will go a little bit faster and also you can see I've aligned the loop there's some pros and cons to doing that but I align the loop itself so every time we jump to the top of the loop it also is a bit faster just approach it there anyway um let's take a look at these other two functions that uh we're using here so they actually have three there's print cars printering and then there's print buffer flush which I'm not including but it's being included by print cares so that's fine so in print cares this is basically kind of a wrapper function to write things out to the to the buffer and then to the standard app actually I think I'll first start in the print buffer flush actually no screw that let's start in the actual code you can see I'm not playing this video at all I have at the top a third directive here which is now print buffer size 4096 just like it was in C on this machine and so what we're doing in our headers is before where we had these two quad words one was code size indicating that the size of our binary on the hard drive and this was size of the binary in memory once the program loads it up I've added this value so now let's say the code was 200 bytes long on the hard drive now when it loads up it will be 4296 bytes in memory and only these bytes will be in the first 200 and then sorry all these bytes of numbers 100 and then down here where it says print buffer at the end of the software there'll be an extra 4 000 96 bytes that will all be zeros hopefully at runtime so that's the idea that's kind of the idea of you know using a print buffer this is like having a dynamically allocated memory sort of because it's not gonna it's not a variable that we're defining a priori so in the print buffer flush array this kind of manages that Vector that 4K Vector in memory and all it does is well obviously it does some pushing and popping to say registers but it pretty much just manages is manages that buffer and so it has its own variable a global variable mind you remember if it has a dot in front that would be a like a local variable or a local address this is actually a global uh variable that we can access and it just can it just can encodes the number of bytes that we've written to our buffer array so let's say we had one of those strings from before it was 22 bytes whenever we print it it would increment this value here by 22 and once we break 4096 this writes and so you can see this is the most fundamental of of things this literally just this is like that right this call from the beginning this moves the address into RSI moves a number of bytes which is accessed at that Global you know variable location it moves this is right into Rex executes this call and then it resets the value in this location so it's very straightforward how this works I'm going to close that because it's uh boring now I've got two other functions here uh print cars and print string and all they do is what I just showed you before I'm not going to go through the code in detail you can take a look at how it works but basically it is just loading inputs from the input array into the buffer array it's loading RDX of those inputs into the buffer array and then it's checking if we have reached the maximum size of the array and whenever we have it flushes it so this will automatically flush the array every time the buffer is full so it's very simple then it pops the registers back and leaves and the last thing I wanted to show was this print string now this is the same exact command except that you can see it has two well sorry one fewer arguments only two arguments again it takes the file descriptor and an address to memory but this involves null terminated character arrays I mentioned those in the previous video this is whenever you have an array that you don't have a length of necessarily but it ends with the null byte it ends with a zero byte so this way you can just write out a string that you don't know what it is beforehand as long as it ends with a zero you you can tell how long it is so this requires one less input and all it does you kind of can see it just counts the number of bytes you see here in RDX and then it executes print cars itself so it's just a wrapper for the previous function that counts the number of bytes in the string before it calls that function so it does some work for you I would never use this unless you didn't know a string beforehand I don't like string formatting like prints like printf and stuff because you do you're making the computer do work at runtime that you could have done beforehand so there's no reason to do that so in this case you know this is just for like strings that you don't know let's say it's a user input let's say it's from a file you know or whatever that's when I would use this particular uh function that's that now let's look at the code that calls it so this is the same code as the previous example again we're moving centered out to RDI we're moving the text address into RSI we're moving the length of the string into RDX and We're looping a million times and you can see we're in this loop we're calling print characters we're decrementing our counter variable R15 by one each time when that hits zero we fall out of the loop otherwise we keep looping and once that Loop's done I'm showing in the other example in which case we're using that second function that print string and this is an alternated text so down here you can see I have two pieces of text I have the old sample text as well as I have this one this one's basically a new line character the word done another new line character and then zero bytes you could also do a slash zero to encode a null byte in this as well one tip I have for you is that when you're using these slash ends make sure you use those like back ticks and not regular quotes sometimes they break so if you honestly use the back ticks these are the top left of my keyboard you can handle uh fancy inputs like slash n and slash zero and slash r or whatever um more easily anyway yeah this line basically just moves that address into RSI and calls the null terminated print function that we just made and lastly the thing that we have to do that we didn't have to do and see is that whenever we end our program we have to make sure we flush the buffer because we have no way otherwise to do that let's say the buffer is only half full it will when you're done with the program that will not have flushed so you'll be you'll be losing 2048 bytes worth of valuable information that you didn't print out so whenever you end your program you have to make sure to print to flush the print buffer before you leave so this is what that's doing it flushes the buffer automatically or I should say uh like uh manually and then it exits the program before you know okay so let's run that one see it's printing a bunch of stuff and see it print out done the more important than that let's actually look at the number of assist calls here you can see there's a 5372 syscalls just like there was in C so we've implemented this the same way that's C did same size buffer and everything but actually if you wanted to go in and you want to change this buffer you can change this buffer let's say you want to make it uh prices big that works let's trust it you can see we have half half this syscalls so you can change that value very quickly and Recon you know recompile and re-execute your code all right with that out of the way we'll get into our final example which was the Nyan Cat this one's a little bit more complicated I'm going to take a while to go through maybe I'll just skip the hard parts I think I will skip the hard parts in this case there's another value here so I'm using a print buffer size of 128 bytes and I'll still read about for 128. again you could change these numbers to whatever you want I just kept them the same just for the you know example here now this means we have more memory to Define we have another buffer to work with why are we doing this because number cap function that was taking bytes from a file and putting them to the screen so we have to be able to take we're going to buffer our input as well as the output and so if you look here remember it used to be just code size plus print buffer size in this case we're adding another buffer which is read buffer size so we'll have the size of our code in Ram plus 128 bytes of zeros plus 128 bytes of zeros when this is loaded into memory and at the very bottom of this you can see I have the print buffer at the end of the program and then you can say I have the read buffer which is just offset from the print buffer by the size of the print buffer so if you grow the print buffer rebuffer will shift down in memory when this thing is loaded not not in real time but you know before you you have to compile that but yeah this basically will automatically look at itself in the right location per the size that you give for your read buffer okay let's talk about how this works so there's a lot of inputs into this program and again includes are literally just copy and pasted from other files so we are copying and pasting let's just call this thing depending if you're on Linux or BST you're putting different values in here they're all like nasm like macros and and other syntactical things um we have a function called file open I think I covered that in the previous video as well as print cars we also have print and see formatting this is how you do uh colors why don't I open that really quick as well um yeah that's important actually so in this case it's just a bunch of Define so I'm defining these different things I have ANC clear screen and see reset and see bold all the different colors they're actually more colors I just picked the cool ones and um basically all it does is based off your input you input the file descriptor and the number of the ANSI color or format that you want to put in let's say you want your code to be you want your prints to be cyanic color bright cyan you pass in 25 or you can just pass in the string and see bright cyan into RSI execute this code and it will print the proper escape code to color your um text out and if you care how that works at the very bottom you kind of can see how the Escape codes work at least how I'm implementing them you have this slash e bracket this these two bytes mean it's an Escape Code then you have either two bytes or three bytes worth of values for formatting or colors and this basically prints those out if you're curious to check the code in the slight Hub suppository so back to the match here that's a print cars that's the printing prank function then there's running that prints out the colors recars this is basically um just a wrapper for the sys read command that reads values from an address in uh or sorry from a file descriptor into a buffer in this case the read buffer and then we have our or our flush buffer function and our exit function so everything you should understand as far as includes go that'll be instructions so we're using what we did in the previous video to get the command line argument so remember we have to take in a file remember we're printing out a file to the screen so we have to take out the file you know out of the command line argument so in this case we're checking from the previous video the RC it has to be two if it's not just leave the program call it a day you've had enough work uh you can't forget how to use the software don't bother if you did pass into though you won't jump to fail and so now we're going to access that second location in the argument that is the the path to the file and we're going to open that with file open the only thing that's important here is that we're opening the file but we're saving that file descriptor in R8 now R8 would normally be a good place to save something because that's a that's not a call a save register that's that will that would lose its value if you're running with the system 5 API but because we're using our own API we can use any register we want because all registers are saved across function calls I guess they should be then I'm using the low three bits of RBX to refer to the color of the rainbow so we're using seven rainbow colors here are at the bottom of this file I'm using the rainbows defined as the stock colors that is ANSI red and the yellow yellow is actually orange on my computer maybe it's more gallery on your computer but on mine it's orange and bright yellow is more like a yellow color Then followed by Green cyan blue magenta and then like pink that's kind of the rainbow I'm going for here and uh basically we're using RBX to access the low three bits so zero would be here one two three four five six and seven and once you make it back around to eight you're gonna get rid of those High values and go back to zero that's kind of how I'm accessing them the uh the rainbow here okay so that's that now we have two Loops we have an outer loop which just fills the buffer from reading the file so basically we're going to constantly keep pulling 128 bytes from that input file over and over and over and over again in this in this Loop so this just basically does that it uh it moves that file descriptor value into RDI um moves that buffer location that we have at the bottom of our code into RSI so it knows where to write the write the bytes of memory to then it reads the buffer it puts rebuffer size the 128 evaluated RDX and it's going to keep reading 128 bytes over and over and over again and what we're doing is actually in this case we're saving that return value which would be an Rax into R15 and that basically what we're saving is the number of bytes read and that should be 128 every single time whenever you read should be 128 except for two times that would be when you get to the end of the file and there's only like seven bytes left it will return seven because it only read seven new bytes it didn't read 128 bytes I read the last seven bytes of the file before the file ended and then when you get to the end of the file it will return obviously zero so the way this works is I'm this Loop is valid for a number of bytes read greater than zero once once we get the zero bytes returned jump to done we're done reading bytes we're done with the whole program that's how the program terminates because we jump to done and at the bottom done basically is you can see here flush the print buffer and then return zero to the to the console okay that's the Outer Loop now the inner loop is where all the work gets done so at this point remember we have a full buffer ideally that's 128 bytes of new things to print and the first thing we do is we print the color so we always start off with I guess red for each new line but you can see at the top here we set RBX to zero so that will refer to red um so basically what this does is it puts centered out into the RDI file descriptor then it kind of computes the address of actually it puts the the ANSI color value into RSI zero extended that's what this means here it means all the leading values you know the high values are zeros above the the low byte and we print out the formatting so this will print out it will make everything this makes everything after it read but we're only going to print one byte at a time so we'll only make the next byte red then Loop would go next slide will be orange then the loop will go next time will be yellow etc etc so after it makes the next color it does the next character so in this case it's just taking um the next byte from the read buffer and printing it out and you can see here we use R9 to track that location so every time this Loop starts this inner loop we set R9 to zero and so that's the start of the read buffer and so basically we're going to go to the the first bite that buffer and print it out standard out using the print cars function so one byte at a time gets printed at least it gets put in the print buffer not printed to the screen but put in the print buffer that we're going to eventually flush when it fills automatically or manually at the end of the program and so there's two things to keep track of there is B RBX which is the kind of the offset we're using into the rainbow as well as R9 which is the number of bytes that we are in our print in our read buffer and so I'll skip this part for a second here and show you this part so every time we write out one letter we're going to increment RBX in this case just the low the low byte of RBX by one so we're going to go from zero to one one to two Etc then we're going to throw away whatever is not in the low three bits by using and bl7 that only keeps the last three right seven and x's and binary is one one so this just keeps the last three bits and then it increments R9 as well so this will keep pushing us one by four in the rainbow and one by four in the read buffer okay and then this last bit of code here before I get to the you know fancy bits is that whenever we get to a new line we reset to Red I want all the Reds to line up all the oranges to line up all the yellows to line up as we go left to right so this basically just checks if we have a new line character the new line ASCII value is 10.