Q: How can the document know the size of paper it is being typeset on?
Traditional TeX doesn't know the papersize. The pagebox is positioned to the point 1in from left, 1in from top of hypothetical paper: left/upper corner of the pagebox is here shifted by \hoffset right (or left, if negative) and \voffset down (or up if negative). This point (1in,1in left,top) is an origin of the typesetting of traditional TeX regardless of the actual papersize. May be the actual papersize can be smaller than pagebox and you'll not see all typesetting without any overfull box warnings.
pdfTeX is able to set the media size (i.e. papersize) by \pdfpageheight and \pdfpagewidth. The origin of the typesetting mentioned above as 1in,1in is possible to change in pdfTeX by \pdfhorigin and \pdfvorigin (they are set to 1in,1in by default).
If you set \pdfpagewidth then you can calculate \hsize as \pdfpagewidth minus left margin minus right margin. Moreover you have to set the sum of \pdfhorigin plus \hoffset as the amount of the left margin. The analogical princile is applicable for vertical margins.
The registers mentioned above have to be set before \shipout (shipping out the page). They can be changed to another values for another pages.
Edit: PostScript language uses different origin of its default coordinate system than TeX: 0,0 left,bottom of the paper. This implies that dvitops convertor needs to set the new origin and it needs to know the actual paper height. The paper width is irrelevant for this need. Moreover PostScript can set the media size by setpagedevice operator (4.11 in Redbook). The dvitops convertor can get the data about media size from \special or from command line or from configuration file. The data are used by setpagedevice operator in dvitops output.
The PostScript or PDF documents have the media size set. When this document is printed on the printer with different media size of paper sheets loaded in the printer then printer warns or makes trouble to the user.
\hsizeis set for letter format minus 2in in plain TeX. – wipet Jun 09 '14 at 17:29