From the company's profits.
When you buy a company, you own a piece of it. The price of a stock theoretically reflects how much profit you expect the company to earn.
In a simple scenario, the company keeps all of its profits in a bank somewhere. The company's value then goes up because you own a share of that money. You'd expect the price to go up to reflect that increased value. You would sell it at a higher price, and it would be a positive-sum game.
In reality it's more complicated. Most companies would re-invest that money so that they'll make even more money in the future. The stock price will reflect how well you expect the company to grow and earn more. It's still a positive-sum game, just with more uncertainty.
It's even more complicated than that, for a lot of reasons. But at the core, it's a positive-sum game, not a zero-sum game.
(At least until the point where people are throwing so much money at the stock market that the prices have nothing to do with a reasonable assessment of uncertainty. And there's a decent chance that this is true today. But long term, such irrational exuberance tends to crash, and over enough time the two mostly cancel out.)