WASHINGTON — The U.S. Secret Service is investigating how a gunman armed with an AR-style rifle was able to get close enough to shoot and injure former President Donald Trump at a rally Saturday in Pennsylvania, in a devastating failure of one of the agency’s core duties.

The FBI identified the shooter Sunday as Thomas Matthew Crooks, 20, of Bethel Park, Pennsylvania.

The gunman, who officials said was killed by Secret Service personnel, fired multiple shots at the stage from an “elevated position outside of the rally venue,” the agency said.

An Associated Press analysis of more than a dozen videos and photos taken at the Trump rally, as well as satellite imagery of the site, shows the shooter was able to get astonishingly close to the stage where the former president was speaking.

A video posted to social media and geolocated by the AP shows Crooks’ body lying motionless on the roof of a manufacturing plant just north of the Butler Farm Show grounds, where Trump’s rally was. A different image shows Crooks wearing a gray T-shirt with a black U.S. flag on the right arm, with a bloody wound to his head.

The roof was fewer than 164 yards from where Trump was speaking, a distance from which a decent marksman could reasonably hit a human-size target. The AR-style rifle, like that of the gunman at the Trump rally, is the semiautomatic civilian version of the military M16.

President Joe Biden said Sunday that he has directed an independent review of the security at the rally.

Biden urged Americans not to make assumptions about the motive of the shooter.

The Secret Service did not have a speaker Saturday night at a news conference where FBI and Pennsylvania State Police officials briefed reporters on the shooting investigation.

Former top Secret Service agents told the AP that Crooks should never have been allowed to gain access to the roof, and the agency will have to figure out how that happened.

They said such a lapse could have been caused by officers neglecting their posts or a flaw in the event’s security plan.

The agency is “going to have to go through the security plan and interview a number of people from the director on down” to figure out what went wrong, said Stephen Colo, who retired in 2003 as an assistant director after a 27-year career in the service.

The FBI said it will lead the investigation into the shooting, working with the Secret Service and local and state law enforcement.