{"id":7303,"date":"2012-06-22T07:00:00","date_gmt":"2012-06-22T07:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/2012\/06\/22\/how-did-real-mode-windows-fix-up-jumps-to-functions-that-got-discarded\/"},"modified":"2012-06-22T07:00:00","modified_gmt":"2012-06-22T07:00:00","slug":"how-did-real-mode-windows-fix-up-jumps-to-functions-that-got-discarded","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20120622-00\/?p=7303\/","title":{"rendered":"How did real-mode Windows fix up jumps to functions that got discarded?"},"content":{"rendered":"<p>\nIn a discussion of how real-mode Windows\n<a HREF=\"http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2011\/03\/16\/10141735.aspx\">\nwalked stacks<\/a>,\ncommenter Matt wonders\n<a HREF=\"http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2011\/03\/16\/10141735.aspx#10142248\">\nabout fixing jumps in the rest of the code to the discarded functions<\/a>.\n<\/p>\n<p>\nI noted in the original article that\n&#8220;there are multiple parts to the solution&#8221;\nand that stack-walking was just one piece.\nToday, we&#8217;ll look at another piece:\nInter-segment fixups.\n<\/p>\n<p>\nRecall that real-mode Windows ran on an 8086 processor,\na simple processor with no memory manager, no CPU privilege levels,\nand no concept of task switching.\nMemory management in real-mode Windows was handled manually by\nthe real-mode kernel,\nand the way it managed memory was by loading code from disk\non demand, and discarding code when under memory pressure.\n(It didn&#8217;t discard data because it wouldn&#8217;t know how to regenerate it,\nand it can&#8217;t swap it out because there was no swap file.)\n<\/p>\n<p>\nThere were a few flags you could attach to a segment.\nOf interest for today&#8217;s discussion are <i>movable<\/i>\n(and it was spelled without the &#8220;e&#8221;)\nand <i>discardable<\/i>.\nIf a segment was not movable (known as <i>fixed<\/i>),\nthen it was loaded into memory and stayed there until the\nmodule was unloaded.\nIf a segment was movable, then the memory manager was allowed\nto move it around when it needed to defragment memory in order\nto satisfy a large memory allocation.\nAnd if a segment was discardable,\nthen it could even be evicted from memory\nto make room for other stuff.\n<\/p>\n<table BORDER=\"1\" STYLE=\"border-collapse: collapse\" CELLPADDING=\"3\">\n<tr>\n<th>Movable<\/th>\n<th>Discardable<\/th>\n<th>Meaning<\/th>\n<\/tr>\n<tr>\n<td>No<\/td>\n<td>No<\/td>\n<td>Cannot be moved or discarded<\/td>\n<\/tr>\n<tr>\n<td>No<\/td>\n<td>Yes<\/td>\n<td>(invalid combination)<\/td>\n<\/tr>\n<tr>\n<td>Yes<\/td>\n<td>No<\/td>\n<td>Can be moved in memory<\/td>\n<\/tr>\n<tr>\n<td>Yes<\/td>\n<td>Yes<\/td>\n<td>Can be moved or purged from memory<\/td>\n<\/tr>\n<\/table>\n<p>\nI&#8217;m going to combine the movable and discardable cases,\nsince the effect is the same for the purpose of\ntoday&#8217;s discussion,\nthe difference being that with discardable memory,\nyou also have the option of throwing the memory out entirely.\n<\/p>\n<p>\nFirst of all, let&#8217;s get the easy part out of the way.\nIf you had an intra-segment call\n(calling a function in your own segment),\nthen there was no work that needed to be done.\nReal-mode Windows always discarded full segments,\nso if your segment was running code,\nit was by definition present,\nand therefore any other code in that segment was also present.\nThe hard part is the inter-segment calls.\n<\/p>\n<p>\nAs it happens,\n<a HREF=\"http:\/\/support.microsoft.com\/kb\/65122\">\nan old document on the 16-bit Windows executable file format<\/a>\ngives you some insight into how things worked,\nif you sit down and puzzle it out hard enough.\n<\/p>\n<p>\nLet&#8217;s start with the <code>GetProcAddress<\/code> function.\nWhen you call <code>GetProcAddress<\/code>, the kernel needs\nto locate the address of the function inside the target module.\nThe loader consults the <i>Entry Table<\/i> to find the function\nyou&#8217;re asking for.\nAs you can see, there are three types of entries in the\nEntry Table.\nUnused entries (representing ordinals with no associated function),\nfixed segment entries, and movable segment entries.\nObviously, if the match is in an unused entry, the return value\nis <code>NULL<\/code> because there is no such function.\nIf the match is in a fixed entry, that&#8217;s pretty easy too:\nLook up the segment number in the target module&#8217;s segment list\nand combine it with the specified offset.\nSince the segment is fixed, you can just return the raw pointer\ndirectly, since the code will never move.\n<\/p>\n<p>\nThe tricky part is if the function is in a movable segment.\nIf you look at the document, it says that &#8220;a moveable segment entry\nis 6 bytes long and has the following format.&#8221;\nIt starts with a byte of flags (not important here),\na two-byte <code>INT&nbsp;3Fh<\/code> instruction,\na one-byte segment number, and the offset within the segment.\n<\/p>\n<p>\nWhat&#8217;s the deal with the\n<code>INT&nbsp;3Fh<\/code> instruction?\nIt seems rather pointless to specify that a file format\nrequires some <code>INT&nbsp;3Fh<\/code> instructions\nscattered here and there.\nWhy not get rid of it to save some space in the file?\n<\/p>\n<p>\nIf you called <code>GetProcAddress<\/code> and the result\nwas a function in a movable segment,\nthe <code>GetProcAddress<\/code> didn&#8217;t actually return the\naddress of the target function.\nIt returned the address of the <code>INT&nbsp;3Fh<\/code> instruction!\n(Thankfully, the Entry Table is always a fixed segment,\nso we don&#8217;t have to worry about the Entry Table itself being discarded.)\n<\/p>\n<p>\n(Now you see why the file format includes these strange\n<code>INT&nbsp;3Fh<\/code> instructions:\nThe file format was designed to be loaded directly\ninto memory.\nWhen the loader loads the entry table,\nit just slurps it into memory and bingo, it&#8217;s ready to go,\n<code>INT&nbsp;3Fh<\/code> instructions and all!)\n<\/p>\n<p>\nSince <code>GetProcAddress<\/code> returned the address of the\n<code>INT&nbsp;3Fh<\/code> instruction,\ncalls to imported functions didn&#8217;t actually go straight\nto the target.\nInstead, you called the <code>INT&nbsp;3Fh<\/code> instruction,\nand it was the\n<code>INT&nbsp;3Fh<\/code> handler which said,\n&#8220;Gosh, somebody is trying to call code in another segment.\nIs that segment loaded?&#8221;\nIt took the return address of the interrupt and used it to\nlocate the segment number and offset.\nIf the segment in question was already in memory,\nthen the handler jumped straight to the segment at the\nspecified offset.\nYou got the function call you wanted, just in a roundabout way.\n<\/p>\n<p>\nIf the segment wasn&#8217;t loaded, then the\n<code>INT&nbsp;3Fh<\/code> handler loaded it\n(which might trigger a round of discarding\nand consequent\n<a HREF=\"http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2011\/03\/16\/10141735.aspx\">\nstack patching<\/a>),\nthen jumped to the newly-loaded segment at the specified offset.\nAn even more roundabout function call.\n<\/p>\n<p>\nOkay, so that&#8217;s the case where a function pointer is obtained\nby calling <code>GetProcAddress<\/code>.\nBut it turns out that a lot of stuff inside the kernel turns into\n<code>GetProcAddress<\/code> at the end of the day.\n<\/p>\n<p>\nSuppose you have some code that calls a function in another\nsegment within the same module.\nAs we saw earlier, fixups are\n<a HREF=\"http:\/\/blogs.msdn.com\/b\/oldnewthing\/archive\/2006\/07\/17\/668284.aspx\">\nthreaded through the code segment<\/a>,\nand if you scroll down to the\n<i>Per Segment Data<\/i> section of that old document,\nyou&#8217;ll see a description of the way the relocation records\nare expressed.\nA call to a function to a segment within the same module\nrequires an <code>INTERNALREF<\/code> fixup,\nand as you can see in the document, there are two types of\n<code>INTERNALREF<\/code> fixups, ones which refer to fixed\nsegments and ones which refer to movable segments.\n<\/p>\n<p>\nThe easy case is a reference to a fixed segment.\nIn that case, the kernel can just look up where it put that\nsegment, add in the offset, and patch that address into the\ncode segment.\nSince it&#8217;s a fixed segment, the patch will never have to be\nrevisited.\n<\/p>\n<p>\nThe hard case is a reference to a movable segment.\nIn that case, you can see that the associated information in the\nfixup table is the &#8220;ordinal number index into [the] Entry Table.&#8221;\n<\/p>\n<p>\nAha, you now realize that the Entry Table is more than just a list\nof your exported functions.\nIt&#8217;s also a list of all the functions in movable segments that\nare called from other segments.\nIn a sense, these are &#8220;secret exports&#8221; in your module.\n(However, you can&#8217;t get to them by <code>GetProcAddress<\/code>\nbecause\n<code>GetProcAddress<\/code> knows how to keep a secret.)\n<\/p>\n<p>\nTo fix up a reference to a function in a movable segment,\nthe kernel calls the <code>SecretGetProcAddress<\/code> (not its real name)\nfunction, which as we saw before, returns not the actual function pointer\nbut rather a pointer to the magic <code>INT&nbsp;3Fh<\/code> in the\nEntry Table.\nIt is that pointer which is patched into your code segment,\nso that when your code calls what it thinks is a function in\nanother segment,\nit&#8217;s really calling the Entry Table,\nwhich as we saw before, loads the code in the target segment if necessary\nbefore jumping to it.\n<\/p>\n<p>\nMatt wrote,\n&#8220;If the kernel wants to discard that procedure,\nit has to find that jump address in my code,\nand redirect it to a page fault handler,\nso that when my process gets to it,\nit will call the procedure and fault the code back in.\nHow does it find all of the references to that function across the program,\nso that it can patch them all up?&#8221;\nNow you know the answer:\nIt finds all of those references because it already had to find them\nwhen applying fixups.\nIt doesn&#8217;t try to find them at discard time;\nit finds them when it loads your segment.\n(Exercise:\nWhy doesn&#8217;t it need to reapply fixups when a segment moves?)\n<\/p>\n<p>\nAll inter-segment function pointers were really pointers into the\nEntry Table.\nYou passed a function pointer to be used as a callback?\nNot really; you really passed a pointer to your own Entry Table.\nYou have an array of function pointers?\nNot really; you really have an array of pointers into your Entry Table.\nIt wasn&#8217;t actually hard for the kernel to find all of these\nbecause you had to declare them in your fixup table in the first place.\n<\/p>\n<p>\nIt is my understanding that the <code>INT&nbsp;3Fh<\/code> trick\ncame from the overlay manager which was included with\nthe Microsoft&nbsp;C compiler.\n(The\n<a HREF=\"http:\/\/www.digitalmars.com\/ctg\/vcm.html\">\nZortech C compiler<\/a> followed a similar model.)\n<\/p>\n<p>\n<b>Note<\/b>:\nWhile the above discussion describes how things worked\n<i>in principle<\/i>,\nthere are in fact a few places where the actual\nimplementation differs from the description above,\nalthough not in any way that fundamentally affects the design.\n<\/p>\n<p>\nFor example, real-mode Windows did a bit of optimization\nin the <code>INT 3Fh<\/code> stubs.\nIf the target segment was in memory,\nthen it replaced the <code>INT 3Fh<\/code> instruction\nwith a direct <code>jmp xxxx:yyyy<\/code> to the target,\neffectively precalculating the jump destination when a segment\nis loaded rather than performing the calculation each time\na function in that segment is called.\n<\/p>\n<p>\nBy an amazing coincidence, the code sequence\n<\/p>\n<pre>\n    int 3fh\n    db  entry_segment\n    dw  entry_offset\n<\/pre>\n<p>\nis five bytes long, which is the exact length\nof a <code>jmp xxxx:yyyy<\/code> instruction.\nPhew, the patch just barely fits!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In a discussion of how real-mode Windows walked stacks, commenter Matt wonders about fixing jumps in the rest of the code to the discarded functions. I noted in the original article that &#8220;there are multiple parts to the solution&#8221; and that stack-walking was just one piece. Today, we&#8217;ll look at another piece: Inter-segment fixups. Recall [&hellip;]<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[2],"class_list":["post-7303","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-history"],"acf":[],"blog_post_summary":"<p>In a discussion of how real-mode Windows walked stacks, commenter Matt wonders about fixing jumps in the rest of the code to the discarded functions. I noted in the original article that &#8220;there are multiple parts to the solution&#8221; and that stack-walking was just one piece. Today, we&#8217;ll look at another piece: Inter-segment fixups. Recall [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/7303","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=7303"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/7303\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=7303"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=7303"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=7303"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}