Hamilton's fastest lap of one minute 38.755 seconds was three tenths of a second quicker than Rosberg.
It was Hamilton's 12th pole position of the season - a personal record - as opposed to Rosberg's eight. Both drivers are locked on nine race wins apiece, however.
Massa's Williams team mate Valtteri Bottas just missed out on the final part of qualifying. He will start 11th, ahead of Jenson Button - another driver retiring after this weekend - Esteban Gutierrez, and Romain Grosjean.
Jolyon Palmer and Manor's Pascal Wehrlein were the final two drivers in the second session, while Daniil Kvyat, who has endured a torrid weekend so far, Kevin Magnussen, Felipe Nasr, Esteban Ocon, Carlos Sainz, and Marcus Ericsson went out in the first part of qualifying.
Bahrain International Circuit - Winter testing