Apparently the oxygen product can be considered a "waste," a pollutant in the early atmosphere emitted by the first photosynthetic organisms such as cyanobacteria. Although recent research also points to processes involving elements such as manganese, as shown in the article published in Proceedings of the National Academy of Sciences (PNAS) titled "Manganese-oxidizing photosynthesis before the rise of cyanobacteria".
Water exists throughout the universe, see for example the first link.
You'll find a lot of information about the Earth in the second link:
"The water, equivalent to 140 trillion times all the water in the world's ocean, surrounds a huge, feeding black hole, called a quasar, more than 12 billion light-years away."
Water and oxygen exist on other planets but are locked away in minerals. Liquid water is more tricky as it requires to be released (via volcanic action) and retained (combination of gravity and temperature). Smaller Mars has no volcanoes and not enough gravity to hold on to it in the atmosphere. meanwhile it seems to be in it's rocks.
Old AGB stars actually produce oxygen via nuclear burning in it's interior which it can dredge up and blow off as carbon monoxide, water and part of minerals in dust. In fact this is probably what planets and comets condensate out of later when the gas and dust collect together in giant molecular dust clouds.