  We measure the stellar mass function (SMF) of galaxies in the COSMOS field up
to $z\sim6$. We select them in the near-IR bands of the COSMOS2015 catalogue,
which includes ultra-deep photometry from UltraVISTA-DR2, SPLASH, and
Subaru/Hyper-SuprimeCam. At $z>2.5$ we use new precise photometric redshifts
with error $\sigma_z=0.03(1+z)$ and an outlier fraction of $12\%$, estimated by
means of the unique spectroscopic sample of COSMOS. The increased exposure time
in the DR2, along with our panchromatic detection strategy, allow us to improve
the stellar mass completeness at high $z$ with respect to previous UltraVISTA
catalogues. We also identify passive galaxies through a robust colour-colour
selection, extending their SMF estimate up to $z=4$. Our work provides a
comprehensive view of galaxy stellar mass assembly between $z=0.1$ and 6, for
the first time using consistent estimates across the entire redshift range. We
fit these measurements with a Schechter function, correcting for Eddington
bias. We compare the SMF fit with the halo mass function predicted from
$\Lambda$CDM simulations. We find that at $z>3$ both functions decline with a
similar slope in the high-mass end. This feature could be explained assuming
that the mechanisms that quench star formation in massive haloes become less
effective at high redshift; however further work needs to be done to confirm
this scenario. Concerning the SMF low-mass end, it shows a progressive
steepening as moving towards higher redshifts, with $\alpha$ decreasing from
$-1.47_{-0.02}^{+0.02}$ at $z\simeq0.1$ to $-2.11_{-0.13}^{+0.30}$ at
$z\simeq5$. This slope depends on the characterisation of the observational
uncertainties, which is crucial to properly remove the Eddington bias. We show
that there is currently no consensus on the method to quantify such errors:
different error models result in different best-fit Schechter parameters.
[Abridged]
